Terraform Automation

Neha BawaneNeha Bawane
7 min read

Infrastructure as Code (IaC)

Infrastructure as Code (IaC) tools allow you to manage infrastructure with configuration files rather than a graphical user interface. IaC allows you to build, change, and manage your infrastructure in a safe, consistent, and repeatable way by defining resource configurations you can version, reuse, and share.

Terraform

Terraform is HashiCorp's infrastructure as a code tool. It lets you define resources and infrastructure in human-readable, declarative configuration files and manages your infrastructure's lifecycle.Terraform has several advantages over manually managing your infrastructure.

1. Terraform can manage infrastructure on multiple cloud platforms.

2. The human-readable configuration language helps you write infrastructure code quickly.

3. Terraform's state allows you to track resource changes throughout your deployments.

4 You can commit your configuration to version control to safely collaborate on infrastructure

HCL

Hashicorp Configuration Language, This low-level syntax of the Terraform language is defined in terms of a syntax called HCL, which is also used by configuration languages in other applications, and in particular other HashiCorp products. It is not necessary to know all of the details of HCL syntax in order to use Terraform, just knowing the basics, should be enough.

<block> <parameters> {
    key1 = value1
    key2 = value2
}

The Terraform language syntax is built around two key syntax constructs arguments and blocks

Terraform with Docker

To deploy an NGINX container with Terraform automation, we can define a Docker container resource in our Terraform configuration, specifying the NGINX image and any necessary settings.

This Terraform instructs Docker to create a container named "my-nginx-container" using the latest NGINX image, and it maps port 80 inside the container to port 8080 on the host. When you apply this Terraform configuration, it automates the deployment of the NGINX container, ensuring it runs consistently and efficiently on your chosen infrastructure.

Let's Begin -->>

Prerequisites

Before we begin with the Project, we need to make sure we have the following prerequisites installed:

1. EC2 ( AMI- Ubuntu, Type- t2.micro, ports 22 and 80 are enabled)

2. Terraform installed

3. Docker installed

Step 1: Create an EC2 instance having AMI-ubuntu. t2.micro

Step2: Terraform Installation

Install the Terraform on your remote machine using the below commands.

Please execute the following commands sequentially, one by one

sudo apt-get update && sudo apt-get update install -y gnupg software-properties-common wget -O- https://apt.releases.hashicorp.com/gpg

sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg echo "deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(lsb_release -cs) main"

sudo tee /etc/apt/sources.list.d/hashicorp.list

sudo apt update

sudo apt install terraform

Docker Installation

Please execute the following commands sequentially, one by one.

sudo apt-get install docker.io

sudo docker ps

sudo chown $USER /var/run/docker.sock

Step 3: Create a directory

mkdir terraform-practice  ---to create directory
cd terraform-practice/    --- go inside that directory
vim terraform.tf          ---create and open terraform.tf file in vim editor

Step 4: Install the required Docker providers/plugins.

Provider

The provider block configures the specified provider, in this case, docker. A provider is a plugin that Terraform uses to create and manage your resources.

provider "docker" {}

For docker, we can use the block of code in our terraform.tf file

Write the below code into the terraform.tf file save and exit that file.

terraform {
  required_providers {
    docker = {
      source  = "kreuzwerker/docker"
      version = "3.0.2"
    }
  }
}

Note: kreuzwerker/docker, is shorthand for registry.terraform.io/kreuzwerker/docker.

After creating a terraform.tf file in which the required providers and plugins are available. Run the command terraform init to install the required plugins.

terraform init

Step 5: Create a main.tf file

Resource

Use resource blocks to define components of your infrastructure. A resource might be a physical or virtual component such as a Docker container.

Resource blocks have two strings before the block: the resource type and resource name. In our code, the resource type is docker_image and the resource name is nginx-img

vim main.tf  ----create and open the main.tf file in vim editor

Here we write a code first to create an nginx image and from that image, we create a container.

Write the below code to deploy container with terraform in the main.tf file save and exit the file

provider "docker" {}
resource "docker_image" "nginx-img" {
        name = "nginx:latest"
        keep_locally = false
}

resource "docker_container" "nginx-ctr" {
       name = "my-nginx-container"
       image = docker_image.nginx-img.name

      ports {
      internal = 80
      external = 80
      }
}

Step 6: Initialize

Open your terminal, navigate to your project directory, and run the following command to initialize Terraform:

terraform init

Step 7: Plan

Run the following command to create an execution plan. This step helps you preview the changes Terraform will make:

terraform plan

