AzureIntermediate

Azure Infrastructure as Code: Using Terraform and ARM Templates

9 min read

TL;DR

Master Infrastructure as Code in Azure with this comprehensive guide covering Terraform, ARM Templates, state management, module development, and pipeline integration.

Azure Infrastructure as Code: Using Terraform and ARM Templates

Executive Summary

Infrastructure as Code turns Azure environments into something you can review, version, and rebuild. This guide compares the two main approaches on Azure — Terraform and ARM templates (with Bicep as their modern authoring layer) — and covers the parts that decide whether an IaC practice survives contact with a team: remote state with locking, modules with stable interfaces, and pipelines that plan on pull requests and apply only from a protected branch. After reading it you will be able to pick a tool for your constraints and structure a repository that other engineers can safely change.

Why This Matters

Click-built infrastructure cannot be audited, reproduced, or rolled back. When an environment exists only as portal state, nobody can answer basic questions: why is this rule open, what changed last Tuesday, can we rebuild this in another region after an incident? The failure mode shows up at the worst time — during a disaster recovery exercise or a real outage, when the team discovers the environment was a snowflake. IaC is the fix, but only if the code is the source of truth. The moment engineers start making portal changes "just this once," the code and the environment diverge and every subsequent deployment becomes a negotiation with drift.

Core Concepts

Terraform vs ARM Templates and Bicep

FeatureTerraformARM templates / Bicep
LanguageHCLJSON (ARM); Bicep is a cleaner DSL that compiles to ARM
StateExternal state file you must store, lock, and protectTracked by Azure Resource Manager; no state file to manage
ScopeMulti-cloud and multi-vendor providersAzure only
Previewterraform plan shows a detailed diff before applyWhat-if operation shows intended changes
EcosystemLarge module registry across cloudsNative, first-party support for new Azure features on day one

The deciding factors are usually organisational: a team standardising across clouds picks Terraform; a team that is Azure-only and wants new Azure features immediately, with no state file to guard, often picks Bicep.

Terraform: Resources and Modules

A Terraform configuration declares resources in HCL, and the azurerm provider maps them to ARM operations:

# Provider configuration
provider "azurerm" {
  features {}
}

# Resource group
resource "azurerm_resource_group" "example" {
  name     = "example-resources"
  location = "East US"

  tags = {
    environment = "Production"
    department  = "IT"
  }
}

# Virtual network
resource "azurerm_virtual_network" "example" {
  name                = "example-network"
  resource_group_name = azurerm_resource_group.example.name
  location            = azurerm_resource_group.example.location
  address_space       = ["10.0.0.0/16"]

  subnet {
    name           = "subnet1"
    address_prefix = "10.0.1.0/24"
  }

  subnet {
    name           = "subnet2"
    address_prefix = "10.0.2.0/24"
  }
}

# Storage account
resource "azurerm_storage_account" "example" {
  name                     = "examplestorageacc"
  resource_group_name      = azurerm_resource_group.example.name
  location                 = azurerm_resource_group.example.location
  account_tier             = "Standard"
  account_replication_type = "LRS"

  tags = {
    environment = "Production"
  }
}

Modules package a repeatable pattern behind variables and outputs. The discipline that makes modules work: a small, stable interface, sensible defaults, and no environment-specific values baked in.

# modules/webapp/main.tf
variable "name" {
  type        = string
  description = "Name of the web app"
}

variable "location" {
  type        = string
  description = "Azure region"
}

variable "resource_group_name" {
  type        = string
  description = "Resource group name"
}

resource "azurerm_app_service_plan" "example" {
  name                = "${var.name}-plan"
  location            = var.location
  resource_group_name = var.resource_group_name

  sku {
    tier = "Standard"
    size = "S1"
  }
}

resource "azurerm_app_service" "example" {
  name                = var.name
  location            = var.location
  resource_group_name = var.resource_group_name
  app_service_plan_id = azurerm_app_service_plan.example.id

  site_config {
    dotnet_framework_version = "v4.0"
    scm_type                 = "LocalGit"
  }

  app_settings = {
    "WEBSITE_NODE_DEFAULT_VERSION" = "10.14.1"
  }
}

