Terraform flatten tuple to set of string
Asked Answered
E

2

6

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

Exodontics answered 1/9, 2021 at 15:19 Comment(0)
D
7

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

ip_rules = [for i in var.allowed_ips : i.ip_address]
Diastema answered 1/9, 2021 at 15:40 Comment(0)
J
1

It seems like the ip_rules argument is expecting a value of type set(string). If you wish to use the allowed_ips variable, you should be able to do something like the following:

ip_rules = toset(var.allowed_ips[*].ip_address)

The jsonencode function will encode the given value to a string, which is not the type that the ip_rules argument expects. The same can be said for the join function since its return value is of type string.

Jupon answered 1/9, 2021 at 15:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.