Terraform – Note to Self

Get list of all possible combination, from multiple lists

> setproduct(["a","b","c"],["x","y"])

tolist([
  [
    "a",
    "x",
  ],
  [
    "a",
    "y",
  ],
  [
    "b",
    "x",
  ],
  [
    "b",
    "y",
  ],
  [
    "c",
    "x",
  ],
  [
    "c",
    "y",
  ],
])

Find the index of a list, where it’s sub attribute contains certain value

Sometimes, you really wish terraform have something like jq…

PS: Suggestions

Example following Azure VPN Gateway BGP Settings is a list.

Need to retrieve the ASN number where the tunnel IP address is matching known public IP.

Hence need to get the index of the list, where the tunnel IP address is matching known public IP

> azurerm_virtual_network_gateway.this.bgp_settings
tolist([
  {
    "asn" = 65010
    "peer_weight" = 0
    "peering_addresses" = tolist([
      {
        "apipa_addresses" = tolist([])
        "default_addresses" = tolist([
          "10.0.10.4",
        ])
        "ip_configuration_name" = "vnetGatewayConfig1"
        "tunnel_ip_addresses" = tolist([
          "20.163.152.123",
        ])
      },
      {
        "apipa_addresses" = tolist([])
        "default_addresses" = tolist([
          "10.0.10.5",
        ])
        "ip_configuration_name" = "vnetGatewayConfig2"
        "tunnel_ip_addresses" = tolist([
          "20.163.152.137",
        ])
      },
    ])
  },
])

Reference idea

locals {
  objList = [
    { name = "Chris" },
    { name = "Dan" }
  ]

  # splat expression index lookup
  myObjIndexSplat = index(local.objList.*.name, "Dan")

  # for expression index lookup
  myObjIndexFor = index([for v in local.objList : v.name], "Dan")
}

Actual code breakdown:

Getting the list of tunnel IP address

> [for v in azurerm_virtual_network_gateway.this.bgp_settings: flatten(v.peering_addresses[*].tunnel_ip_addresses)]
[
  [
    "20.163.152.123",
    "20.163.152.137",
  ],
]

Check if the list contains certain public IP

> [for v in azurerm_virtual_network_gateway.this.bgp_settings: contains(flatten(v.peering_addresses[*].tunnel_ip_addresses),"20.163.152.123")]
[
  true,
]

Getting the index

> index([for v in azurerm_virtual_network_gateway.this.bgp_settings: contains(flatten(v.peering_addresses[*].tunnel_ip_addresses),"20.163.152.123")],true)
0

Getting the ASN number

> azurerm_virtual_network_gateway.this.bgp_settings[index([for v in azurerm_virtual_network_gateway.this.bgp_settings: contains(flatten(v.peering_addresses[*].tunnel_ip_addresses),"20.163.152.123")],true)].asn
65010

Leave a Reply

Your email address will not be published. Required fields are marked *