Connection blocks for SSH in Terraform - Time & Space Complexity
When Terraform uses connection blocks for SSH, it needs to connect to each resource to run commands or provision. We want to understand how the time to complete these connections grows as we add more resources.
How does the number of SSH connections affect the total execution time?
Analyze the time complexity of the following Terraform connection block usage.
resource "aws_instance" "example" {
count = var.instance_count
ami = "ami-123456"
instance_type = "t2.micro"
connection {
type = "ssh"
user = "ec2-user"
private_key = file("~/.ssh/id_rsa")
host = self.public_ip
}
provisioner "remote-exec" {
inline = ["echo Hello World"]
}
}
This code creates multiple AWS instances and connects to each via SSH to run a command.
Identify the API calls, resource provisioning, data transfers that repeat.
- Primary operation: Establishing an SSH connection and running remote commands on each instance.
- How many times: Once per instance created (equal to
var.instance_count).
Each new instance requires a separate SSH connection and command execution. So, the total time grows directly with the number of instances.
| Input Size (n) | Approx. Api Calls/Operations |
|---|---|
| 10 | 10 SSH connections and command runs |
| 100 | 100 SSH connections and command runs |
| 1000 | 1000 SSH connections and command runs |
Pattern observation: The number of SSH operations increases linearly as the number of instances increases.
Time Complexity: O(n)
This means the total time to complete all SSH connections and commands grows directly in proportion to the number of instances.
[X] Wrong: "Connecting to all instances via SSH happens all at once, so time stays the same no matter how many instances."
[OK] Correct: Each SSH connection and command runs separately, so more instances mean more total time, not constant time.
Understanding how connection blocks scale helps you design infrastructure that runs efficiently and predict how long provisioning will take as your environment grows.
"What if we changed from SSH connections to a single centralized management system? How would the time complexity change?"