Infrastructure As Code (IaC) Using Terraform And It's Benefits

Introduction

In the earlier days, IT infrastructure management was difficult. We had to manually manage and configure all of the hardware and software. After Cloud computing is evolving, that management changed and it becomes easy compared to the past. We can easily configure and maintain the hardware and software infrastructure using code itself. It is called "Infrastructure as Code (IaC)". Infrastructure as Code (IaC) is managing the IT infrastructure through code instead of manual processes. Terraform is one way to build and manage the infrastructure in the cloud platform such as Azure, AWS, GCP, etc. In this article, we are going to learn about the basic concept of Terraform and its benefits.

What is Terraform?

Terraform is an open-source Infrastructure as Code (IaC) tool developed by HashiCorp. It is human-readable configuration files that are used to create and manage the infrastructure in the cloud platform. Terraform can manage low-level components like compute, storage, and networking resources as well as high-level components like DNS entries. Terraform code is written in a language called HCL and files with the extension .tf.

Benefits of using Terraform 

  • Terraform supports multiple providers such as AWS, Azure, GCP, DigitalOcean and etc.
  • Easy to understand language. It is a human-readable configuration language which helps to write infrastructure code quickly.
  • Immutable infrastructure
  • Portability
  • Reusable configurations
  • Integration to CI/CD
  • Version Controls

Terraform Life Cycle

Terraform lifecycle consists of below stages 

  • init - Initializes the working directory, which consists of all the configuration files
  • plan - Used to create an execution plan and preview the changes.
  • apply - Makes the changes in the infrastructure as defined in the above plan.
  • destroy - Used to delete all the infrastructure resources

How to Install Terraform

  • Download the terraform from the official download page to get the latest version.
  • Extract the downloaded package.
  • Move the "terraform.exe" to the required folder.
  • Add that folder in the "path" in "Environment Variables".
  • To verify the installation, Open the command window and type "terraform", you will get the list of available terraform commands.

Terraform Basic Concepts

1) Provider

It is a plugin to interact with APIs of service and access its related resources.

terraform {
    required_providers {
        aws = {
            source = "hashicorp/aws"
            version = "~> 4.16"
        }
    }
    required_version = ">= 1.2.0"
}
provider "aws" {
    region = "us-west-2"
}

2) Variables

It is used as input variable which is a key value pair used in the Terraform modules.

variable "aws_region" {
    description = "The AWS region to create resources"
    default = "eu-west-2"
}

3) Module

It is a folder with Terraform templates where all the configurations are defined.

4) Resources

It refers to a block of one or more infrastructure objects (compute instances, virtual networks, etc.), which are used in configuring and managing the infrastructure.

Syntax

resource "<PROVIDER>_<TYPE>" "<NAME>" {
 [CONFIG …]
}

resource "aws_instance" "sample_ec2" {
  ami           = "ami-830c94e3"
  instance_type = "t2.micro"

  tags = {
    Name = "ExampleAppServerInstance"
  }
}

5) Output Values

These are the return values of a terraform module.

output "sample_ec2_arn" {
    description = "Arn of the ec2 instance"
    value = aws_instance.sample_ec2.arn
}

Example

In this example, we are going to create a simple EC2 instance. Create following files with below terraform code.

variables.tf

variable "region" {
    type = string
    description = "Refers to AWS region"
    default = "eu-west-2"
}
variable "ec2_instance_type" {
    description = "The type of EC2 Instance to run"
    default = "t2.micro"
}
variable "ec2_ami" {
    description = "The Amazon Machine Image (AMI) to run on the EC2 Instance"
    default = "ami-0c55b159cbfafe1f0"
}

main.tf

terraform {
    required_providers {
        aws = {
            source = "hashicorp/aws"
        }
    }
}
provider "aws" {
    region =
        var.region
}
resource "aws_instance"
"sample_ec2_instance" {
    ami =
        var.ec2_ami
    instance_type =
        var.ec2_instance_type
    tags = {
        Name = "tf-example ec2"
    }
}

