alphatango165
alphatango165

Reputation: 85

Terraform: Iterating a resources over multiple values?

I'm testing the PAN-OS provider from Palo Alto networks, with the goal of configuring a firewall as-code. I can easily make a security policy:

resource "panos_security_policy" "security_policy" {
    rule {
        name = var.name
        source_zones = var.source_zones
        source_addresses = var.source_addresses
        source_users = var.source_users
        destination_zones = var.destination_zones
        destination_addresses = var.destination_addresses
        applications = var.applications
        services = var.services
        categories = var.categories
        action = var.action
    }
}

I have 50+ rules that will need to be managed this way. I could brute-force each rule as an individual resource, or I could use a module with mapped values. But both of those seem like a lot of manual work and hard to maintain. Any ideas for the most efficient way to iterate this resource over a set of values? Anyone who has had to manage a large AWS security group with lots of rules may know of something.

Upvotes: 0

Views: 173

Answers (1)

Riann Selegar
Riann Selegar

Reputation: 21

You can use a for_each loop, e.g.

for_each = { for k, v in var.rules : k => v }

name = each.key
source_zones = each.value.source_zones
source_addresses = each.value.source_addresses
source_users = each.value.source_users
...

on variables file:

rules = {
    rulename1 = {
      source_zones   = "foo"
      source_address = "bar"
      source_users   = "baz"
    }
    rulename2 = {
      source_zones   = "foo"
      source_address = "biz"
      source_users   = "buz"
    }
  }

Make sure to read this if you need further details.

Upvotes: 2

Related Questions