4

I have a use case where I have set variable instance_count = 3 and I have 2 Private_subnets which is a list ["subnet-id-A", "subnet-id-B"], what I want my terraform code to dynamically generate a local map or list which can be like this

subnets = {
01 = subnet-id-A
02 = subnet-id-B
03 = subnet-id-A
}
OR
subnets = ["subnet-id-A","subnet-id-B","subnet-id-A"]

If the instance count goes to 4 it can be like this

subnets = {
01 = subnet-id-A
02 = subnet-id-B
03 = subnet-id-A
04 = subnet-id-B
}
OR
subnets = ["subnet-id-A","subnet-id-B","subnet-id-A","subnet-id-B"]

If the instance count goes to 2 it can be like this

subnets = {
01 = subnet-id-A
02 = subnet-id-B
}
OR
subnets = ["subnet-id-A","subnet-id-B"]
suleman
  • 41
  • 2
  • 1
    Instead of generating an actual list, is using the modulo operator (something equivalent to `subnet_id = local.subnets[count.index % length(local.subnets)]`) an acceptable solution? – Kaustubh Khavnekar Jan 17 '22 at 16:30
  • @KaustubhKhavnekar this was useful , however, I have used element(var.subnet_ids,each.value - 1) to launch the ec2's in separate AZ. As the element function handles the indexes beautifully and we never go out of the index, no matter how big the count is the EC2 serves will be launched into the separate subnet, selection of subnets will be round robin. – suleman Jan 18 '22 at 16:56

1 Answers1

0

Subnet_ids is a list that contains all the private subnets.

Here is the code

locals {
 formatted_count = [for index in range(var.instance_count) : format("0%s", index + 1)]
 instances_count = toset(local.formatted_count)
}
   module "ec2" {
   for_each                    = local.instances_count
   source                      = "terraform-aws-modules/ec2-instance/aws"
   version                     = "3.2.0"
   name                        = var.name
   ami                         = var.ami
   instance_type               = var.instance_type
   key_name                    = var.key_name
   monitoring                  = var.monitoring
   tags                        = var.tags
   vpc_security_group_ids      = var.vpc_security_group_ids
   subnet_id                   = element(var.subnet_ids,each.value - 1)
   }
suleman
  • 41
  • 2