Search code examples
terraformterraform-provider-aws

Terraform: Merge two tuples/lists to create a map


I would like to know how I can create a map from two lists/tuples. To put the question in context, I've got a variable that holds the subnet IDs and another variable that holds the availability zone IDs for the subnets. Now I want a variable (a map of Zone ID to Subnet ID ) which will create the below result:

locals {
  subnet_ids = aws_subnet.tf_subnet.*.id
  az-info = aws_subnet.tf_subnet.*.availability_zone_id
}

az-info = [
  "use2-az1",
  "use2-az2",
  "use2-az3",
]
subnet_ids = [
  "subnet-07045e06d7f8a34d5",
  "subnet-0a2eead3a90c2f9e5",
  "subnet-0ef0d8fce5dd017ae",
]

subnets_to_privatelink = {
use2-az1 = subnet-07045e06d7f8a34d5
use2-az1 = subnet-0a2eead3a90c2f9e5
use2-az1 = subnet-0ef0d8fce5dd017ae
}

Any help is greatly appreciated.


Solution

  • The operation you've described is called zipmap in the Terraform language:

    zipmap(local.az-info, local.subnet_ids)
    

    Of course, if you do this then it's important to ensure that the order of elements is consistent between these two sequences, or else the keys and values won't match properly. That's true in your case because they are both derived from the elements of aws_subnet.tf_subnet, but I mention it just because others might find this question in future and try to apply this answer in a different situation.


    A different way to achieve this result would be to use a for expression over the aws_subnet.tf_subnet value directly:

    tomap({
      for sn in aws_subnet.tf_subnet :
      sn.availability_zone_id => sn.id
    })
    

    This avoids the need for the intermediate lists and ensures that the relationships between availability zones and subnet ids will always be preserved correctly, because both the key and the value of each element are being derived from the same sn object.