Assign SSH-key to AWS Instance Using Terraform

in the last blog we create a key pair, in this blog, we will assign that key to the AWS instance. let's modify the instance.tf file(that we created in the previous blog) with the below content.

and make sure in your current directory have id_rsa, id_rsa.pub, provider.tf, instance.tf, aws-kp.tf that we created in previous blogs.

resource "aws_instance" "web" {
  ami                    = "ami-0b0ea68c435eb488d"
  instance_type          = "t2.micro"
  key_name               = aws_key_pair.key-tf.key_name
  tags = {
    Name = "first-tf-instance"
  }
}

first, destroy the instance that we created in previous blogs using terraform destroy command. and run terraform apply command and verify that new instance created and ssh key assigned to that instance.

you can ssh that instance with the help of that id_rsa key.

example

ssh -i id_rsa username@ipAddressOfInstance

Demo: Demo Video