DevOps | Scripts | Automation

Azure CLITerraform

Terraform Basics

In this article, we will start terraform from scratch and the below topics will be covered. For the demonstration purpose I have used the Azure cloud in this article and as of now, I’m writing this article, terraform has the latest 1.4 version released.

Table of content

  • What is Terraform?
  • Pre-Requisites.
  • Terraform Stages
  • Terraform Files
  • Terraform Registry
  • Demo

What is Terraform ?

Terraform is an Infrastructure as a Code (IaC) language provided by HarshiCop to create the infrastructure on multiple platforms. Terraform is an open-source platform used to create or update the Infrastructure safely.

Terraform is not stuck to a specific platform, unlike the other IAC languages like ARM template and Biceps. This language works with multiple cloud providers (Azure, AWS, GCP, etc). Providers will remain different but the language is the same.

Terraform works in phases Write -> Plan -> Apply.

Below is the official website for Terraform.

https://www.terraform.io/

Terraform is one of the popular languages in DevOps and is easy to get started and learn. Moreover, you can run Terraform

Alright, Let’s get started with the Terraform prerequisites and stages.

Terraform Pre-Requisites (For Azure Cloud)

To run the terraform code we need the below prerequisites.

  1. Terraform CLI
  2. Azure CLI
  3. Azure Cloud Subscription
  4. Command Prompt, PowerShell, or any other console.
  1. Terraform CLI : You need terraform CLI to execute the terraform code. You can download the CLI installation package for the respective operating system from this link (https://developer.hashicorp.com/terraform/downloads). If you are using Azure DevOps then you need to install the Terraform extension. Use this article to install Terraform extension for Azure DevOps.
  2. Azure CLI: Azure CLI is needed to authenticate on the Azure cloud. Use this link to download Azure CLI.
  3. Azure Cloud Subscription: Azure cloud subscription is needed in order to create resources on Azure Cloud with Terraform. For the experimental purpose trial subscription is also fine.
  4. Console: Any console is fine to run the Terraform and Azure CLI commands. If you are on a Windows machine then you can use CMD or PowerShell. In case you don’t have any console available, use the Azure Cloud shell.

Please Note: If you are using Azure Cloud shell, you don’t need to install terraform cli or Azure CLI.

Terraform Stages:

Terraform runs in the stages. Multiple stages are required to successfully run the terraform code and deploy the infrastructure.

Here are the main stages which should be executed in the sequence. This is just a high-level overview, the more details you will understand in the demo.

  1. Terraform Init
  2. Terraform Validate
  3. Terraform Plan
  4. Terraform Apply
  5. Terraform Destroy

a. Terraform Init: Terraform init command is the first command to run. This command initializes providers, backend configuration, and working directory for terraform configuration files. It also initializes the state file (.tfstate) If you have made any changes in the terraform code, you always need to run this command.

b. Terraform Validate: Terraform validates the syntax written in the configuration files.

c. Terraform Plan: Terraform plan will let you understand what type of changes are being done in the infrastructure. The resources that are going to be created, updated, or deleted.

d. Terraform Apply: Terraform apply command executes the files needed to deploy the infrastructure and records the changes in the terraform state file (.tfstate).

e. Terraform Destroy: Terraform destroy command deletes the infrastructure created by Terraform. It takes the reference of the terraform state file (.tfstate) and whichever items are there, this command will delete them.

Terraform Files

Terraform consists of the below files to write terraform code, declare variables, store output, etc.

a. main.tf: This file is the main file in Terraform and it is used for initiating providers, writing infrastructure configuration, and creating backend connection to the storage account (not required always). Whatever infrastructure components are written in this file will be created or updated on the cloud platform.

b. variables.tf: This file is to declare variables. Main.tf file takes the reference of the variables from this file.

c. Output.tf: This file is used by the main.tf file to take the reference of the created or mentioned resources. Resources output or reference can be stored in output.tf file to refer to the other resources.

d. terraform.tfstate: This is the state file used by Terraform to store the state of the resources. Whenever resources are created or deleted through Terraform entries are recorded in this state file. Terraform state files can be used for creating or destroying resources.

e. terraform.tfvars: Another terraform variable file. This file is optional but has higher precedence than the variables.tf file. Values declared in the tfvars file overwrite the values declared in variables.tf file.

Terraform registry

Whenever you write the terraform code, you need help with available terraform modules for the specific providers. You can always refer to the Terraform registry or documentation to work with the available modules.

Here is the terraform registry URL: https://registry.terraform.io/

You can browse the different providers and modules available for them and use them in your code.

Terraform Demo

Alright, we have seen the basics of Terraform and now let’s start with a demo. In this demo, we will create one resource group on the Azure cloud. Before starting make sure we have all the pre-requisites are met.

let’s go step by step.

  • Use any editor and create a main.tf file under the folder C:\TerraformLab (You can use any folder).
  • Browse the Azure provider (https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs) registry and search for the resource group.
  • Select the azurerm_resource_group under Resources. For each module, you see there are resources and Data bases are available. The resource base is to create new resources and the Data is to get the information from the existing module.
  • Once you click on it, you will be redirected to the following page. https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/resource_group
  • Once you open that page, click on the use provider button and it will provide the code to initialize the terraform for Azure. Copy that code to the main.tf file.
  • Now if you scroll down the page, you can see the Example Usage for that particular module and there are arguments you can provide. You need to use all the required arguments to create the resource successfully.

Here, you need to provide the location and name both in the resource section as they are mandatory. azurerm_resource_group is the module name for the resource group and an example is the name given to that module. You can use any name but it should be unique across your terraform file.

  • Copy, that resource section and put it in the main.tf file under the provider’s section. Your whole code should look like this,
terraform {
  required_providers {
    azurerm = {
      source = "hashicorp/azurerm"
      version = "3.52.0"
    }
  }
}

provider "azurerm" {
  # Configuration options
}

resource "azurerm_resource_group" "myResourceGroup" {
  name     = "TF_ResourceGroup"
  location = "West Europe"
}
  • Alright, we now have Terraform configuration file ready that will create TF_ResourceGroup in the “West Europe” region. Open the console (we are using PowerShell) here and log in to your Azure account using azure cli.
az login
  • Once logged in, use the below command to set the Azure subscription in which you wish to create the Resource group.
az account set -s SubscriptionID
  • Once that is done, browse the C:\TerraformLab in which the main.tf file resides and run terraform init command.
PS C:\TerraformLab> terraform init

As highlighted, this command will initialize the backend and install the providers.

  • Run the terraform validate command to validate the syntax and configuration.
terraform validate
  • Next, run the terraform plan command to check what configuration changes are going to make on the provider.
terraform plan

When we run the terraform plan on main.tf file, we get the error message “Error: Insufficient features blocks“.

This error is saying the features block is missing in the main.tf file provider. Feature block is to configure additional features or certain behavior of the resources. To know more about the feature block, check the link: https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/guides/features-block.

Let’s modify the main.tf file and add the features block there. As we don’t want to configure the resources feature now, we can leave that block blank.

terraform {
  required_providers {
    azurerm = {
      source = "hashicorp/azurerm"
      version = "3.52.0"
    }
  }
}

provider "azurerm" {
  features {}
}

resource "azurerm_resource_group" "myResourceGroup" {
  name     = "TF_ResourceGroup"
  location = "West Europe"
}

Run again terraform init command and run terraform plan again.

Alright, now the terraform plan is successful. We can see here, + sign indicates the terraform resources that going to create. Here, we have added a resource group to create. It will create a resource group with the name specified on the specific location.

You can also save the terraform plan using -out argument.

This is just a plan for you to understand what resources will be created, updated or deleted. Use the terraform apply the command to get the plan into effect.

Enter ‘Yes‘ in order to proceed further. You can skip this confirmation part by adding approval automatically through the command line adding -auto-approve in the command line.

terraform apply -auto-approve

To know more about -auto-approve check this link: https://developer.hashicorp.com/terraform/cli/commands/apply

If you have already saved the Terraform plan using the -out parameter then terraform apply command will not ask for the confirmation.

Ok. Let’s press Yes and run the configuration.

So the resource is created now. You can verify this on the Azure Portal.

Once the configuration is applied, the terraform state file will be generated in the same folder we discussed earlier.

{
  "version": 4,
  "terraform_version": "1.3.9",
  "serial": 1,
  "lineage": "dde5f151-ca38-84897c71bad2",
  "outputs": {},
  "resources": [
    {
      "mode": "managed",
      "type": "azurerm_resource_group",
      "name": "myResourceGroup",
      "provider": "provider[\"registry.terraform.io/hashicorp/azurerm\"]",
      "instances": [
        {
          "schema_version": 0,
          "attributes": {
            "id": "/subscriptions/xxxx-xxxx-xxxxx-xxxx/resourceGroups/TF_ResourceGroup",
            "location": "westeurope",
            "name": "TF_ResourceGroup",
            "tags": null,
            "timeouts": null
          },
          "sensitive_attributes": [],
          "private": "eyJlMmJmYjczMC1lY2FhLTExZTYtOGY4OC0zNDM2M2JjN2M0YzAssdsiOnsiY3JlYXRlIjo1NDA"
        }
      ]
    }
  ],
  "check_results": null
}

This state file is used to reference the resource when you run the terraform plan / apply command next time to update/delete the resources.

Let’s check how the terraform destroy command works.

Once the terraform state file is ready, you can destroy the entire infrastructure in a single click using terraform destroy command.

We just need two commands, terraform init and terraform destroy.

Run terraform init first and then terraform destroy.

The console shows that the resource group will be destroyed. Enter Yes and the destruction of the resources created by Terraform from the Terraform state file will be started.

Loading