Getting Started with Terraform on Microsoft Azure

Safely and consistently manage your Azure infrastructure using Infrastructure as Code.

Erik Burger
NAVARA
Published in
6 min readOct 1, 2023

--

In this article, you’ll learn how to install and configure Terraform to connect to Microsoft Azure. You’ll then create your first resource using Terraform.

What is Infrastructure as Code?

Infrastructure as Code (IaC) is a method of managing and providing IT infrastructure using machine-readable scripts or code rather than manual configuration. It enables DevOps teams to use code to describe and automate the setup and maintenance of infrastructure resources such as servers, networks, and databases.

IaC has various benefits, including higher consistency, repeatability, and scalability of infrastructure deployments, faster and more reliable provisioning. It also allows for the use of version control and documentation of infrastructure configurations, making it easier to trace changes and rollbacks. It aligns perfectly with core DevOps principles of automation, collaboration, and continuous integration and delivery (CI/CD).

What is Terraform?

A lot of different tools exist to enable a team to use IaC, like Ansible and AWS Cloudformation, and which tool to use depends a lot on the use case, as well as on the availability of skills within your team.

Terraform, by HashiCorp, is one of the most well-known IaC tools. One of its key benefits over other tools is its multi-cloud support, allowing users to manage infrastructure consistently across various cloud platforms, including AWS, Azure, Google Cloud, and more. Terraform’s state management ensures efficient and safe updates to infrastructure, and its plan-driven approach provides a clear preview of changes before they are applied, enhancing predictability and reducing the risk of errors.

Installing Terraform

The easiest way to install Terraform on OS X is using Homebrew. Inside a Terminal, run:

brew tap hashicorp/tap

This installs the HashiCorp tap, which contains all their packages.

Installing HashiCorp tap.

Then, to install Terraform, run:

brew install hashicorp/tap/terraform
Installing Terraform.

You can run terraform -version to check whether Terraform was installed successfully.

Terraform version.

Connecting to Azure

In order to use Terraform to create resources on Microsoft Azure, you’ll need to have an Azure subscription. If you don’t have one, you can create one here.

You also need the Azure CLI installed. Using Homebrew again:

brew update && brew install azure-cli

Log in to Azure

In your terminal, type az login to log in to your Azure subscription. This will open a browser window, which you can close again after you successfully authenticate. The output will look something like this:

Output from az login.

Then set the active subscription using the id field from the above output:

az account set -s "<id>"

Create a Service Principal

Terraform needs a Service Principal to be able to go into your Azure subscription and make changes. The Service Principal needs the Contributor role in order to do this:

az ad sp create-for-rbac --role="Contributor" --scopes="/subscriptions/<id>"

Again, replace <id> with the active subscription id. Your output will look something like this:

Creating a Service Principal.

Setup environment variables

Terraform needs a set of environment variables to connect to your Azure subscription. Replace the values between < > with the values from the outputs above.

export ARM_CLIENT_ID="<appId>"
export ARM_CLIENT_SECRET="<password>"
export ARM_SUBSCRIPTION_ID="<id>"
export ARM_TENANT_ID="<tenant>"

Now that you have Terraform installed and connected to your Azure subscription, you can start creating your first resource.

Creating a Resource Group

In Azure, Resource Groups are used to, well, group resources. Any resource has to belong to a Resource Group, and they’re a very convenient way to organize larger numbers of resources that belong together, such as the resources in your test, acceptance, and production environments.

Or, in this case, to the With Terraform series.

Create a folder with-terraform.

Inside the folder, create a new file called main.tf. tf is the file extension for Terraform files.

Configure the Azure provider

To start, we need to configure Terraform to use the Azure provider. A provider determines which cloud infrastructure you can manage using Terraform.

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

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

required_version = ">= 1.5.7"
}

provider "azurerm" {
features {}
}

This configures the required_provider to be Azure, and to use version 3.75.0. The ~> sign allows for patch updates, but nothing else. We also specify the required_version for Terraform to be at least 1.5.7.

Now, run terraform init in your terminal top initialize Terraform with your configuration.

Initializing Terraform.

You can see that it automatically installs the correct version of the Azure provider. It also created a lock file to make sure the configuration doesn’t change by accident.

Adding a Resource Group

Now, let’s add a Resource Group. Add the following code at the bottom of your main.tf file.

# Create a resource group
resource "azurerm_resource_group" "rg-wtf" {
name = "rg-with-terraform"
location = "West Europe"
}

This instructs Terraform that a resource group called rg-with-terraform should be created, in the West Europe region. To reference the resource group in our Terraform configuration, we’re specifying rg-wtf as the name of this particular resource group.

The location property supports specifying the Azure region in several formats.

Creating the Resource Group

To create the Resource Group in Azure, you use two separate commands.

First, use terraform plan to preview what changes will be made to your Azure subscription.

Terraform plan, or “what does this button do?”

The output tells us that one resource will be created, which is our rg-with-terraform Resource Group. Nothing’s going to be changed or destroyed. It's looking good so far.

While, technically, running terraform plan is optional, it is always a good idea to check before you do something you’ll regret. As Robin Hobb said in Assassin’s Apprentice: “Don’t do what you can’t undo, until you’ve considered what you can’t do once you’ve done it.” I think this quote counts double, when Terraform is involved.

Then, run terraform apply -auto-approve to apply your changes to your Azure subscription (it’s safe to add the auto-approve flag, since you ran terraform plan like, a few seconds ago).

Terraform apply, or “terraformus azurus!

This really is the coolest part of this entire tutorial 😎

If you check your Azure subscription, you can see that the Resource Group was successfully created.

Successfully created Resource Group in the Azure portal.

Cleaning up

At one point, you should clean up any resources you created using Terraform. terraform destroy destroys all the resources you defined in your configuration, leaving your Azure subscription nice and clean.

Terraform destroy, or “here comes the BOOM!”

Conclusion

In this article, you learned how to use Terraform to create a Resource Group in Microsoft Azure.

Terraform is an incredibly powerful tool to have in your arsenal, if you are serious about Infrastructure as Code in particular, and DevOps in general.

Being able to manage your infrastructure safely and consistently (albeit not always quickly as your infrastructure grows), allows you and your team to respond quicker to changing business requirements, and to keep an edge on the competition.

Quick reference of Terraform commands

terraform init initializes the Terraform configuration, preparing the working directory for use.

terraform plan generates an execution plan, outlining the actions Terraform will take to achieve the desired state, aka what resources will be added, changed, and/or destroyed.

terraform apply applies the changes described in the execution plan. The auto-approve flag can be used to bypass interactive approval.

terraform destroy destroys all the resources defined in your Terraform configuration, cleaning up your infrastructure.

--

--

Erik Burger
NAVARA
Editor for

Poly-passionate. Coder, writer, technical lead, coach. Also into mindset, fitness, productivity, finance and personal development.