Format Count and for_each Resources

Format Terraform resources using count and for_each meta-arguments with proper alignment of dynamic references, conditional expressions, and map lookups.

Resources

Detailed Explanation

Formatting count and for_each

The count and for_each meta-arguments enable creating multiple instances of a resource. Formatting these correctly is important because the dynamic references (count.index, each.key, each.value) appear throughout the block.

count Example

resource "aws_subnet" "private" {
  count = length(var.private_subnet_cidrs)

  vpc_id            = aws_vpc.main.id
  cidr_block        = var.private_subnet_cidrs[count.index]
  availability_zone = var.availability_zones[count.index]

  tags = {
    Name = "private-subnet-${count.index}"
    Type = "private"
    AZ   = var.availability_zones[count.index]
  }
}

for_each with Map Example

resource "aws_iam_user" "team" {
  for_each = toset(var.team_members)

  name          = each.value
  path          = "/team/"
  force_destroy = true

  tags = {
    Team      = "engineering"
    ManagedBy = "terraform"
  }
}

resource "aws_s3_bucket" "environments" {
  for_each = {
    dev     = "us-east-1"
    staging = "us-east-1"
    prod    = "us-west-2"
  }

  bucket = "myapp-${each.key}-assets"

  tags = {
    Environment = each.key
    Region      = each.value
  }
}

Formatting Conventions

  • Meta-argument first: count or for_each is always the first attribute in the block, separated by a blank line from other attributes
  • Consistent references: count.index, each.key, and each.value references are kept on the same line as the attribute they populate
  • Inline maps: When for_each uses an inline map, keys are aligned within the map block
  • Tag alignment: Tags that mix static and dynamic values still have their equals signs aligned

Use Case

Creating multiple similar resources like subnets, IAM users, or S3 buckets from lists or maps, where consistent formatting clarifies the dynamic resource generation pattern.

Try It — Terraform HCL Formatter

Open full tool