Terraform with Azure for Beginners

Towards Automation: An Introduction to Terraform (Infrastructure as Code)

Terraform with Azure for Beginners

"Software isn't done when the code is working on your computer, software isn't done until you deliver it to the user" says Yevgeniy in his book "Terraform Up and Running". Despite being a hot topic, DevOps is still in its early days of adoption as organizations look for ways to automate the infrastructure deployment and management using code, pipelines, and no-touch deployments.

Terraform has emerged as a key component in the DevOps world. It enables you to replace the manual parts of your infrastructure management with a solid and automated foundation upon which you can build all your DevOps practices including automated testing, Continuous Integration, Continuous Delivery and orchestrates the workloads using tools such as Docker, Chef, Puppet, and Ansible.

In this article, I'll introduce you to the Infrastructure as Code tool, Terraform that you can use to automate and build scalable cloud infrastructure without manually provisioning the resources using Azure Portal.

If you are working as a Cloud Admin, Engineer, or any role that involves deploying cloud resources and managing the workloads, using Terraform might be the best decision to automate your manual work and let the code work for you instead.

If you wish to watch instead, check out the Video below:

Table Of Content

  1. Prerequisites
  2. What is Terraform?
  3. What is Infrastructure as Code (IaC)?
  4. How does it work?
  5. Installing Terraform on Windows
  6. Terraform Commands
  7. Conclusion
  8. Reference

Prerequisites

  • Download Terraform CLI binary. I'll walk through the installation process.
  • Install Azure CLI on your computer. Azure PowerShell is not necessary.

What is Terraform?

Terraform is a tool for building, changing, and versioning infrastructure. It is essentially an infrastructure as a code (IaC) tool that helps you build, manage, and scale your infrastructure easily and effectively. It is a powerful tool that supports multi-cloud like Amazon Web Services, Microsoft Azure, and Google Cloud Platform, or on-prem in private clouds such as VMWare vSphere, OpenStack, or CloudStack. The primary use of the terraform is to ensure that the infrastructure never drifting away from its desired configuration. The language used for configuration is Hashicorp Configuration Language (HCL).

What is Infrastructure as Code (IaC)?

If you are new to infrastructure as code as a concept, it is the process of managing infrastructure in a file or files rather than manually configuring resources in a user interface. A resource in this instance is any piece of infrastructure in a given environment, such as a virtual machine, security group, network interface, etc.

To simplify, terraform allows you to use HCL to build files that contain your desired resource configuration and automates the creation of those resources at any time using the apply command.

How does it work?

The terraform workflow follows a few different steps that ensure the requirements are clear and the idea of infrastructure is valid as well. In simple language, you create a set of files with a list of resources you want to deploy and then deploy those to your environment using terraform CLI which handles all the state management and upgrades for you as your codebase and requirements increase over time. Let's see what are the four key requirements or steps to work with terraform in real life.

  • Resource Scope - A general idea of what resources you need in your cloud environment to build configuration files for them.
  • Configuration Files - Creating the configuration file based on the scoped resource list.
  • Initialize - Running terraform init in the project directory with the configuration files.
  • Plan & Apply - Running terraform plan to verify creation process and then terraform apply to create resources as well as state file that compares future changes in your configuration files to what actually exists in your deployment environment.

A typical terraform configuration file to deploy a resource group might look something like this:

#Configure the Azure provider
terraform {
  required_providers {
    azurerm = {
      source = "hashicorp/azurerm"
      version = ">= 2.26"
    }
  }
}

provider "azurerm" {
  features {}
}

resource "azurerm_resource_group" "rgname" {
  name     = "somergname"
  location = "location"
}

Installing Terraform on Windows

At this point, you should have a high-level idea of what terraform is and what steps it involves to get it working. The next step is to install the Terraform CLI on your computer so that you can start with it locally. Use the steps below to download and configure the terraform CLI for your local workstation.

  • Download the Executable Zip file for Terraform.
  • Unzip the package downloaded from the official Hashicorp website to any local directory of your choice.
  • Copy the terraform.exe from the extracted files, and store it inside your C:\\Windows folder. This ensures that you can run the terraform commands using PowerShell or CMD from any folder on your computer.
  • If you don't prefer the previous method to store the file inside your Windows directory, you can store the executable anywhere as long as you update your 'Environment Variables' with the path to the terraform executable. See reference for the steps here.

Also, make sure you have Azure CLI installed on your computer as well which is a prerequisite for deploying your infrastructure using terraform CLI. If you are using a Windows machine, you can simply run the following command in an elevated PowerShell session to download the Azure CLI or follow the link here for alternate options.

Invoke-WebRequest -Uri <https://aka.ms/installazurecliwindows> -OutFile .\\AzureCLI.msi; Start-Process msiexec.exe -Wait -ArgumentList '/I AzureCLI.msi /quiet'; rm .\\AzureCLI.msi

Terraform Commands

Now that you have installed the terraform CLI, it's time to confirm that your PATH is set up correctly for using terraform. You might need to restart the terminal session if it was open before you changed the path or terraform executable location.

