ZiGGi
ZiGGi

Reputation: 3

Terraform and complex variables

I am using the "Hetzner" provider with Terraform.
My plan is to have something like this in fx .auto.tfvars :

fw_openings = [
   {
      port = "22",
      protocol = "tcp",
      subnet = "100.100.100.100/32"
   },
   {
      port = "80",
      protocol = "tcp",
      subnet = "0.0.0.0/0"
   }
]

Based on the fw_openings I would like to generate something like this:

resource "hcloud_firewall" "firewall" {
   rule {
      direction = "in"
      protocol = "tcp"
      port = "22"
      source_ips = [
         "100.100.100.100/32"
      ]
   }
   rule {
      direction = "in"
      protocol = "tcp"
      port = "80"
      source_ips = [
         "0.0.0.0/0"
      ]
   }
}

I'm sure it's possible (since it seems very trivial). But I seem to keep tripping over the looping options with Terraform.
What would be the proper solution?

Upvotes: 0

Views: 139

Answers (1)

Marcin
Marcin

Reputation: 238121

You can use dynamic blocks:

resource "hcloud_firewall" "firewall" {
   dynamic "rule" {
   
      for_each = var.fw_openings
   
      content {
            direction = "in"
            protocol = rule.value.protocol
            port = rule.value.port
            source_ips = [
                rule.value.subnet
            ]
        }
   }
}

Upvotes: 2

Related Questions