https://unsplash.com/photos/BfrQnKBulYQ

How To Easily Deploy AWS EC2 Instance With Terraform

Introduction

In previous post, we walked through how to deploy an AWS EC2 Instance from the console. Here, we will deploy the same resources using the industry standard Infrastructure as a Code (IaC) called Terraform.

what is infrastructure as code

Infrastructure as code (IaC) means managing your cloud infrastructure using configuration files. This is as opposed to using physical hardware configuration. This method of managing infrastructure help to reduce cost of maintenance. Rather than employing the service of multiple networking engineer to manage the infrastructure. The IaC also helps to speed up implementation of scalability. With an IaC, you can increase the number of resources in that your application needs without increasing the overhead in a short time. IaC also helps to solve problems of inconsistency. This is very useful when you have multiple people working on your infrastructure. You can enjoy the immutability that IaC provides for every your infrastructure you deploy. An IaC can be imperative or declarative. Some examples of IaC includes AWS CloudFormation, Pulumi, Chef, Terraform. We will use terraform to deploy our EC2 instance in this tutorial.

what is terraform

Terraform is one of the infrastructure as a service that you can use to deploy your resources such as EC2 instance. Terraform is an open source tools. It also enables you to safely and predictably provision and manage infrastructure in any cloud. And because terraform supports many cloud providers coupled with the ease of use, it has become popular among Cloud Engineer, DevOps engineers and Site Reliability Engineers. You can install terraform on your machine using this documentation.

what is ec2 instance

An EC2 instance is like having your very own computer in the cloud. With an EC2 instance, you can run programs, store data, and even host websites. One cool thing about EC2 instances is that they are really flexible. You can choose how powerful your instance is and how much memory it has. This means you can have a small instance for simple tasks or a big instance for more demanding jobs. EC2 instances are also very reliable. And if lots of people start using your website or program, you can easily make your instance bigger to handle the extra traffic.

Instance Configuration

Configuring Terraform resources is pretty straight forward. And considering that terraform has a well detailed documentation on their website, it is even more seamless.

So, to begin, we will create an aws_instance resources in our instance.tf file. Then add all our configuration to set up our server. Copy the below and paste in the file. This resource will create an EC2 Instance in us-east-1s availability zone, enable the monitoring, and use the t2.micro instance type. The instance type will be recovered from the AMI image which will be provided from the data in terraform.

If you will use a custom VPC and Subnet, you can specify the subnet in the subnet_id block as shown. Otherwise, terraform will create the EC2 in the default VPC and Subnet.

resource "aws_instance" "ec2-instance" {
  ami                                  = data.aws_ami.ubuntu.id
  instance_type                        = "t2.micro"     #free tier eligible
  availability_zone                    = "us-east-1a"
  instance_initiated_shutdown_behavior = "terminate"
  key_name                             = aws_key_pair.server-keypair.id
  monitoring                           = true
  subnet_id                            = aws_subnet.public-subnet.id
  tenancy                              = "default"
  ebs_optimized                        = false
  associate_public_ip_address          = true
  iam_instance_profile                 = aws_iam_instance_profile.iam-instance-profile.id

  ebs_block_device {
    device_name = "/dev/sda1"
    volume_size = 20
    delete_on_termination = true
    volume_type = "gp2"
  }
  security_group = [aws_security_group.public-traffic-SG.id]

  tags = {
    Name        = "public-server"
    Environment = "lab"
  }

}

Also, notice that the associate_public_ip_address is set to true. However, if you are deploying a private EC2 instance, you will set that to false. For this tutorial, I also added the ebs_block_device and use the 20GB disk for our EC2 instance. That is the beauty of terraform.

Also, I used the security_group to specify the security groups I want to use in the VPC. If none is specified, Terraform will use the default security group and rules.

create security group

In the step above, we specified a security group in the EC2 resources. Now, let’s deploy the Security Group for the EC2 instance with Terraform. The security group will allow traffic on port 443, 80, 22 from anywhere. However, in production, security best practices should be considered. Also, the egress traffic allow all traffic by default.

resource "aws_security_group" "public-traffic-SG" {
  name        = "public-traffic-SG"
  description = "Allow TLS inbound traffic"
  vpc_id      = aws_vpc.vpc.id
  ingress {
    description      = "Public-Traffic-TLS"
    from_port        = "443"
    to_port          = "443"
    protocol         = "tcp"
    cidr_blocks      = ["0.0.0.0/0"]
    ipv6_cidr_blocks = ["::/0"]
  }
  ingress {
    description      = "Public-Traffic-TLS"
    from_port        = "22"
    to_port          = "22"
    protocol         = "tcp"
    cidr_blocks      = ["0.0.0.0/0"]
    ipv6_cidr_blocks = ["::/0"]
  }
    ingress {
    description      = "Public-Traffic-TLS"
    from_port        = "80"
    to_port          = "80"
    protocol         = "tcp"
    cidr_blocks      = ["0.0.0.0/0"]
    ipv6_cidr_blocks = ["::/0"]
  }
  egress {
    from_port        = 0
    to_port          = 0
    protocol         = "-1"
    cidr_blocks      = ["0.0.0.0/0"]
    ipv6_cidr_blocks = ["::/0"]
  }
  tags = {
    Name = "allow_tls"
  }
}
add ssh key for keypair

In addition, we will create the key-pair for our resources. The key-pair will enable us to SSH into the EC2 instance after terraform finish deploying it. Generate a key-pair on your local machine with $ssh-keygen. Give it a name and take note of the path. I created mine in the same directory where my other terraform file is and referenced it there using the file utility in terraform.

resource "aws_key_pair" "server-keypair" {
  key_name   = "server-keypair"
  public_key = file("./server-lab-keys.pub")   #" "
}
add instance profile

One other important resources to create is the AWS Instance profile. The instance profile is the IAM role that the AWS EC2 will take after it has been deploy to perform some basic functions.

resource "aws_iam_role" "iam-instance-role" {
  name               = "iam_role"
  path               = "/"
  assume_role_policy = data.aws_iam_policy_document.server-assume-role.json
}

resource "aws_iam_instance_profile" "iam-instance-profile" {
  name = "test_profile"
  role = aws_iam_role.iam-instance-role.name
}

data "aws_iam_policy_document" "server-assume-role" {
  statement {
    effect = "Allow"

    principals {
      type        = "Service"
      identifiers = ["ec2.amazonaws.com"]
    }

    actions = ["sts:AssumeRole"]
  }
}

The AWS terraform data will create a template that will be used to create the instance profile.

resource "aws_iam_instance_profile" "iam-instance-profile" {
  name = "test_profile"
  role = aws_iam_role.oxla-instance-role.name
}

data "aws_iam_policy_document" "iam-assume-role" {
  statement {
    effect = "Allow"

    principals {
      type        = "Service"
      identifiers = ["ec2.amazonaws.com"]
    }

    actions = ["sts:AssumeRole"]
  }
}

Once that is done, you can use the terraform plan to see the resource that terraform will deploy for you, including the EC2, the key-pair, and the security group.

terraform plan

Once you are cool with the resources and terraform did not show any error, you can use the apply command to deploy the resources. Enter YES when prompted for the confirmation.

terraform apply
conclusion

In this tutorial, we have been able to deploy the AWS EC2 instance in to a subnet with security group using terraform. You can also check about the how to deploy the core network infrastructure in AWS in my other posts. Till the next time. Kindly drop your comments in the box below and also remember to share to your circle of friends.


Posted

in

,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *