UTKARSH SHRIVASTAVA
UTKARSH SHRIVASTAVA

Reputation: 313

Can I SSH into my EC2 instance created by terraform?

I have created an EC2 instance using terraform (I do not have the .pem keys). Can I establish an SSH connection between my local system and the EC2 instance?

Upvotes: 21

Views: 19145

Answers (1)

jwillker
jwillker

Reputation: 1035

Assuming you provisioned an instance using Terraform v0.12.+ with this structure:

resource "aws_instance" "instance" {
  ami              = "${var.ami}"
  instance_type    = "t2.micro"
  count            = 1
  associate_public_ip_address = true
}

You can make some additional settings:

  • Configure the public ip output:
output "instance_ip" {
  description = "The public ip for ssh access"
  value       = aws_instance.instance.public_ip
}

  • Create an aws_key_pair with an existing ssh public key or create a new one Ex:
resource "aws_key_pair" "ssh-key" {
  key_name   = "ssh-key"
  public_key = "ssh-rsa AAAAB3Nza............"
}
  • Add the key_name in instance resource just like this:
resource "aws_instance" "instance" {
  ami              = var.ami
  instance_type    = "t2.micro"
  count            = 1
  associate_public_ip_address = true

  key_name         = "ssh-key"
}
  • Now you need to apply running terraform apply and terraform output to return the public IP

  • Get your public IP and run:

 ssh <PUBLIC IP>

OR with a public key path

ssh -i "~/.ssh/id_rsa.pub" <PUBLIC IP>

Sources:

Upvotes: 40

Related Questions