Count vs for_each decision in Terraform - Performance Comparison
When using Terraform, we often create multiple resources using either count or for_each. Understanding how the time to apply changes grows helps us choose the best method.
We want to know how the number of resources affects the number of API calls and provisioning steps.
Analyze the time complexity of creating multiple resources using count.
resource "aws_instance" "example" {
count = var.instance_count
ami = var.ami_id
instance_type = "t2.micro"
}
This code creates a number of AWS instances equal to var.instance_count using count.
Each instance creation triggers similar operations.
- Primary operation: API call to create one AWS instance resource.
- How many times: Exactly once per instance, so
var.instance_counttimes.
As you increase the number of instances, the number of API calls grows directly with it.
| Input Size (n) | Approx. API Calls/Operations |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The number of API calls grows linearly as you add more instances.
Time Complexity: O(n)
This means the time to create resources grows directly in proportion to how many you create.
[X] Wrong: "Using count or for_each changes the total number of API calls needed."
[OK] Correct: Both methods create one resource per item, so the total API calls scale the same way with the number of resources.
Understanding how resource creation scales helps you design infrastructure that grows predictably. This skill shows you can think about costs and performance in real cloud projects.
"What if we used a module that internally creates multiple resources per item? How would that affect the time complexity?"