How to Use the Terraform Azure Provider to Deploy Cloud Resources

Microsoft Azure

If you plan to manage and work with Azure along with Terraform, using the Azure provider is a must. The Terraform Azure Provider lets you interact with the many resources supported by Microsoft Azure.

In this ultimate guide, you’re going to learn, step-by-step, about everything you need to know about the Azure Provider and how to use this provider with Terraform to manage your Azure cloud infrastructure.

Let’s get started!

Prerequisites

This tutorial comprises step-by-step instructions. If you’d like to follow along, be sure you have the following in place:

  • Azure account. You can create a free Azure account or use an existing sandbox subscription. Either should work.
  • Azure subscription
  • Terraform – This tutorial will use Terraform v1.0 running on Ubuntu 18.04.5 LTS. Still, any operating system that Terraform supports should work.
  • Azure CLI version 2.0.79 or newer. To install the Azure CLI, consider running the below command.
sudo curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash

What Is Terraform?

Terraform is a tool for building, versioning, and managing the infrastructure in an automated way. Terraform is an Infrastructure-as-Code (IaC) tool that simplifies your infrastructure management by using a simple syntax language called HashiCorp Configuration Language (HCL), which is easier than YAML or JSON formats.

Terraform is used with various cloud providers such as Amazon AWS, Oracle, Microsoft Azure, Google Cloud, and many more.

Terraform has dozens of benefits, and some of the key features are:

  1. Terraform allows you to reuse code multiple times and keep various versions of code, which can be shared among other Terraform developers and administrators.
  2. One of the best parts of Terraform is that it generates execution plans, which are a blueprint showing you all the infrastructure changes or updates that will be provisioned in the cloud without actually being deployed.
  3. If you wish, you can generate a Terraform resource graph that makes it easy to understand the infrastructure and resources; and build resources as efficiently as possible. It gives you greater insight into your infrastructure.
  4. Finally, Terraform applies complex changes to your infrastructure with little human interaction. When updating configuration files, Terraform determines what changed and it creates incremental execution plans that respect dependencies.

Terraform is an easy-to-use tool that generally requires three commands to run: terraform initterraform plan, and terraform apply. You will learn them later in the guide.

How to use the Terraform Azure Provider?

Terraform depends on plugins to interact with cloud providers such as Azure, Google Cloud Platform (GCP), and Oracle. One of the most widely used providers is the Terraform Azure provider. The provider interacts with many resources supported by Azure, such as Azure SQL, Azure Data FactoryAzure Active Directory, and many more.

Terraform uses the Azure provider with proper credentials to authenticate and connect with Azure to manage or deploy/update dozens of Azure services.

Terraform supports multiple methods for authenticating to Azure, such as authenticating to Microsoft Azure using the Azure CLI and Managed Service Identity, etc. But this tutorial will authenticate using Azure CLI. So, let’s dive in.

Authenticating to Microsoft Azure using Azure CLI

The easiest way to test Terraform resource management is by authenticating with Azure CLI. If you want to try creating resources on your local machine or in a dev environment, consider using the Azure CLI as your authentication method. Let’s learn how to use Azure CLI and configure it for Terraform.

To install Azure CLI on an Ubuntu machine, click here

  1. Log in to the Ubuntu machine using your favorite SSH client.
  2. First, need to log in to the Azure CLI using the below command.
az login

Log in to the Azure CLI

  1. After logging in to Azure CLI, list the subscriptions associated with the account by running the below command. After you execute the az account list command, you should see the list of subscriptions with details such as tenant id, etc.
az account list

List the associated subscriptions

  1. Next, once you have a list of all subscriptions, you can specify the subscription that you need to work with via the following command. By default, you only need to specify a subscription ID using the – subscription parameter if you have multiple subscriptions associated with the account.
