0
0
Terraformcloud~5 mins

Connection blocks for SSH in Terraform - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Connection blocks for SSH
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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).
How Execution Grows With Input

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
1010 SSH connections and command runs
100100 SSH connections and command runs
10001000 SSH connections and command runs

Pattern observation: The number of SSH operations increases linearly as the number of instances increases.

Final Time Complexity

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.

Common Mistake

[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.

Interview Connect

Understanding how connection blocks scale helps you design infrastructure that runs efficiently and predict how long provisioning will take as your environment grows.

Self-Check

"What if we changed from SSH connections to a single centralized management system? How would the time complexity change?"