How to Use Count in Terraform: Simple Guide with Examples
In Terraform,
count is a meta-argument that lets you create multiple instances of a resource or module by specifying how many copies you want. You add count = number inside a resource block, and Terraform will create that many identical resources with indexes starting at zero.Syntax
The count argument is placed inside a resource or module block. It accepts a number that tells Terraform how many copies of that resource to create. Each instance can be accessed using count.index, which starts at 0 and increments by 1 for each copy.
- count: Number of instances to create.
- count.index: The current instance number (0-based).
terraform
resource "aws_instance" "example" { count = 3 ami = "ami-12345678" instance_type = "t2.micro" tags = { Name = "example-${count.index}" } }
Example
This example creates three AWS EC2 instances with unique names using count. Each instance gets a tag with its index number, so you can tell them apart.
terraform
provider "aws" { region = "us-east-1" } resource "aws_instance" "example" { count = 3 ami = "ami-0c55b159cbfafe1f0" instance_type = "t2.micro" tags = { Name = "example-instance-${count.index}" } }
Output
Apply complete! Resources: 3 added, 0 changed, 0 destroyed.
Outputs:
aws_instance.example[0]: created
aws_instance.example[1]: created
aws_instance.example[2]: created
Common Pitfalls
Common mistakes when using count include:
- Using
countwith resources that do not support it. - Not using
count.indexto differentiate instances, causing naming conflicts. - Changing
countvalues can cause resource replacement, so plan carefully.
Example of a wrong and right way to use count:
terraform
resource "aws_instance" "wrong" { count = 2 ami = "ami-12345678" instance_type = "t2.micro" tags = { Name = "duplicate-name" } } resource "aws_instance" "right" { count = 2 ami = "ami-12345678" instance_type = "t2.micro" tags = { Name = "unique-name-${count.index}" } }
Quick Reference
| Term | Description |
|---|---|
| count | Number of resource instances to create |
| count.index | Current instance index starting at 0 |
| Use with care | Changing count can recreate resources |
| Works with | Most resource and module blocks |
| Common use | Create multiple similar resources easily |
Key Takeaways
Use
count to create multiple resource instances by specifying a number.Access each instance with
count.index to give unique names or settings.Changing
count can cause resource replacement; plan changes carefully.Not all resources support
count, so check documentation before use.Use
count to simplify and reduce repeated code in Terraform configurations.