Devops ToolsTerraform

Terraform-SSH connection to EC2 instance

This blog will help you if you need to enable the ssh connection to EC2 instance.

Path to the SSH public key to be used for authentication. Ensure this keypair is added to your local SSH agent so provisioners can connect.

ssh-keygen (Generate keys if not exist already)

Adding your SSH key to the ssh-agent

Ensure ssh-agent is enabled:

start the ssh-agent in the background

eval "$(ssh-agent -s)"

Agent pid 59566

Add your SSH key to the ssh-agent. If you used an existing SSH key rather than generating a new SSH key, you’ll need to replace id_rsa in the command with the name of your existing private key file.

$ ssh-add ~/.ssh/id_rsa

How to make ssh connection to host

variable public_subnet_id {}
variable private_subnet_id {}
variable FrontEnd_SG_id {}
variable Database_SG_id {}
variable vpc_id {}
resource "aws_key_pair" "auth" {
  key_name   = "${var.key_name}"
  public_key = "${file(var.public_key_path)}"
}
resource "aws_instance" "webserver" {
  ami           = "${lookup(var.ami, var.region)}"
 connection {
    # The default username for our AMI
    user = "ec2-user"
host = "${aws_instance.webserver.public_ip}"
# The connection will use the local SSH agent for authentication.
}instance_type = "t2.micro"
associate_public_ip_address = "true"
subnet_id = "${var.public_subnet_id}"
vpc_security_group_ids = ["${var.FrontEnd_SG_id}"]
key_name = "${aws_key_pair.auth.id}"
tags {
Name = "webserver"
}
}

 

SSH connection to EC2 Instance is completed successfully.

Please follow and like us: