Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 57 ยท Infrastructure as Code and DevOps

Terraform on Azure

Manage Azure with Terraform: the azurerm provider, plan and apply, state and remote state in Blob Storage, modules, and importing existing resources.

Bicep is Azure's own language for describing infrastructure. Terraform, from HashiCorp, solves the same problem with a tool that works across many platforms: Azure, AWS, Google Cloud, GitHub, Cloudflare, Kubernetes, databases and hundreds more. You write configuration files in HCL (HashiCorp Configuration Language), Terraform compares them with what exists, shows you a plan, and makes only the changes needed. If your company uses more than one cloud, or manages non-Azure services next to Azure ones, one tool and one workflow for everything is the main attraction.

The big difference from Bicep is state. Terraform keeps a record of what it created, and that record has to be stored, shared and protected. Most of the care in a real Terraform setup goes into that. This lesson covers the Azure provider, the plan and apply cycle, state, modules and importing existing resources. Running Terraform against Azure needs an account, so the commands and HCL are read-only. The runnable examples are JavaScript stand-ins for a plan engine and for state locking.

The azurerm provider

Terraform itself knows nothing about Azure. A provider is a plugin that translates resource blocks into API calls. For Azure the main provider is azurerm. A starting file (read-only):

HCL
terraform {
  required_version = ">= 1.9"

  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "~> 4.0"
    }
  }
}

provider "azurerm" {
  features {}
  subscription_id = var.subscription_id
}

variable "subscription_id" {
  type = string
}

variable "environment" {
  type    = string
  default = "dev"

  validation {
    condition     = contains(["dev", "prod"], var.environment)
    error_message = "environment must be dev or prod."
  }
}

variable "location" {
  type    = string
  default = "westeurope"
}

The empty features {} block is required by the provider. Recent major versions also require a subscription ID, which you can supply with a variable or with the ARM_SUBSCRIPTION_ID environment variable. Pin the provider with version so an upgrade never surprises you.

Authentication. On your laptop, az login is enough: the provider uses the Azure CLI's sign-in. In a pipeline, use a service principal or, better, a managed identity or OpenID Connect federation, which avoids stored secrets (see CI/CD with GitHub Actions and Azure DevOps and Managed Identities and Service Principals). That identity needs RBAC roles on the scope it manages (Role-Based Access Control).

Resources and references

HCL
resource "azurerm_resource_group" "main" {
  name     = "shop-${var.environment}-rg"
  location = var.location

  tags = {
    environment = var.environment
  }
}

resource "azurerm_storage_account" "data" {
  name                     = "shop${var.environment}data01"
  resource_group_name      = azurerm_resource_group.main.name
  location                 = azurerm_resource_group.main.location
  account_tier             = "Standard"
  account_replication_type = var.environment == "prod" ? "GRS" : "LRS"
  min_tls_version          = "TLS1_2"

  allow_nested_items_to_be_public = false
}

output "blob_endpoint" {
  value = azurerm_storage_account.data.primary_blob_endpoint
}

A resource has a type (azurerm_storage_account), a local name (data) and arguments. Writing azurerm_resource_group.main.name inside another resource is both a value and a dependency: Terraform builds a graph and creates the group before the account. Resources with no dependencies are created in parallel.

The workflow: init, plan, apply

Terminal
terraform init      # download providers, configure the backend
terraform fmt       # format files
terraform validate  # check syntax and references
terraform plan -out=tfplan
terraform apply tfplan
terraform destroy   # remove everything this configuration manages

terraform plan is the heart of it. It reads the configuration and the state, asks Azure what actually exists, and prints what it would do, marked with symbols:

  • + create
  • ~ update in place
  • - destroy
  • -/+ replace: destroy then create, because a changed argument cannot be updated in place (such as a storage account's name or location)

Always read the plan. Saving it with -out and applying that exact file guarantees you apply what was reviewed.

State

After each apply, Terraform writes a state file that maps each resource in your configuration to a real Azure object (its resource ID and its attributes). State is how Terraform knows that azurerm_storage_account.data is that storage account and not another. Lose it and Terraform thinks nothing exists and tries to create everything again.

Three rules follow:

  1. Never keep state only on one laptop. Use a remote backend so the team shares one copy.
  2. Protect it. State can contain sensitive values such as keys and connection strings. Restrict access and enable encryption.
  3. Never edit it by hand. Use terraform state commands, import and moved blocks.

Remote state in Blob Storage

The azurerm backend stores state as a blob and uses a blob lease as a lock, so two people cannot apply at the same moment:

HCL
terraform {
  backend "azurerm" {
    resource_group_name  = "tfstate-rg"
    storage_account_name = "tfstateshop001"
    container_name       = "tfstate"
    key                  = "shop-prod.tfstate"
    use_azuread_auth     = true
  }
}

You create the state account once, outside the configuration it will hold (a chicken-and-egg problem), for example with the Azure CLI. Turn on blob versioning so earlier versions of the state can be recovered. With use_azuread_auth, access comes from RBAC (a data role such as Storage Blob Data Contributor) instead of account keys; see Storage Security and SAS Tokens. Use a different key per environment, so a mistake in dev cannot touch production.

A plan engine: a stand-in

The real Terraform and Azure are not available here. The stand-in below keeps the planning idea. It holds a configuration (desired), a state (what Terraform believes) and Azure (what really exists). It refreshes state from Azure, diffs desired against state, and labels each resource create, update, replace or destroy. Which arguments force replacement depends on the provider; the lists here are examples.

JS Plan, apply and detect drift

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice the second run: no changes, because the configuration, the state and Azure agree. Then see the drift: Terraform refreshed from Azure, noticed the portal edit and planned to put it back. A changed location was a replacement, which means data loss for a real storage account, so you should read -/+ lines carefully.

State locking: a stand-in

Remote state is protected by a lock. The second stand-in models the Blob lease: whoever acquires it can write state, everyone else is told to wait or fail.

JS Two applies, one lock

Press Run (or Ctrl + Enter) to see the console output here.

No output.

If a run is killed mid-apply, the lock can be left behind. terraform force-unlock <lock-id> clears it, but only do that after you are sure nothing is still running.

Modules

A module is a folder of Terraform files used by another configuration. Every configuration is already a module (the root module); calling others lets you reuse patterns.

HCL
module "network" {
  source = "./modules/network"

  name          = "shop-${var.environment}"
  location      = var.location
  address_space = ["10.20.0.0/16"]
}

resource "azurerm_subnet" "app" {
  name                 = "app"
  resource_group_name  = module.network.resource_group_name
  virtual_network_name = module.network.vnet_name
  address_prefixes     = ["10.20.1.0/24"]
}

Modules take inputs (variables), expose outputs and can come from a local folder, a Git repository or the public Terraform Registry. Microsoft maintains verified modules for common Azure patterns, which are worth a look before you write your own.

Importing existing resources

What if the resource already exists, because someone created it in the portal? Terraform must be told that the real object belongs to a resource block, or its next plan will try to create a duplicate.

Terminal
terraform import azurerm_resource_group.main \
  /subscriptions/<subscription-id>/resourceGroups/shop-dev-rg

Newer Terraform versions also support an import block inside the configuration, which can be planned and reviewed like any other change:

HCL
import {
  to = azurerm_resource_group.main
  id = "/subscriptions/<subscription-id>/resourceGroups/shop-dev-rg"
}

After an import, run terraform plan. If it still shows differences, adjust your configuration until the plan is empty. The resource ID format is the one described in Resource Groups and Azure Resource Manager.

Terraform or Bicep?

Bicep Terraform
Clouds Azure only Many clouds and services
State None to manage (Azure is the source of truth) State file you must store and protect
New Azure features Available quickly Depends on provider releases
Preview what-if plan
Best when Everything is on Azure You manage several platforms or already use Terraform

Neither is wrong. Pick one per project and keep to it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does Terraform's state file record?

    State maps configuration to real resources (IDs and attributes). Without it, Terraform cannot tell what it already created.
  2. 2. A plan line is marked -/+ for a storage account. What will happen?

    -/+ means replacement: a changed argument, such as the name or location, cannot be updated in place, so the resource is destroyed and recreated.
  3. 3. How does the azurerm backend prevent two people from applying at the same time?

    The backend takes a lease on the state blob. A second apply fails to acquire it until the first finishes.
  4. 4. Someone created a resource group in the portal. How do you bring it under Terraform control?

    terraform import (or an import block) attaches the real object to a resource address. Then adjust the code until plan shows no changes.
  5. 5. Why use a different state key for each environment?

    Separate state keeps environments independent, which limits the blast radius of a mistake.

Summary

  • Terraform describes infrastructure in HCL and works across many providers; the azurerm provider manages Azure.
  • The cycle is init, plan, apply; read the plan and watch for -/+ replacements.
  • State links your configuration to real resources; store it in a remote backend such as Blob Storage, with locking, versioning and restricted access.
  • References between resources build a dependency graph.
  • Modules package reusable patterns; imports bring existing resources under management.
  • Bicep suits Azure-only estates without state to manage; Terraform suits multi-platform work.

Next: CI/CD with GitHub Actions and Azure DevOps.