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
You can accomplish this using a simple
for
expression:This produces:
I ended up using https://www.terraform.io/language/functions/setproduct to generate a list of instances, mapped to az’s.