Resource Meta-Arguments: count
You'll learn how to create multiple identical resources using a single resource block with the count meta-argument.
What Is Count?
When you need multiple copies of the same resource—like five virtual machines or three storage buckets—you don't want to copy-paste the same resource block five times. The count meta-argument lets you specify how many instances of a resource to create, and Terraform handles the rest.
Think of it like a copy machine: instead of manually feeding five sheets one-by-one, you set the counter to 5 and press start once.
How Count Works
Add count to any resource block with an integer value:
resource "aws_instance" "web_server" {
count = 3
ami = "ami-12345678"
instance_type = "t2.micro"
}
This creates three EC2 instances instead of one.
Using count.index
Each instance needs something unique—otherwise they'd be exact duplicates. Use count.index to reference the current instance number (starting from 0):
resource "aws_s3_bucket" "data" {
count = 4
bucket = "my-app-data-${count.index}"
}
This creates buckets named: my-app-data-0, my-app-data-1, my-app-data-2, my-app-data-3.
Referencing Count Resources
When you reference a resource with count, Terraform treats it as a list. Access specific instances with bracket notation:
output "first_bucket" {
value = aws_s3_bucket.data[0].bucket
}
Key Takeaway: Use count to create multiple resource instances from a single block, and reference count.index to give each instance unique attributes—turning one configuration into many resources efficiently.