count

The count meta-argument creates multiple copies of a resource from a single block.

Syntaxcount = 3

The count meta-argument makes Terraform create a numbered set of identical resources from one block. Inside the block, count.index gives the current index (starting at 0).

Addressing counted resources

Counted resources become a list: aws_instance.web[0], aws_instance.web[1], and so on.

count as an on/off switch

Setting count = var.enabled ? 1 : 0 conditionally creates a resource or not.

Example

Example · hcl
resource "aws_instance" "web" {
  count         = 3
  ami           = "ami-0c02fb55956c7d316"
  instance_type = "t3.micro"

  tags = {
    Name = "web-${count.index}"
  }
}

# References: aws_instance.web[0], aws_instance.web[1], aws_instance.web[2]

When to use it

  • A team creates three identical worker EC2 instances by setting count = 3 on a single resource block instead of copying the block three times.
  • An engineer uses count = var.environment == 'production' ? 3 : 1 to deploy three instances in production and one in dev from the same configuration.
  • A configuration uses count.index to number each instance uniquely, naming them worker-0, worker-1, worker-2 from a single resource block.

More examples

Create multiple instances with count

Creates three EC2 instances from one resource block, using count.index to give each a unique name.

Example · hcl
resource "aws_instance" "worker" {
  count         = 3
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t3.micro"

  tags = {
    Name = "worker-${count.index}"
  }
}

Reference a counted resource

Shows how count creates indexed resource addresses and how to reference individual or all instances using splat expressions.

Example · bash
# After apply, count creates a list of instances
terraform state list
# aws_instance.worker[0]
# aws_instance.worker[1]
# aws_instance.worker[2]

# Access one instance in outputs
# value = aws_instance.worker[0].public_ip

# Access all public IPs
# value = aws_instance.worker[*].public_ip

Conditional resource with count

Uses count = 0 or 1 as a boolean toggle to optionally create a bastion host based on a variable flag.

Example · hcl
variable "enable_bastion" {
  type    = bool
  default = false
}

resource "aws_instance" "bastion" {
  count         = var.enable_bastion ? 1 : 0
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t3.nano"

  tags = { Name = "bastion" }
}

Discussion

  • Be the first to comment on this lesson.