๐Ÿ” How to SSH into an EC2 Instance Created by Terraform

BinereetDevopsBinereetDevops
2 min read

In this guide, we'll learn how to securely SSH into an EC2 instance provisioned using Terraform. The process includes generating SSH keys, uploading the public key to AWS, and connecting to the instance using the private key.


โœ… Step 1: Generate an SSH Key Pair

Run the following command on your local machine:

ssh-keygen -f terra-key-ec2

๐Ÿ“‚ This generates two files:

  • terra-key-ec2.pub โ€“ the public key

  • terra-key-ec2 โ€“ the private key

๐Ÿ’ก The public key is meant to be shared (with AWS in this case), while the private key must be stored securely and is used to authenticate you.


โœ… Step 2: Add the Public Key to AWS using Terraform

In your Terraform configuration, use the following resource:

resource "aws_key_pair" "my_key" {
  key_name   = "terra-key-ec2"
  public_key = file("terra-key-ec2.pub")
}

๐Ÿ” Explanation:

  • aws_key_pair is the resource type.

  • my_key is the internal Terraform name.

  • key_name is what your key pair will be called in AWS.

  • public_key loads the content of your .pub file and sends it to AWS.

โœ… This step registers the public key with AWS, allowing EC2 instances to trust connections made using your private key.


โœ… Step 3: Launch EC2 Instance (Optional Context)

Make sure to reference your key pair in the EC2 configuration:

resource "aws_instance" "my_instance" {
  ami           = "ami-0cb91c7de36eed2cb"  # Example Ubuntu AMI
  instance_type = "t2.micro"
  key_name      = aws_key_pair.my_key.key_name
  ...
}

This ties your EC2 instance to the key pair.


โœ… Step 4: SSH into the EC2 Instance

Once your EC2 instance is running, use the following command to SSH into it:

chmod 400 terra-key-ec2
ssh -i terra-key-ec2 ubuntu@<EC2_PUBLIC_IP>

๐Ÿ›ก๏ธ Important Notes:

  • chmod 400 ensures your private key is not publicly viewable.

  • Replace <EC2_PUBLIC_IP> with the actual public IP address of your EC2.

  • ubuntu is the default user for Ubuntu AMIs. For Amazon Linux, use ec2-user.


๐ŸŽฏ Conclusion

By generating SSH keys and configuring Terraform properly, you can securely access your AWS EC2 instances. This is a foundational skill in Infrastructure as Code and DevOps automation workflows.

Let me know in the comments if you'd like to automate SSH setup even further or explore advanced Terraform modules!

#Terraform #AWS #EC2 #DevOps #CloudComputing #SSH #InfrastructureAsCode #AWSCommunity #HashnodeDev #TerraformTips

My LinkedIn Profile - https://www.linkedin.com/in/binereet-singh-9a7685316/

0
Subscribe to my newsletter

Read articles from BinereetDevops directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

BinereetDevops
BinereetDevops