Launch EC2 servers in multiple subnets using count with terraform

Viewed 334

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"]
1 Answers

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)
   }
Related