The first thing you need to do is run the help command to ensure the terminal recognize the terraform command. Run the following command to validate the installation.

PS> terraform -help

If you get an error that terraform could not be found, your PATH environment variable might not be set up properly. Ensure that your PATH variable contains the directory where Terraform executable is stored.

In the next few sections, I'll walk you through the terraform commands that you will be using almost all the time while working on deploying your infrastructure.

Terraform Help

If you got the first command working to validate the installation, go ahead and run the following command to read the help information for various terraform commands. Simply change the last part of the command to read the information about plan, init, apply, destroy, and state.

PS> terraform -help plan

# Output #
Usage: terraform plan [options] [DIR]

Generates an execution plan for Terraform.

This execution plan can be reviewed prior to running apply to get a
sense for what Terraform will do. Optionally, the plan can be saved to
a Terraform plan file, and apply can take this plan file to execute
this plan exactly.

Terraform Init

Terraform init command initialize the provider plug-ins for the project that you build. Think of this as refreshing the state and making sure you have all the components, modules, and external libraries in your project before you go ahead and deploy the infrastructure. You simply run the terraform init to initialize the project. The output of the command will tell you the version details and the plugins it needs to install and initialize.

PS> terraform init

# Output #
Initializing the backend...

Initializing provider plugins...
- Finding hashicorp/azurerm versions matching ">= 2.26.*"...
- Installing hashicorp/azurerm v2.38.0...
- Installed hashicorp/azurerm v2.38.0 (signed by HashiCorp)

Terraform has been successfully initialized!

You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.

If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.

Terraform Plan

Once the terraform init is run, the project is ready for test or deployment. As you make changes to your configuration files, the project requirement changes, hence the plan needs to be updated. Terraform plan does not deploy any resources in the cloud whereas it simply creates a local execution plan of what your infrastructure will look like once deployed in the cloud.

Here's an example of what the output of terraform plan looks like:

PS> terraform plan

# Output #
Refreshing Terraform state in-memory prior to plan...
The refreshed state will be used to calculate this plan, but will not be
persisted to local or remote state storage.

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

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:
## Plan Details
------------------------------------------------------------------------

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.

As you can see, the output describes how the state is changing, and being refreshed followed up by what the execution plan looks like. In this case, the plan will show you the list of actions whether to create or delete a resource based on the changes in your configuration file.

You can optionally save the plan using -out {tfpln} where tfplan is the name of the output file. You can refer to the same plan output file to use it for deployment.

Terraform Apply

Once you run through the execution plan, the next step is to perform the deployment using apply command. Here you can simply run terraform apply to do the planning and deployment, or you can refer to your previous plan if you saved the plan to an external file in the directory.

PS> terraform apply

# Output #

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:
## Plan Details

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:

Terraform Destroy

Now you have created your resources in the cloud using terraform apply, it's worth mentioning that you don't have to go to the cloud portal to delete the resources. You can simply run terraform destroy to delete anything that was deployed using terraform initially. Check the command below with the sample output where you can see that the terraform is going to destroy one resource from your environment.

PS> terraform destroy

# Output #
azurerm_resource_group.rg: Refreshing state... [id=/subscriptions/xxxxx-xxxxx-xxxx/resourceGroups/somename]

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

Terraform will perform the following actions:

  # azurerm_resource_group.rg will be destroyed
  - resource "azurerm_resource_group" "rg" {
      - id       = "/subscriptions/xxxxx-xxxxx-xxxx/resourceGroups/somename" -> null
      - location = "location" -> null
      - name     = "Name" -> null
    }

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:

So, how does terraform know what to destroy anyway? Let's check out what the State is.

Terraform State

As you saw from the commands above that terraform does all the plan, apply, and destroy based on what you have inside your configuration files. It is interesting to note that terraform has to know somehow about what it deploys to the cloud and what to destroy if need be.

When you apply your configuration using the apply command, Terraform writes all the data into a file called terraform.tfstate. This file contains the IDs and properties of the resources Terraform created so that it can manage or destroy those resources going forward.

One important thing to note is that your state file contains all of the data in your configuration and could also contain sensitive values in plaintext. It's not recommended to check out this file to your source control if your configuration files are stored in a public repository.

The alternative to storing state is using Remote Storage. The remote stage storage enables collaboration using Terraform by leveraging a blog storage container for storing all the files but that is beyond the scope of this article.

While inside your project directory, you can inspect the current state using terraform show:

PS> terraform show

# Output #
azurerm_resource_group.rg:
resource "azurerm_resource_group" "somename" {
    id       = "/subscriptions/xxxxx-xxxxx-xxxx/resourceGroups/somename"
    location = "location"
    name     = "Name"
}

Conclusion

I hope you get a high level idea of what terraform is and how you can use this tool to build reusable code along with managing your infrastructure state and configurations. This was simply an introduction to Terraform for Azure if you are someone who has never worked with this tool. Be sure to keep an eye for upcoming articles where I'll show you how to use this tool and start building out your resource in Azure without manual work all using Infrastructure as Code.

Check out the next article in the series here:

Terraform in Action with Azure
Towards Automation: Building the First Terraform Project with Azure

Reference