Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can i do ssh into my ec2 instance created by terraform?

i have created an ec2 instance using terraform (do not have .pem keys). Can i establish ssh connection between my local system and ec2 instance?

like image 396
UTKARSH SHRIVASTAVA Avatar asked Jan 12 '20 22:01

UTKARSH SHRIVASTAVA


People also ask

Does Terraform use SSH?

To access a private Git repository, Terraform either needs login credentials (for HTTPS access) or an SSH key. Terraform Cloud can store private SSH keys centrally, and you can easily use them in any workspace that clones modules from a Git server.


1 Answers

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:

  • https://www.terraform.io/docs/providers/aws/r/instance.html
  • https://www.terraform.io/docs/providers/aws/r/key_pair.html
  • https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AccessingInstancesLinux.html
like image 121
jwillker Avatar answered Oct 16 '22 05:10

jwillker