az account set --subscription="SUBSCRIPTION_ID"
  1. Now that you have successfully configured the Azure CLI, it’s time to configure the Terraform provider block with the credentials you just configured.
  2. The Azure Provider is declared within the Terraform configuration file and it includes various parameters such as version, endpoint URLs or cloud regions, etc., as shown below.
terraform {
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "=2.46.0"
    }
  }
}

# Configure the Microsoft Azure Provider (azurerm provider) in provider blocks.

provider "azurerm" {
  features {}
}

Callout: Find out more about authenticating with Terraform Azure cloud infrastructure.

How to create an Azure Resource from a template?

Previously you learned how to declare the Terraform Azure Provider, which is excellent, but you will be required to manage resources in the Azure cloud.

In the Azure cloud, a resource can be a virtual machine (VM), storage accounts, web apps, databases, virtual networks, etc. Creating resources with Terraform templates is an easy process; let’s learn how to create an Azure resource from a Terraform template.

Terraform templates are configuration files that contain the code, or multiple configuration files, that you use to build or provision resources in the Azure cloud. There are mainly five configuration files that Terraform has: main.tf, vars.tf, provider.tf, output.tf and terraform.tfvars.

  • Main.tf allows you to define all the resources you want to create in Azure. The resources are defined in the file in resource blocks or module blocks. Also, main.tf contains variables such as var.name, var.location, etc. These variables have their values defined in another file named terraform.tfvars, which you will create later in this section.

The code below will create a Linux virtual machine in Azure with standard_F2 size.

resource "azurerm_linux_virtual_machine" "petri_instance" {
  name                = var.name
  resource_group_name = var.resource_group
  location            = var.location
  size                = "Standard_F2"
  }
}
  • vars.tf is a Terraform variables file containing the configuration file’s (main.tf) variables. The variables below defined in vars.tf are referred to in main.tf.

The vars.tf file below contains two string variables named location and name.

variable "location" { type = string}variable "name" {}
  • Output.tf – if you want Terraform to provide you with details, such as Azure Resource Name (ARN) and resource id after a resource is provisioned in Azure, you need to declare it in this file. You can specify all the resources you need to find the output for.
  • Terraform.tfvars files contain values that you want to pass to Azure. terraform.tfvars contains the values Terraform uses to replace the variable references inside a configuration file (main.tf).
name = petri_instancelocation = West Europe

To deploy the Terraform files as shown above, below are the commands that you should run in the directory where these files reside:

  • terraform init → This command looks through all the *.tf files in the current working directory. It automatically downloads providers Azure needs to provision infrastructure.
  • terraform plan → This command determines what actions are necessary to achieve the desired state specified in the configuration files. This is a dry run and shows which actions will be made.
  • terraform apply → The terraform apply command will create resources as per the config file.
  • terraform destroy → The terraform destroy command will destroy the configuration created based on the tfstate file.

How to create an Azure resource group?

If you are looking to manage several resources in one go, then you need to create an Azure resource group. Resource groups include all the resources you would like to operate as a group and that you think should be managed together. It becomes easier to deploy, manage, and delete the resources in a group with a resource group.

Now, let’s learn how to create an Azure resource group using the Terraform Azure provider.

  • First, create a folder called terraform-azure-demo in your home directory, as shown below.
mkdir ~/terraform-azure-democd ~/terraform-azure-demo
cd ~/terraform-azure-demo
  • Next, create another file named main.tf and copy/paste the below code.

The code below contains the name of a new Azure resource group petri_rg, and its location in West Europe, which specifies where this resource group will be created. While this resource group will be created with the name petri_rg, the instance under this resource group will be tagged with the name petri_instance.

resource "azurerm_resource_group" "petri_rg" { 
    name = petri_rg
    location = West Europe
    tags = {     
      InstanceType = petri_instance
       } 
  }

Now, use the terraform init command shown below to run Terraform.

terraform init

As you can see below, the Terraform has been successfully initialized.

Initialize Terraform

  • Next, run the terraform plan command. It doesn’t actually deploy or provision the resources but it provides you the details of what all Terraform plans do in the infrastructure, as shown below.
