terraform-provider-hcloud icon indicating copy to clipboard operation
terraform-provider-hcloud copied to clipboard

[Feature]: Have firewall rules as separate resources so they can be created using for_each

Open michaelniemand opened this issue 2 years ago • 1 comments

What whould you like to see?

Maybe I'm misunderstanding something; so apologies if that's the case:

I'm writing a module that creates a standalone server including firewall and rules. In my vars, I want to pass firewall rules as a map and then create the rules dynamically using for_each like so:

variable "firewall_rules" {
  type = map(any)
  default = {

    "icmp_in_allowed" = {
      direction = "in"
      protocol = "icmp"
      port = ""
      source_ips = [  
        "0.0.0.0/0",
        "::/0"
      ]      
    }

    "ssh_in_allowed" = {
      direction = "in"
      protocol = "tcp"
      port = "22"
      source_ips = [  
        "0.0.0.0/0",
        "::/0"
      ]      
    }

    "https_in_allowed" = {
      direction = "in"
      protocol = "tcp"
      port = "443"
      source_ips = [  
        "0.0.0.0/0",
        "::/0"
      ]      
    }

  }
}

Now for_each is only allowed on the resource level, so creating 1 firewall with as many rules as there are keys in my map is not possible. My only option would be to create a new firewall for each rule with just one rule per firewall instead of one firewall with multiple rules. Is this intended?

michaelniemand avatar Aug 23 '22 08:08 michaelniemand

@michaelniemand , If I understand you correctly, you probably need something like this:

resource "hcloud_firewall" "public_web_ssh" {
  name = "public 22/443 and icmp"

  dynamic "rule" {
    for_each = var.firewall_rules
    content {
      description = rule.key
      direction   = rule.value.direction
      protocol    = rule.value.protocol
      source_ips  = rule.value.source_ips
      port        = rule.value.protocol == "icmp" ? null : rule.value.port
    }
  }
}

b8dmin avatar Sep 13 '22 20:09 b8dmin

The suggestion by @cital is right for this need.

Going to close the issue as the problem has been solved. If you still have issues, please feel free to reopen the issue or to create a new one.

apricote avatar Nov 23 '22 13:11 apricote