outputs.tf

output "sample_ec2_arn" {
    description = "Arn of the ec2 instance"
    value = aws_instance.sample_ec2_instance.arn
}

output "instance_public_ip" {
    value = aws_instance.sample_ec2_instance.public_ip
}

output "instance_state" {
    value = aws_instance.sample_ec2_instance.instance_state
}

How to run the Terraform

  • Open the command window and navigate to the folder where your terraform code was created.
  • Export your AWS account AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY

    SET AWS_ACCESS_KEY_ID=(your access key id)
    SET AWS_SECRET_ACCESS_KEY=(your secret access key)
  • Run the "terraform init" command.
    Initializing the backend...
    
    Initializing provider plugins...
    - Checking for available provider plugins...
    - Downloading plugin for provider "aws" 
    (...)
    * provider.aws: version = "~> 4.17"
    
    Terraform has been successfully initialized!
  • Run the "terraform plan" command
    Refreshing Terraform state in-memory prior to plan...
    (...)
    + aws_instance.example
        ami:                      "ami-0c55b159cbfafe1f0"
        availability_zone:        "<computed>"
        ebs_block_device.#:       "<computed>"
        ephemeral_block_device.#: "<computed>"
        instance_state:           "<computed>"
        instance_type:            "t2.micro"
        key_name:                 "<computed>"
        network_interface_id:     "<computed>"
        placement_group:          "<computed>"
        private_dns:              "<computed>"
        private_ip:               "<computed>"
        public_dns:               "<computed>"
        public_ip:                "<computed>"
        root_block_device.#:      "<computed>"
        security_groups.#:        "<computed>"
        source_dest_check:        "true"
        subnet_id:                "<computed>"
        tenancy:                  "<computed>"
        vpc_security_group_ids.#: "<computed>"
    Plan: 1 to add, 0 to change, 0 to destroy.

The plan command will help you to identify what Terraform going to do. This is used to check your changes before going to deploy. The resources with a plus sign (+) are going to be created, resources with a minus sign (-) are going to be deleted and resources with a tilde sign (~) are going to be modified. 

In the above plan output, you can see that Terraform is going to create a new EC2 instance.So, it has plus (+) sign.

  • Run the "terraform apply" command
     # aws_instance.example will be created
      + resource "aws_instance" "example" {
          + ami                          = "ami-0c55b159cbfafe1f0"
          + arn                          = (known after apply)
          + associate_public_ip_address  = (known after apply)
          + availability_zone            = (known after apply)
          + cpu_core_count               = (known after apply)
          + cpu_threads_per_core         = (known after apply)
          + get_password_data            = false
          + host_id                      = (known after apply)
          + id                           = (known after apply)
          + instance_state               = (known after apply)
          + instance_type                = "t2.micro"
          + ipv6_address_count           = (known after apply)
          + ipv6_addresses               = (known after apply)
          + key_name                     = (known after apply)
          (...)
      }
    Plan: 1 to add, 0 to change, 0 to destroy.
    
    Do you want to perform these actions?
      Terraform will perform the actions described above.
      Only 'yes' will be accepted to approve.
    Enter a value:

Type in “yes” and enter to deploy the EC2 Instance.

Do you want to perform these actions?
 Terraform will perform the actions described above.
 Only 'yes' will be accepted to approve.
Enter a value: yes

aws_instance.example: Creating…
aws_instance.example: Still creating… [10s elapsed]
aws_instance.example: Still creating… [20s elapsed]
aws_instance.example: Still creating… [30s elapsed]
aws_instance.example: Creation complete after 38s
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

Now see the EC2 section in the AWS console, the above EC2 instance will be created.

Summary

In this article, you have learned the following topics,

  • Basic concepts of Terraform
  • Benefits of Terraform
  • Terraform Example


Similar Articles