terraform plan

Once the Terraform plan is executed, you will see something like ‘Plan: Number of resources to add, Number of resources to change, and Number of resources to destroy.’

Execute a plan

  • Finally, deploy the resource, i.e.. the Azure resource group using the terraform apply command.

As you can see below, the resources have been successfully deployed as the display shows ‘Apply complete, 1 resource has been added.’

Deploy resources from the command line

Once the resource is deployed with Terraform, verify it by navigating Azure and checking Resource groups on the main dashboard. You can see below that the specified resource group has been created successfully.

Verify resource deployment by navigating Azure management portal and checking Resource groups on the main dashboard

How to use built-in variables in Terraform templates?

In the previous section, you learned how to create an Azure resource using hardcoded values instead of dynamic variables, but if you need to reuse the variable file across different projects then consider defining them as variables in variable file referencing in the main file and retrieving the values from values file.

Let’s learn some of the built-in variables that are used in Terraform, as shown below.

There are multiple variable types available in Terraform, such as string, list, Boolean, etc. As you can see, the code snippet below contains a string variable.

variable "location" {
    type = string
    description = "Azure location where the resource will exist."
    default = "westus2"
}

The label after the variable keyword is a variable that should contain the location, and it should be a unique value in the module. Further, the name is used to assign a value to the variable from outside and to reference the variable’s value from within the module.

Inside the variable block, you have the following arguments (optional) for variable declarations such as:

  1. default – the default value sets the default value.
  2. type – the type argument specifies what value types are accepted for the variable.
  3. description – With description, you can specify the input variable’s documentation, i.e. some notes about the purpose of the code.
  4. validation – if you need to provide validation rules, you can add them in this type.
  5. sensitive – if you set the sensitive value to true, then the Terraform UI output will skip this; otherwise, you will see the values in the Terraform output if set it is set to false.
  6. nullable – if you don’t want to specify any value, then you can set nullable true

How to use variables in Terraform templates?

Up to now, whatever resource or resource group you provisioned in Azure had all the variables with specified values; that is, all the values are hardcoded. But if you need to create dynamic and more flexible Terraform configurations, consider adding variables in your configuration files.

Declaring the variables allows you to share modules across different Terraform configurations, making your module reusable. There are different types of variables used in Terraform, such as Boolean, list, string, maps, etc. Let’s see how different types of terraform variables are declared.

In the code below you will see different types of variables are declared with the following characteristics:

  • Each input variable in the module must be declared using a variable block as shown below.
  • The label after the variable keyword is a name for the variable, which should be unique within the same module
  • The following arguments can be used within the variable block:
    • default – A default value allows you to declare the value in this block only and makes the variable optional.
    • type – This argument declares the value types.
    • description – You can provide the description of the input variables.
    • validation -To define validation rules if any.
    • sensitive – If you specify the value as sensitive then terraform will not print the values in while executing.
    • nullable – Specify null if you don’t need any value for the variable.
# Declaring the variable1 of type boolean

variable "variable1" {                        
  type        = bool
  default     = false
  description = "boolean type variable"
}


# Declaring the variable2 of type map

variable  "variable2" {                       
   type    = map
   default = {
      us-east-1 = "image-1"
      us-east-2 = "image2"
    }
}


# Declaring the variable3 of type list

variable "variable3" {                   
  type    = list(string)
  default = []
  description = "list type variable"
}

#   Declaring the variable4 of type list(object))

variable "variable5" {                        
 type =  list(object({
  instancetype        = string
  minsize             = number
  maxsize             = number

 

Conclusion

With this ultimate guide, you now have the knowledge you need to work with the Azure Provider, from declaring to executing the Azure Provider within Terraform. You also learned how the Azure Provider allows you to securely declare credentials in many ways.

Now, which Azure service do you have in mind to manage with the Azure Provider and Terraform? If you’re working with AWS resources, you can also check out our separate guide for the Terraform Azure provider.