Step 8: Apply

Once you are satisfied with the execution plan, apply it to create the Docker nginx container.

terraform apply

Confirm the action by typing "yes" when prompted.

We have accomplished the successful deployment of the NGINX container.

Let's perform a local validation to confirm the operational status of our container.

http://public-ip

"Celebrating a successful deployment, the nginx container is now up and running, thanks to Terraform automation."

Terraform with AWS

Deploying an EC2 instance with Terraform automation is straightforward. In a Terraform configuration file, you define the EC2 instance's specifications, such as its size, region, and any required configurations. Terraform then translates this code into infrastructure actions, creating the instance and associated resources, like security groups or key pairs, when you apply the configuration. With Terraform's simplicity and repeatability, you can easily provision and manage EC2 instances, making it a reliable choice for infrastructure automation on Amazon Web Services (AWS).

Prerequisites

AWS CLI installed

The AWS command line interface (AWS CLI) is a unified tool to manage your AWS services. With just one tool to download and configure, you can control multiple AWS services from the command line and automate them through scripts.

We can install the AWS CLI with the below commands

sudo apt install awscli

aws configure

In order to connect the AWS account and Terraform, we need the access keys and secret access keys

AWS IAM user

IAM (Identity Access Management) AWS IAM is a web service that helps you securely control access to AWS resources. We use IAM to control who is authenticated and authorized to use resources.

Step 1: Create a directory

mkdir terraform-aws  -- to cretae directory
cd terraform-aws/  -- to go inside that directory
vim terraform.tf  ---create and open the file in vim editor

Step 2: Install the required AWS providers/plugins.

Create terraform.tf configuration file

# install required providers
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

Execute the command terraform init to install plugins

Step 3: Generate the public key.

Please execute the following commands sequentially, one by one

Include the file path for 'terraform-key.pub' within the resource code for further refinement."

file path /home/ubuntu/.ssh/terraform-key.pub

Step 4: Declare the variable

we can create a variable.tf file which will hold all the variable

# create a variable
variable "ec2-ubuntu-ami" {
  default = "ami-0f5ee92e2d63afc18"
}

Step 5: Add a resource block to define your EC2 instance. create main.tf file

# Add the region where you want your instance to be
provider "aws" {
       region = "ap-south-1"
}

# add the public key path
resource "aws_key_pair" "mykey" {
       key_name = "terraform-key"
       public_key = file("/home/ubuntu/.ssh/terraform-key.pub")
}

resource "aws_default_vpc" "default_vpc"{

}

resource "aws_security_group" "allow_ssh" {
  name        = "allow_ssh"
  description = "Allow ssh inbound traffic"

  # using default VPC
  vpc_id      = aws_default_vpc.default_vpc.id
  ingress {
    description = "TLS from VPC"

    # we should allow incoming and outgoing
    # TCP packets
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"

    # allow all traffic
    cidr_blocks = ["0.0.0.0/0"]
  }

  tags = {
    Name = "allow_ssh"
  }
}

# AWS EC2 instance provisioning
resource "aws_instance" "my-vpc-instance" {
       key_name = aws_key_pair.mykey.key_name
       ami =  var.ec2-ubuntu-ami
       instance_type = "t2.micro"
       security_groups = [aws_security_group.allow_ssh.name]

       tags = {
       Name = "Terraform-Automation"
       }
}

# get the public ip for the created instance

output "instance_pub_ip" {
value = aws_instance.my_vpc_instance.public_ip
}

Step 6: Initialize

Open your terminal, navigate to your project directory, and run the following command to initialize Terraform:

terraform init

Step 7: Plan

Run the following command to create an execution plan. This step helps you preview the changes Terraform will make:

terraform plan

Step 8: Apply

Once you are satisfied with the execution plan, apply it to create the EC2 instance:

terraform apply

Confirm the action by typing "yes" when prompted.

Step 9: Output

"The EC2 instance has been provisioned successfully through Terraform automation."

Congrats!!! You have Successfully done the Terraform Automation with AWS and Docker

Summary

Terraform with AWS: Terraform enables you to automate and manage your AWS infrastructure by defining resources like EC2 instances, networks, and databases as code. It simplifies provisioning, scaling, and maintaining AWS resources.

Docker: Docker simplifies application deployment by packaging applications and their dependencies into containers. It ensures consistency across different environments and allows for easy scaling and portability.

Happy Learning

Thank you

Neha Bawane

0
Subscribe to my newsletter

Read articles from Neha Bawane directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Neha Bawane
Neha Bawane