output "webapp_url" {
  value = azurerm_app_service.example.default_site_hostname
}

ARM Templates and Bicep

ARM templates declare the same resources in JSON, evaluated directly by Azure Resource Manager:

{
    "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "storageAccountName": {
            "type": "string",
            "metadata": {
                "description": "Name of the storage account"
            }
        },
        "location": {
            "type": "string",
            "defaultValue": "[resourceGroup().location]",
            "metadata": {
                "description": "Location for resources"
            }
        }
    },
    "variables": {
        "storageAccountSku": "Standard_LRS"
    },
    "resources": [
        {
            "type": "Microsoft.Storage/storageAccounts",
            "apiVersion": "2021-04-01",
            "name": "[parameters('storageAccountName')]",
            "location": "[parameters('location')]",
            "sku": {
                "name": "[variables('storageAccountSku')]"
            },
            "kind": "StorageV2",
            "properties": {
                "supportsHttpsTrafficOnly": true,
                "minimumTlsVersion": "TLS1_2",
                "allowBlobPublicAccess": false
            }
        }
    ],
    "outputs": {
        "storageAccountId": {
            "type": "string",
            "value": "[resourceId('Microsoft.Storage/storageAccounts', parameters('storageAccountName'))]"
        }
    }
}

Raw ARM JSON is verbose, which is why Bicep exists: same deployment engine, a far more readable language. Large ARM estates are usually composed with linked templates — a main template invoking nested deployments — while Bicep achieves the same composition with modules inside one project.

State Management (Terraform)

Terraform's state file records which real resources your configuration owns. Losing it, corrupting it, or letting two applies write it concurrently are the classic Terraform disasters, so remote state with locking is not optional. On Azure, the azurerm backend stores state in Blob Storage and locks via blob leases:

# Backend configuration
terraform {
  backend "azurerm" {
    resource_group_name  = "terraform-state-rg"
    storage_account_name = "terraformstate"
    container_name       = "tfstate"
    key                  = "prod.terraform.tfstate"
  }
}

Bootstrap the state storage itself once, with versioning on so a bad write can be rolled back:

# State locking
resource "azurerm_storage_account" "state" {
  name                     = "terraformstate"
  resource_group_name      = "terraform-state-rg"
  location                 = "East US"
  account_tier             = "Standard"
  account_replication_type = "LRS"

  blob_properties {
    versioning_enabled = true
  }
}

resource "azurerm_storage_container" "state" {
  name                  = "tfstate"
  storage_account_name  = azurerm_storage_account.state.name
  container_access_type = "private"
}

Treat state as sensitive: it contains resource attributes, sometimes including secrets. Restrict who and what can read the storage account, and use one state per environment rather than one state for everything.

Pipeline Integration

The pipeline pattern that works: on a pull request, run format checks, validation, and plan (or what-if), and post the diff to the PR. On merge to the protected branch, apply — with an approval gate for production. The pipeline identity should be a service principal or federated workload identity with the minimum scope it deploys to.

