Declarative vs imperative IaC in Terraform - Performance Comparison
We want to understand how the number of steps grows when using declarative or imperative infrastructure code.
Which approach takes more repeated actions as the infrastructure grows?
Analyze the time complexity of creating multiple resources using declarative Terraform code.
resource "aws_instance" "example" {
count = var.instance_count
ami = "ami-123456"
instance_type = "t2.micro"
}
This code creates a number of virtual machines equal to instance_count in a declarative way.
Look at what happens repeatedly when this code runs.
- Primary operation: Creating each virtual machine resource via API calls.
- How many times: Once per instance, so as many times as
instance_count.
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 work grows evenly as you add more resources.
Time Complexity: O(n)
This means the time to create resources grows directly with the number of resources you want.
[X] Wrong: "Declarative code runs all steps only once no matter how many resources."
[OK] Correct: Each resource still requires its own API call and provisioning, so the total work grows with the number of resources.
Understanding how resource count affects execution helps you explain infrastructure scaling clearly and confidently.
"What if we used a loop in imperative code to create resources one by one? How would the time complexity compare?"