Terraform (IaC)

This is a preview lesson
Register or sign in to take this lesson.

What is Terraform?

Terraform is one of the most popular tools that helps you to manage various cloud infrastructure services in the form of code. All the infrastructure can be codified with Terraform, so it is known as Infrastructure as Code (IaC).

Terraform is an Open-source tool created by HashiCorp and written in the Go language. Terraform uses cloud provider APIs to create the resource.

In short, Terraform is a tool for building, changing, versioning, and managing infrastructure efficiently.

Why Terraform?

With the increasing cloud computing and the number of cloud providers and their services, it’s becoming more important to be able to manage or maintain cloud infrastructure resources. As Terraform works on the IaC concept, it makes infrastructure resources manageable easily.

There are a lot of IaC tools but Terraform is the most popular and widely used tool.

Features

  • Support almost all clouds (cloud-agnostic)

Terraform supports most of the clouds such as AWS, Azure, GCP, etc.

  • Declarative syntax

Developers don’t need to worry about making terraform understand the steps required to create the resources. Terraform takes care of the steps internally.

  • Modules

Terraform provides modules that can be used as reusable code. This means complex infrastructure can be broken into smaller modules and each module can be reused in different projects.

  • Orchestration

Terraform acts as an orchestration process to create cloud resources.

  • State management

When creating and planning terraform resources, the state is maintained. Which can be shared with other members too.

  • Provisioning

Terraform has local-exec and remote-exec features which are used to run inline scripts. This feature can be used to install software components upon successful creation of the resource.

Advantages of Terraform

  • Easier to maintain as infrastructure creation is used as code. One can leverage version control.
  • Changes to infrastructure are easier and comparable.
  • SDLC becomes more efficient.

Terraform Workflow

To create and destroy resources using Terraform, you need to follow simple steps— init, plan, apply, and destroy.

init

After you configure the files then the very first command or step you need to do is run the command terraform init. In this step, based on the provider, appropriate plugins are downloaded. And initialize the backend.

plan

In this step, the command terraform plan helps to generate an execution plan based on the configuration you provide. In this, terraform performs feasibility checks like syntax errors, API authentication, state verification, etc. Also, it outputs a summary of potential changes in the infrastructure. Running terraform plan before apply makes you aware of any risks before modifying.

apply

In this(terraform apply), all the changes to infrastructure are executed and deployed to the cloud. In this case, a new plan file will be created automatically.

destroy

It helps to destroy any resources which are created or part of a configuration or state file.

Installation

The command to destroy is terraform destroy.

To use terraform, you need to install Terraform CLI. You can install Terraform CLI easily by following the official documentation for the OS of your system. For this tutorial, I’ll show you how to install CLI on Ubuntu(Linux).

$ sudo apt-get update && sudo apt-get install -y gnupg software-properties-common curl

Add GPG key of HashiCorp:

$ curl -fsSL https://apt.releases.hashicorp.com/gpg | sudo apt-key add -

Add repository:

$ sudo apt-add-repository "deb [arch=amd64] https://apt.releases.hashicorp.com $(lsb_release -cs) main"

Now, update and install Terraform CLI:

$ sudo apt-get update && sudo apt-get install terraform

Verify installation:

$ terraform -help

Creating Terraform First Project

After some theory, let’s try to implement what we have learned by actually creating an instance of EC2 on AWS.

How to create an EC2 instance on AWS

First, create a first terraform file main.tf (you can name it anything but it should have an extension .tf).

Copy the following code and paste it into main.tf file.

provider “aws” {
	region = “ap-south-1”
}

resource “aws_instance” “example-ec2” {
	ami = “ami-334dsfei343422”
	instance_type = “t2.micro”
}

Note: Use correct AMI based on your instance choice of preferred region.

Now, initialize the Terraform by running terraform init. This will install the required AWS plugin. To run the initialize command, go to the project directory and run the command:

$ terraform init

The output will be as below.

Next, run the plan command to see the changes. This also validates any syntaxes or references and checks the feasibility of the declared resources.

$ terraform plan

The output will be generated as below:

An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # aws_instance.example will be created
  + resource "aws_instance" "example-ec2" {
      + ami                          = "ami-334dsfei343422"
      + arn                          = (known after apply)
      + associate_public_ip_address  = (known after apply)
. . .
Plan: 1 to add, 0 to change, 0 to destroy.

------------------------------------------------------------------------

Note: You didn't specify an "-out" parameter to save this plan, so Terraform
can't guarantee that exactly these actions will be performed if
"terraform apply" is subsequently run.

The plan command indicates which resource will be created. In our case, an example-ec2 will be created with AMI ID as we have configured. Other attributes like arn, associate_public_ip_address will be known after apply command.

At the bottom, Plan: 1 to add, 0 to change, 0 to destroy. indicates that 1 resource will be added and 0 changes will be applied and 0 resources will be destroyed when the apply command is executed.

Finally, if everything looks good run the apply command:

$ terraform apply

in output, you’ll see a confirmation prompt to accept. Type yes and the resource will be created.

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: yes

aws_instance.myec2: Creating...
aws_instance.myec2: Still creating... [10s elapsed]
aws_instance.myec2: Still creating... [20s elapsed]
aws_instance.myec2: Still creating... [30s elapsed]
aws_instance.myec2: Still creating... [40s elapsed]
aws_instance.myec2: Still creating... [50s elapsed]
aws_instance.myec2: Creation complete after 51s [id=i-04ef3120a0006a153]

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

You have successfully created an EC2 instance using IaC terraform.

You can destroy the same configuration by running destroy command if you don’t need it anymore.

To destroy the configuration:

$ terraform destroy

The output will ask for a confirmation prompt, accepting the prompt will destroy your resource created by IaC./

Terraform destroy
Plan: 0 to add, 0 to change, 1 to destroy.

Do you really want to destroy all resources?
  Terraform will destroy all your managed infrastructure, as shown above.
  There is no undo. Only 'yes' will be accepted to confirm.

  Enter a value: yes

aws_instance.myec2: Destroying... [id=i-04ef3120a0006a153]
aws_instance.myec2: Still destroying... [id=i-04ef3120a0006a153, 10s elapsed]
aws_instance.myec2: Still destroying... [id=i-04ef3120a0006a153, 20s elapsed]
aws_instance.myec2: Still destroying... [id=i-04ef3120a0006a153, 30s elapsed]
aws_instance.myec2: Still destroying... [id=i-04ef3120a0006a153, 40s elapsed]
aws_instance.myec2: Still destroying... [id=i-04ef3120a0006a153, 50s elapsed]
aws_instance.myec2: Still destroying... [id=i-04ef3120a0006a153, 1m0s elapsed]
aws_instance.myec2: Destruction complete after 1m5s

Destroy complete! Resources: 1 destroyed.

You can check the resources on AWS console by logging in. (to verify either deleted or not)

Conclusion

In this chapter, we’ve discussed the basic introduction of Terraform IaC, and how it works with a sample example.

Thank you!