skip to Main Content

Issue

I have a variable that is to be used to generate EC2 launch templates and a variable for a list of availability zones to use. I want the blocks inside the launch template variable to designate details around the implementation, and I want the code to create a launch template PER az (so that I can properly configure the network interface blocks). But I don’t want the to require an ec2 configuration block for each AZ (I would like it to be dynamic)

Is there a way to loop over the availability zone list, generate a new map (per map in the launch template configuration) for each AZ and inject the AZ as a key in said map??

Code Blocks

# Some code redacted for brevity
module "env_spinup" {
  availability_zones        = ["az-1", "az-2"]
  ec2_groups = {
    main_ec2_group = {
      instance_count        = 1
      extra_security_groups = []
      root_volume_size      = 200
      extra_tags            = {}
      management_allow_list = {}
    }
  }
}

Desired output for the ec2_groups argument (parsed into local):

ec2_groups = {
    main_ec2_group_az1 = {
      az                    = "az-1"
      instance_count        = 1
      extra_security_groups = []
      root_volume_size      = 200
      extra_tags            = {}
      management_allow_list = {}
    }
    main_ec2_group_az2 = {
      az                    = "az-2"
      instance_count        = 1
      extra_security_groups = []
      root_volume_size      = 200
      extra_tags            = {}
      management_allow_list = {}
    }
  }

2

Answers


  1. You can accomplish this using a simple for expression:

    locals {
      availability_zones = ["az-1", "az-2"]
    
      ec2_groups = {
        for az in local.availability_zones : "main_ec2_group_${az}" => {
          az                    = az
          instance_count        = 1
          extra_security_groups = []
          root_volume_size      = 200
          extra_tags            = {}
          management_allow_list = {}
        }
      }
    }
    

    This produces:

      + ec2_groups = {
          + main_ec2_group_az-1 = {
              + az                    = "az-1"
              + extra_security_groups = []
              + extra_tags            = {}
              + instance_count        = 1
              + management_allow_list = {}
              + root_volume_size      = 200
            }
          + main_ec2_group_az-2 = {
              + az                    = "az-2"
              + extra_security_groups = []
              + extra_tags            = {}
              + instance_count        = 1
              + management_allow_list = {}
              + root_volume_size      = 200
            }
        }
    
    Login or Signup to reply.
  2. I ended up using https://www.terraform.io/language/functions/setproduct to generate a list of instances, mapped to az’s.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search