Skip to main content

Command Palette

Search for a command to run...

Terraform: Infrastructure as Code

Updated
Terraform: Infrastructure as Code
H

Enthusiastic about DevOps tools like Docker, Kubernetes, Maven, Nagios, Chef, and Ansible and currently learning and gaining experience by doing some hands-on projects on these tools. Also, started learning about AWS and GCP (Cloud Computing Platforms).

Infrastructure as code (IaC) tools allow you to manage infrastructure with configuration files rather than through 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.

Challenges in IT infrastructure

Terraform

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

  • Terraform can manage infrastructure on multiple cloud platforms.

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

  • Terraform’s state allows you to track resource changes throughout your deployments.

  • You can commit your configurations to version control to safety collaborate on infrastructure.

Installations Guide

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

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.

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

Blocks and Arguments

A block is a container for other content and An argument assigns a value to a particular name: filename = “/home/ubuntu/harsh.txt“

The identifier before the equals sign is the argument name, and the expression after the equals sign is the argument’s value.

Resource block: block name used to mention the type of the block. The resource block expects two labels, which are local_file and “pet” in the example above. A particular block type may have any number of required labels, or it may require none.

resource "<provider>_<resource type>" "<resource name>" {
    Argument1 = " "
    Argument2 = " "
}

Implementation

terraform --version
mkdir terraform-course
cd terraform-course
mkdir terraform-local
cd terraform-local

Now make a .tf file for creating a normal text file

# vi local.tf
resource "local_file" "pet"{
    filename = "/home/ubuntu/terraform-course/terraform-local/devops_automated.txt"
    content = "Let's learn terraform togeother"
}

Then run the command to initialize the provider details

terraform init

Run the command to check whether the code is correct or not

terraform validate

Run the command to check what changes will be done after executing the command

terraform plan

Finally execute the code

terraform apply

You can also use —auto-approve to give permission to changes directly

Check the file

ls
cat devops_automated.txt

Execution of Infrastructure

init → plan → apply (validate is optional command)

terraform init

This command will scan your tf files in that folder and install all the required automation things.

terraform plan

This command will create an execution plan for terraforming, the things that will be installed, the names, and the properties added.

terraform apply

The actual execution and automation happen in this command.

Random String

Now create a file which generate random string through Terraform

#vi local.tf
resource "local_file" "pet"{
    filename = "/home/ubuntu/terraform-course/terraform-local/devops_automated.txt"
    content = "Let's learn terraform togeother"
}

resource "random_string" "rand_str"{
    length = 16
    special = true
    override_special = "!@#$%^&*(){}<>?:"
}

output "rand_str"{ 
    value = random_string.rand_str[*].result
}

Initialize the random provider:

terraform init

Here you will find terraform is pulling the random provider from the registry of terraform and using the old local provider.

Check the code for correctness:

terraform validate

Plan the Changes to be Done:

terraform plan

Here you have observed that terraform has not created the old file which is also mentioned in the local.tf, it just created the random string only. Terraform checks the state through terraform.tfstate and figure out what is to be install and what not ?

Finally let’s apply the changes:

terraform apply --auto-approve

We got output of the string also as we have mentioned it on local.tf

Terraform with Docker

Terraform needs to be told which provider to be used in the automation, hence we need to give the provider's name with source and version.

Terraform Block

terraform {
    required_providers {
        docker = {
            source = "kreuzwerker/docker"
            version = "~> 2.21.0"
}
}
}
# Note: kreuzwerker/docker, is the shorthand for registry.terraform.io/kreuzwerker/docker.

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" {
}

Resource

Use resource blocks to define components of your infrastructure. A resource might be a physical or virtual component such as Docker container, or it can be logical resource such as a Heroku application.

Resource blocks have two strings before the block: the resource type and the resource name. In this example, the first resource type is docker_image and the name is Nginx.

Implementation

Make a folder for terraform-docker

mkdir terraform-docker
cd terraform-docker

Install Docker

sudo apt install docker.io -y
sudo chmod 666 /var/run/docker.sock

Some of you might think that if we have to install manually than what is the use of script, but I want to tell you that terraform install only provider who can run and check the process on your behalf but the base we have to provide it.

Create main.tf file

terraform {
    required_providers {
        docker = {
            source = "kreuzwerker/docker"
            version = "~> 2.21.0"
}
}
}

provider "docker" {}

resource "docker_image" "nginx" {
    name = "nginx:latest"
    keep_locally = false
}

resource "docker_container" "nginx"{
    image = docker_image.nginx:latest
    name = "terraform"
    ports {
        internal = 80
        external = 80
}
}

Terraform init

Terraform plan

Terraform apply

Now check on your public-ip nginx server is running or not

Congratulations!!

Terraform: Infrastructure As Code

Part 1 of 6

Explore my Terraform blog series to master Infrastructure as Code (IaC). From resource provisioning and configuration to advanced integrations with AWS, each blog offers concise, actionable insights for automating cloud deployments efficiently.

Up next

Terraform Variables (Part 2)

Variables are fundamental constructs in every programming language because they are inherently useful in building dynamic programs. We use variables to store temporary values so that they can assist programming logic in simple as well as complex prog...