trigger:
  branches:
    include:
    - main
  paths:
    include:
    - terraform/*

variables:
  - group: terraform-vars

stages:
- stage: Validate
  jobs:
  - job: ValidateAndPlan
    pool:
      vmImage: 'ubuntu-latest'
    steps:
    - task: TerraformInstaller@0
      inputs:
        terraformVersion: '1.0.0'

    - task: TerraformTaskV3@3
      inputs:
        provider: 'azurerm'
        command: 'init'
        backendServiceArm: '$(AZURE_SUBSCRIPTION)'
        backendAzureRmResourceGroupName: '$(BACKEND_RG)'
        backendAzureRmStorageAccountName: '$(BACKEND_SA)'
        backendAzureRmContainerName: '$(BACKEND_CONTAINER)'
        backendAzureRmKey: '$(BACKEND_KEY)'

    - task: TerraformTaskV3@3
      inputs:
        provider: 'azurerm'
        command: 'plan'
        environmentServiceNameAzureRM: '$(AZURE_SUBSCRIPTION)'

- stage: Apply
  dependsOn: Validate
  condition: succeeded()
  jobs:
  - deployment: ApplyTerraform
    environment: 'Production'
    strategy:
      runOnce:
        deploy:
          steps:
          - task: TerraformTaskV3@3
            inputs:
              provider: 'azurerm'
              command: 'apply'
              environmentServiceNameAzureRM: '$(AZURE_SUBSCRIPTION)'
              commandOptions: '-auto-approve'

Testing and Validation

Test typeToolPurpose
Static analysistflintSyntax and provider-rule validation
Security scanningtfsec / CheckovFlag insecure defaults before deployment
Policy complianceAzure Policy, CheckovEnforce organisational rules on what may be deployed
Integration testsTerratestDeploy real infrastructure and assert behaviour

Layer these cheap-to-expensive: lint and security scans on every PR, integration tests on a schedule or for module changes, since they cost real money and time.

Decision Framework

SituationRecommendation
Multi-cloud estate or existing Terraform standardTerraform with azurerm backend per environment
Azure-only team wanting day-one feature support and no state fileBicep (ARM underneath)
Small team, first IaC adoptionWhichever the team will actually maintain; Bicep has the shorter path on Azure
Regulated environment needing deployment evidenceEither tool, with plan/what-if output archived from the pipeline as the change record
Frequently changing shared platform componentsVersioned modules with a changelog, consumed by pin, not by branch

Implementation Checklist

  • [ ] Remote state configured with locking and versioning (Terraform), stored in a dedicated, access-restricted resource group
  • [ ] One state/workspace per environment; production state isolated from non-production
  • [ ] Pull requests run format, validate, lint, security scan, and plan/what-if, with the diff visible to reviewers
  • [ ] Apply runs only from a protected branch, with an approval gate for production
  • [ ] Pipeline identity is least-privilege and cannot read state it does not own
  • [ ] Modules have documented inputs/outputs and pinned versions; consumers upgrade deliberately
  • [ ] Drift is detected on a schedule (plan with no changes expected) and reconciled through code, not portal edits
  • [ ] Secrets are referenced from Key Vault, never committed in variable files
  • Trade-offs

    Terraform's plan is the best pre-deployment review tool in the category, but you own the state file's safety, and provider coverage for brand-new Azure features can lag the portal. ARM and Bicep remove the state problem and track Azure features immediately, at the cost of Azure lock-in and a what-if output that can be noisier than a Terraform plan. Both approaches share one limit: IaC describes the resources it manages and nothing else — configuration inside a VM or a database still needs a configuration tool, and pretending otherwise produces half-managed estates.

    When Not to Use

  • Terraform is the wrong choice when the estate is Azure-only and small enough that Bicep's zero-state simplicity wins, or when the team has no appetite for state stewardship.
  • Hand-written ARM JSON is the wrong choice for new work of any size; author in Bicep and let it compile to ARM.
  • IaC pipelines with auto-approve everywhere are the wrong choice for production: the plan review is the control. Removing it to save minutes trades away the main safety property the pipeline exists to provide.
  • Conclusion

    Pick the tool your organisation can standardise on, then invest in the surrounding discipline: isolated state, reviewed plans, versioned modules, and drift detection. The tool decision is reversible far more easily than the habit of treating the code as the source of truth — and that habit, not the syntax, is what makes infrastructure reproducible.

    Why This Matters

    Understanding the business and technical context helps you make informed decisions rather than blindly following patterns.

    Trade-offs to Consider

    Every architectural decision involves trade-offs. Consider your specific requirements, team expertise, and scale when evaluating options.

    When NOT to Use This

    Knowing when a solution doesn't apply is as valuable as knowing when it does. Consider alternatives for your specific situation.

    Decision Framework

    Use this framework to evaluate whether this approach is right for your use case based on your specific constraints and requirements.

    Share this articleShare on XShare on LinkedIn

    Keep the decision frameworks coming

    One practical architecture guide a week — patterns, trade-offs, and when not to use them. No spam, unsubscribe anytime.