Terraform: EC2 Instance with SSH Setup

In this post, I am going to use Terraform to create a EC2 instance with ssh setup.

If you have not installed Terraform yet, check https://web-quickstart.blogspot.com/2021/03/terraform-with-docker-compose.html


ssh key pair

First, create a key pair (as test & test.pub in this example)

% ssh-keygen

Generating public/private rsa key pair.

Enter file in which to save the key (/Users/tomo/.ssh/id_rsa): test

Enter passphrase (empty for no passphrase): 

Enter same passphrase again: 

...

% ls test*

test     test.pub


main.tf

Create main.tf with following contents: 

provider "aws" {
  region = "us-east-1"
}

data "aws_ami" "ami" {
  most_recent = true
  filter {
    name   = "name"
    values = ["amzn2-ami-hvm-*"]
  }
  owners = ["amazon"]
}

resource "aws_instance" "instance" {
  ami = data.aws_ami.ami.id
  instance_type = "t2.micro"
  key_name = aws_key_pair.key_pair.id
}

resource "aws_key_pair" "key_pair" {
  public_key = file("./test.pub")
}

resource "aws_security_group" "sg" {
  ingress {
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

resource "aws_network_interface_sg_attachment" "sg_attachment" {
  security_group_id    = aws_security_group.sg.id
  network_interface_id = aws_instance.instance.primary_network_interface_id
}

1. provider.aws.region (the first block) is optional, if you want to specify region in the code.

2. data.aws_ami (second block) is to search for the AMI

3. resource.aws_instance creates an instance with the key pair.

4. resource.aws_key_pair is where you pass the public key

5. resource.aws_security_group is SG for ssh

6. resource "aws_network_interface_sg_attachment attaches SG on the EC2 instance


create aws resources

% terraform init

% terraform plan

% terraform apply


ssh

You can get the ssh command by navigating on the AWS console:

AWS Console > N.Virginia(us-east-1) > EC2 > Instances > [instance] > Connect > SSH Client


% ssh -i test ec2-user@ec2-3-238-52-214.compute-1.amazonaws.com

If you prefer to see the IP on a command line tool, try:

% aws ec2 describe-instances | jq -r '.Reservations[].Instances[].PublicIpAddress'


cleanup

% terraform destroy


link

For more detail about security group with Terraform:


Comments

Popular posts from this blog

Minikube Installation for M1 Mac

Selenide: Quick Start

PyCharm: Quick Start