The Talent500 Blog
How to use Terraform to deploy your infrastructure in CI/CD 1

How to use Terraform to deploy your infrastructure in CI/CD

As a DevOps engineer, continuous integration (CI) and continuous delivery (CD) are two of the most crucial parts of your job role and thus, you must be updated with the latest tools and practices in CI/CD. 

Terraform has evolved into a mainstream tool for companies that leverage DevOps and being proficient is a must. It helps you ensure that all deployments are tracked, security and compliance are being taken care of, and a lot more through automation. Terraform also helps DevOps engineers shorten their delivery times while also reducing errors and even collaborating better. 

To help our broader audience, Talent500 has developed a simple yet insightful mini-guide on using Terraform to deploy infrastructure in CI/CD. 

Let’s get started:

What is Terraform 

How to use Terraform to deploy your infrastructure in CI/CD 2

(Source)

Developed by HashiCorp, Terraform is one of the popular open-source infrastructure-as-a-code tools which enables safe, predictable, and efficient provisioning and management of infrastructure resources.

Terraform lets DevOps engineers define infrastructure resources and their dependencies on other resources in a high-level configuration language. These definitions are used to create, update, and delete infrastructure resources.

It is compatible with AWS, Azure, and Google Cloud, and supports virtual machines, DNS entries, and databases as well as VMware and on-premises infrastructure.

Its infrastructure versioning capabilities make it easy to roll back to previous settings and manage infrastructure-as-code, fostering collaboration, support review, and testing of infrastructure changes before deployment.

Before we begin

As we get started, it is important that you will require a few prerequisites to follow this guide:

  • GitHub account
  • AWS account
  • Azure DevOps account
  • A Linux machine
  • Basic understanding of Git and Bash 
  • Docker
  • InfraCost
  • TFlint
  • TFsec
  • CircleCI

Step-by-step process deploy your infrastructure in CI/CD using Terraform

In this section, we will go through the procedure for deploying infrastructure in CI/CD with the help of Terraform and other tools mentioned here:

Step #1: Create a Terraform configuration file

Use the HashiCorp Configuration Language (HCL) to create the Terraform configuration file like in the below example of a simple configuration file where an Amazon Web Services (AWS) Elastic Compute Cloud (EC2) instance is created:

provider “aws” {

  region = “us-west-2”

}

resource “aws_instance” “example” {

  ami           = “ami-0ff8a91507f77f867”

  instance_type = “t2.micro”

  tags = {

    Name = “example-instance”

  }

}

 

Here, the “provider” component configures the AWS region. The  “resource” block defines the EC2 instance, including the AMI, instance type, and name.

Terraform’s interpolation syntax can reference other resources in your configuration file, and modules can encapsulate and reuse configurations.

You must maintain configuration files in a version control system like git to track changes, roll back to previous versions, and manage interaction with teammates.

Step #2: Use Terraform to set up the environment and download the required providers 

Follow the below process to initialize the environment and download any needful providers using Terraform:

  1. Install Terraform on your local machine.
  2. Create a new directory for your Terraform project and locate it in your terminal.
  3. Run terraform init command to download the required providers and initialize the Terraform environment in the current directory.

Also, you may choose to specify providers (and their versions) in the providers block of your Terraform configuration file which is generally named main.tf and run the terraform init command. 

For instance:

 

provider “aws” {

  version = “~> 2.0”

}

This command will download the specified version of the AWS provider and initialize the Terraform environment.

Store your provider credentials in a terraform.tfvars file to avoid storing them in shared environments like a CI/CD pipeline.

Step #3: Plan the changes by running ‘terraform plan’

Follow the below procedure to plan the changes using Terraform:

  1. Double-check whether you have a valid Terraform configuration file to define the resources you wish to create/modify.
  2. Navigate to the directory containing your Terraform configuration file within your terminal.
  3. Run the terraform plan command to get a preview of the results of creation/modification subsequent to terraform apply.

The Terraform plan compares your infrastructure’s present condition to your desired state and then creates an action plan and prompts confirmation.

For later use, add the -out flag to the plan command.

Step #4: Apply the changes by running ‘terraform apply’

Follow the below process to apply changes using Terraform:

  1. Make sure you have a valid Terraform configuration file defining the resources you want to create/modify, and that you have run terraform plan and reviewed the plan.
  2. Go to the directory containing your Terraform configuration file in your terminal.
  3. Run the terraform apply command to create/modify the infrastructure as per your Terraform configuration.

 

Running the terraform apply command will promptTerraform to use the execution plan generated by your last terraform plan command for making the changes to your infrastructure. 

You can also use the -auto-approve flag to skip the confirmation prompt:

terraform apply -auto-approve

Also, you can use a previously saved plan file with the help of -input=false -lock=false -refresh=false flags:

terraform apply tfplan

Note: Once you have run the terraform apply command, it is important to keep your Terraform configuration files up to date so that you can easily make changes or destroy the infrastructure in the future.

Also, it is in your best interests to use version control for your terraform configuration files, as it helps simplify keeping track of incremental changes you made over time and make rollbacks easier.

For destroying the redundant infrastructure, you can use the terraform destroy command (with -auto-approve flag) or target specific resources like in the below example:

terraform destroy -target=aws_instance.example

You must take notice of the fact that eliminating resources can potentially impact other resources/services with dependencies so you must be cautious when doing so.

It’s recommended to use CI/CD tools like Jenkins, TravisCI, or CircleCI to automate these steps and integrate with version control systems like git to version control your terraform code.

In Conclusion

One of the most compelling benefits of using Terraform to manage your infrastructure as code is that it provides the inherent advantages of CI/CD workflow to the infrastructure deployments, thereby slashing complexities, manual work, and scope of errors- a hallmark of DevOps.

If you are finding DevOps engineer opportunities amid the economic slowdown, join Talent500.

 

0
Avatar

Neel Vithlani

Add comment