Skip to main content

Fix Terraform Error - Remote-Exec Connection Refused

Key Takeaway

Terraform cannot SSH into the target instance — the instance may not be ready, security group blocks SSH, or wrong crede

Table of Contents

The Error

When working with Terraform, you may encounter this error:

Error: timeout - last error: dial tcp: connect: connection refused

This error can block your entire workflow. Let’s understand why it happens and how to fix it.

What Causes This Error

Terraform cannot SSH into the target instance — the instance may not be ready, security group blocks SSH, or wrong credentials.

How to Fix It

Solution 1

Ensure security group allows SSH (port 22) from your IP.

Solution 2

Add a depends_on to wait for the instance to be fully ready.

Solution 3

Verify the SSH key and user: connection { type = ssh; user = ec2-user; private_key = file(key.pem) }

Solution 4

Consider using user_data or cloud-init instead of remote-exec provisioners.

Prevention Tips

  • Always run terraform validate before terraform plan
  • Use terraform fmt to keep configuration clean and readable
  • Pin provider versions to avoid unexpected schema changes
  • Review plan output carefully before applying

Learn More

Conclusion

Related: Fix the Terraform inconsistent dependency lock file error — quick fix for this common issue.

This error is common but straightforward to fix. The key is understanding the root cause and applying the correct solution for your specific situation. Following the prevention tips above will help you avoid this error in future projects.

🚀

Level Up Your Terraform Skills

Hands-on courses, books, and resources from Luca Berton

Luca Berton
Written by

Luca Berton

DevOps Engineer, AWS Partner, Terraform expert, and author. Creator of Ansible Pilot, Terraform Pilot, and CopyPasteLearn.