Search code examples
stringazuretuplesterraformazure-rm

Terraform flatten tuple to set of string


I have the following terraform allowed_ips tuple which contains a json of ip address and metadata about each ip. I am trying to flatten the tuple, to get a list of ip addresses in the format ["2.2.2.2", "3.3.3.3"] will then be passed to ip_rules variable

Variable

allowed_ips = [
    {
      name       = "ip1"
      ip_address = "3.3.3.3"
    },
    {

      name       = "ip2"
      ip_address = "127.0.0.1"
    }
  ]


Resource

variable "allowed_ips" {
  type = list(object({
    name       = string,
    priority   = string,
    ip_address = string
  }))
}

network_acls {
    default_action = "Deny"
    bypass         = "AzureServices"

    ip_rules =  jsonencode(var.allowed_ips.*.ip_address)
  }

When I set ip_rules = ["2.2.2.2", "3.3.3.3"] rules are created without issue but I would like somehow parse the variable from the allowed_ips above.

I have tried various ways including

  • jsonencode(var.allowed_ips.*.ip_address)
  • "${join("\\,", local.subnets.*.id)}"
  • iterating via a foreach,

Unfortunately most of the solutions throw an error Inappropriate value for attribute "ip_rules": set of string required.

Any help will be appreciated


Solution

  • You can use a simple for loop to create a set:

    ip_rules = [for i in var.allowed_ips : i.ip_address]