First issue - I was missing the security group inside my terraform file so that i can connect to my ec2 instance.
Step1 - Create key-pair from the aws dashboard and then create .pem file and also download it to the development machine.
Step2 - Add the following terraform script so along with the security group with egress and ingress ports running on 22 so that you can connect with the ec2 instance also.
provider "aws" {
region = "eu-central-1"
access_key = ""
secret_key = ""
}
resource "aws_instance" "ec2_example" {
ami = "ami-0767046d1677be5a0"
instance_type = "t2.micro"
key_name= "terraform-keypair"
vpc_security_group_ids = [aws_security_group.main.id]
}
resource "aws_security_group" "main" {
egress = [
{
cidr_blocks = [ "0.0.0.0/0", ]
description = ""
from_port = 0
ipv6_cidr_blocks = []
prefix_list_ids = []
protocol = "-1"
security_groups = []
self = false
to_port = 0
}
]
ingress = [
{
cidr_blocks = [ "0.0.0.0/0", ]
description = ""
from_port = 22
ipv6_cidr_blocks = []
prefix_list_ids = []
protocol = "tcp"
security_groups = []
self = false
to_port = 22
}
]
}
Second method is you can create a key pair manually using the key pair utility - ssh keygen
Here is the example command - ssh-keygen -t aws_key
it will generate two file for you -
- aws_key
- aws_key.pub
use the aws_key.pub inside your terrafrom file -
provider "aws" {
region = "eu-central-1"
access_key = ""
secret_key = ""
}
resource "aws_instance" "ec2_example" {
ami = "ami-0767046d1677be5a0"
instance_type = "t2.micro"
key_name= "aws_key"
vpc_security_group_ids = [aws_security_group.main.id]
}
resource "aws_security_group" "main" {
egress = [
{
cidr_blocks = [ "0.0.0.0/0", ]
description = ""
from_port = 0
ipv6_cidr_blocks = []
prefix_list_ids = []
protocol = "-1"
security_groups = []
self = false
to_port = 0
}
]
ingress = [
{
cidr_blocks = [ "0.0.0.0/0", ]
description = ""
from_port = 22
ipv6_cidr_blocks = []
prefix_list_ids = []
protocol = "tcp"
security_groups = []
self = false
to_port = 22
}
]
}
resource "aws_key_pair" "deployer" {
key_name = "aws_key"
public_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDbvRN/gvQBhFe+dE8p3Q865T/xTKgjqTjj56p1IIKbq8SDyOybE8ia0rMPcBLAKds+wjePIYpTtRxT9UsUbZJTgF+SGSG2dC6+ohCQpi6F3xM7ryL9fy3BNCT5aPrwbR862jcOIfv7R1xVfH8OS0WZa8DpVy5kTeutsuH5FMAmEgba4KhYLTzIdhM7UKJvNoUMRBaxAqIAThqH9Vt/iR1WpXgazoPw6dyPssa7ye6tUPRipmPTZukfpxcPlsqytXWlXm7R89xAY9OXkdPPVsrQA0XFQnY8aFb9XaZP8cm7EOVRdxMsA1DyWMVZOTjhBwCHfEIGoePAS3jFMqQjGWQd rahul@rahul-HP-ZBook-15-G2"
}
Once you provision the EC2 machine you can use the following command to ssh into the machine -
But before that you need to change the mod of the key -
chmod 400 aws_key
ssh -i "aws_key" ubuntu@ec2-3-127-37-1.eu-central-1.compute.amazonaws.com