Goal

2 Subnets → subnet-0, subnet-1
4 EC2 instances → 2 in each subnet

subnet-0 → ec2-0, ec2-2
subnet-1 → ec2-1, ec2-3

New Concept: element() and %

element()

element(list, index)  # picks item from list at given index
element(["subnet-0", "subnet-1"], 0)  # subnet-0
element(["subnet-0", "subnet-1"], 1)  # subnet-1
element(["subnet-0", "subnet-1"], 2)  # subnet-0 (wraps around!)
element(["subnet-0", "subnet-1"], 3)  # subnet-1 (wraps around!)

element() wraps around - if index goes beyond list size, it starts from beginning again.

% (modulo)

count.index % length(subnets)

index 0 % 2 = 0  → subnet-0
index 1 % 2 = 1  → subnet-1
index 2 % 2 = 0  → subnet-0
index 3 % 2 = 1  → subnet-1

Modulo gives the remainder — keeps cycling through subnet indexes.


Complete Code

locals {
  project = "project-01"
}

# Create VPC
resource "aws_vpc" "my-vpc" {
  cidr_block = "10.0.0.0/16"
  tags = {
    Name = "${local.project}-vpc"
  }
}

# Create 2 Subnets using count
resource "aws_subnet" "main" {
  vpc_id     = aws_vpc.my-vpc.id
  count      = 2
  cidr_block = "10.0.${count.index}.0/24"

  tags = {
    Name = "${local.project}-subnet-${count.index}"
  }
}

# Create 4 EC2 instances - 2 in each subnet
resource "aws_instance" "name" {
  ami           = "ami-0c83cb1c664994bbd"
  instance_type = "t3.micro"
  count         = 4

  # element() picks subnet by wrapping count.index over subnet list
  # % makes sure index stays within subnet count (0 or 1)
  subnet_id = element(aws_subnet.main[*].id, count.index % length(aws_subnet.main))

  tags = {
    Name = "${local.project}-instance-${count.index}"
  }
}

How subnet_id is Assigned

aws_subnet.main[*].id  →  ["subnet-id-0", "subnet-id-1"]

count.index % length(aws_subnet.main)
= count.index % 2

instance-0 → 0 % 2 = 0 → element(list, 0) → subnet-0
instance-1 → 1 % 2 = 1 → element(list, 1) → subnet-1
instance-2 → 2 % 2 = 0 → element(list, 0) → subnet-0
instance-3 → 3 % 2 = 1 → element(list, 1) → subnet-1

Result:

subnet-0 → instance-0, instance-2
subnet-1 → instance-1, instance-3