Terraform Labs · Lab 8 of 9

Azure: A Linux VM with cloud-init and State in Blob Storage

Create a resource group, virtual network, subnet with a network security group, static public IP and a Linux VM (B1s) configured by cloud-init, with SSH keys only, a managed identity, and Terraform state in a storage account accessed with Entra ID instead of account keys.

Environment
Azure
Level
Intermediate
Time
About 55 min
Cost
Free tier for new accounts, otherwise ≈ $0.02 per hour

You will build

A web server on Azure with the same structure as the AWS and Google Cloud labs, so you can see what is different between clouds — and how much stays the same.

Before you start

Members can save this page, take notes and track progress. See membership · Sign in

The Azure provider needs a real sign-in even to plan, so the plan and apply steps describe what to look for instead of showing output.

What you will build

  • Subscription and resource group shop-dev-rg: every Azure resource lives in a resource group, and deleting the group deletes everything in it.
  • VNet 10.20.0.0/16 with subnet web 10.20.1.0/24, protected by a network security group (NSG) that allows only tcp/80 from your CIDR.
  • Public IP (static, Standard SKU) attached to the VM's network interface (NIC), which holds its private address.
  • Linux VM B1s: Ubuntu 24.04 with nginx installed by cloud-init, SSH key login only, and a system-assigned managed identity for reaching other Azure services without secrets.
InternetusersSubscriptionResource group shop-dev-rgPublic IPstatic, StandardVNet 10.20.0.0/16Subnet web 10.20.1.0/24NSG: allow tcp/80from your CIDR, rest deniedNICprivate IPLinux VMB1s, Ubuntu 24.04Managed identitysystem-assignedcloud-initinstalls nginxSSH key onlyno passwords
What the Azure lab builds: a resource group holding a VNet, an NSG-protected subnet and a Linux VM

Project structure

azure-web/
├── .gitignore
├── versions.tf    # provider and empty azurerm backend
├── backend.hcl    # backend settings for terraform init
├── variables.tf
├── network.tf     # resource group, VNet, subnet, NSG, public IP, NIC
├── compute.tf     # Linux VM with cloud-init
└── outputs.tf

Download starter filesDownload finished project

Steps

  1. 1Sign in and pick a subscription

    Run
    az login
    az account show --query "{name:name, id:id}" -o table
    export TF_VAR_subscription_id=$(az account show --query id -o tsv)
    
    Check:

    The table shows the subscription you want to use for the lab.

  2. 2Create state storage that uses Entra ID

    Shared-key access is turned off, so the only way in is an Entra ID identity with a data role — the same way CI will authenticate later. Blob versioning keeps every state revision.

    The state is a blob in a container of a storage account, kept in its own resource group tfstate-rg. With use_azuread_auth = true, Terraform signs in with your Entra ID token (from az login, or OIDC in CI); the Storage Blob Data Contributor role grants access, and shared keys are turned off. A blob lease is the lock while a run is applying.

    terraform initaz login (Entra ID)Resource group tfstate-rgStorage account acmetfstate12345Container tfstateshop/dev/azure-web.tfstatestate blobBlob leasethe lock while applyingtokenuse_azuread_auth = true: your role Storage Blob Data Contributor grants access; account keys are off
    Remote state on Azure: a blob in a storage account, reached with an Entra ID token instead of keys
    Run
    az group create -n tfstate-rg -l eastus
    az storage account create -n acmetfstate12345 -g tfstate-rg -l eastus --sku Standard_LRS \
      --min-tls-version TLS1_2 --allow-blob-public-access false --allow-shared-key-access false
    az role assignment create --role "Storage Blob Data Contributor" \
      --assignee $(az ad signed-in-user show --query id -o tsv) \
      --scope $(az storage account show -n acmetfstate12345 -g tfstate-rg --query id -o tsv)
    az storage account blob-service-properties update -n acmetfstate12345 -g tfstate-rg --enable-versioning true
    az storage container create -n tfstate --account-name acmetfstate12345 --auth-mode login
    
    Check:

    The container is created. Storage account names are global: replace acmetfstate12345 with your own (3-24 lowercase letters and digits) everywhere, including backend.hcl.

    Hint

    If the container step says you lack permission, wait a minute: new role assignments take a moment to apply.

  3. 3Provider and a partial backend

    As in the Google Cloud lab, the backend block is empty in code and backend.hcl fills in the storage account, container and key at init.

    versions.tfbackend "azurerm" {}backend.hclaccount, container, keyterraform init-backend-config=backend.hclStorage accountStateazure-web.tfstateLockblob lease while applyingThe backend block stays empty in code; each environment passes its own settings at init
    Partial backend configuration: an empty backend block plus a settings file read at init
    versions.tf
    terraform {
      required_version = ">= 1.6"
    
      required_providers {
        azurerm = {
          source  = "hashicorp/azurerm"
          version = "~> 5.0"
        }
      }
    
      # Settings come from backend.hcl: terraform init -backend-config=backend.hcl
      backend "azurerm" {}
    }
    
    provider "azurerm" {
      features {}
      subscription_id = var.subscription_id
    }
    
  4. 4Backend settings

    backend.hcl
    resource_group_name  = "tfstate-rg"
    storage_account_name = "acmetfstate12345" # the account you create in step 2
    container_name       = "tfstate"
    key                  = "shop/dev/azure-web.tfstate"
    use_azuread_auth     = true # Entra ID login instead of storage account keys
    
  5. 5Inputs

    variables.tf
    variable "subscription_id" {
      description = "Azure subscription ID (az account show --query id -o tsv)"
      type        = string
    }
    
    variable "location" {
      type    = string
      default = "eastus"
    }
    
    variable "name" {
      description = "Name prefix for every resource"
      type        = string
      default     = "shop"
    }
    
    variable "environment" {
      type    = string
      default = "dev"
    }
    
    variable "vm_size" {
      description = "Standard_B1s is included in the 12-month free services for new accounts"
      type        = string
      default     = "Standard_B1s"
    }
    
    variable "ssh_public_key_path" {
      description = "Public key for the admin user"
      type        = string
      default     = "~/.ssh/id_ed25519.pub"
    }
    
    variable "allowed_http_cidr" {
      description = "Who may open the web page. Use your own IP with /32 to keep it private."
      type        = string
      default     = "0.0.0.0/0"
    
      validation {
        condition     = can(cidrhost(var.allowed_http_cidr, 0))
        error_message = "allowed_http_cidr must be a valid IPv4 CIDR block."
      }
    }
    
  6. 6Network

    On Azure everything lives in a resource group. The network security group allows only HTTP and is attached to the subnet, so every VM in it gets the same rules.

    network.tf
    locals {
      prefix = "${var.name}-${var.environment}"
      tags = {
        Project     = var.name
        Environment = var.environment
        ManagedBy   = "terraform"
      }
    }
    
    resource "azurerm_resource_group" "main" {
      name     = "${local.prefix}-rg"
      location = var.location
      tags     = local.tags
    }
    
    resource "azurerm_virtual_network" "main" {
      name                = "${local.prefix}-vnet"
      resource_group_name = azurerm_resource_group.main.name
      location            = azurerm_resource_group.main.location
      address_space       = ["10.20.0.0/16"]
      tags                = local.tags
    }
    
    resource "azurerm_subnet" "web" {
      name                 = "web"
      resource_group_name  = azurerm_resource_group.main.name
      virtual_network_name = azurerm_virtual_network.main.name
      address_prefixes     = ["10.20.1.0/24"]
    }
    
    resource "azurerm_network_security_group" "web" {
      name                = "${local.prefix}-web-nsg"
      resource_group_name = azurerm_resource_group.main.name
      location            = azurerm_resource_group.main.location
      tags                = local.tags
    
      security_rule {
        name                       = "allow-http"
        priority                   = 100
        direction                  = "Inbound"
        access                     = "Allow"
        protocol                   = "Tcp"
        source_port_range          = "*"
        destination_port_range     = "80"
        source_address_prefix      = var.allowed_http_cidr
        destination_address_prefix = "*"
      }
    }
    
    resource "azurerm_subnet_network_security_group_association" "web" {
      subnet_id                 = azurerm_subnet.web.id
      network_security_group_id = azurerm_network_security_group.web.id
    }
    
    resource "azurerm_public_ip" "web" {
      name                = "${local.prefix}-web-ip"
      resource_group_name = azurerm_resource_group.main.name
      location            = azurerm_resource_group.main.location
      allocation_method   = "Static"
      sku                 = "Standard"
      tags                = local.tags
    }
    
    resource "azurerm_network_interface" "web" {
      name                = "${local.prefix}-web-nic"
      resource_group_name = azurerm_resource_group.main.name
      location            = azurerm_resource_group.main.location
      tags                = local.tags
    
      ip_configuration {
        name                          = "primary"
        subnet_id                     = azurerm_subnet.web.id
        private_ip_address_allocation = "Dynamic"
        public_ip_address_id          = azurerm_public_ip.web.id
      }
    }
    
  7. 7The VM

    Password login is disabled; your public key is the only way in. custom_data carries a cloud-init file that installs nginx on first boot, and the system-assigned identity lets the VM reach other Azure services without stored secrets.

    compute.tf
    resource "azurerm_linux_virtual_machine" "web" {
      name                  = "${local.prefix}-web"
      resource_group_name   = azurerm_resource_group.main.name
      location              = azurerm_resource_group.main.location
      size                  = var.vm_size
      admin_username        = "azureuser"
      network_interface_ids = [azurerm_network_interface.web.id]
      tags                  = local.tags
    
      disable_password_authentication = true
    
      admin_ssh_key {
        username   = "azureuser"
        public_key = file(pathexpand(var.ssh_public_key_path))
      }
    
      os_disk {
        caching              = "ReadWrite"
        storage_account_type = "Standard_LRS"
      }
    
      source_image_reference {
        publisher = "Canonical"
        offer     = "ubuntu-24_04-lts"
        sku       = "server"
        version   = "latest"
      }
    
      custom_data = base64encode(<<-EOT
        #cloud-config
        packages:
          - nginx
        runcmd:
          - echo "<h1>${var.name} ${var.environment}</h1><p>Served by $(hostname)</p>" > /var/www/html/index.html
      EOT
      )
    
      identity {
        type = "SystemAssigned" # an identity for the VM, for Key Vault or storage access without secrets
      }
    }
    
  8. 8Outputs

    outputs.tf
    output "url" {
      description = "Open this in a browser (allow a couple of minutes for cloud-init)"
      value       = "http://${azurerm_public_ip.web.ip_address}"
    }
    
  9. 9Initialise with the backend settings

    Run
    terraform init -backend-config=backend.hcl
    
    Check:

    Terraform installs hashicorp/azurerm v5.x and reports that the azurerm backend was configured.

  10. 10Validate

    Run
    terraform fmt -check
    terraform validate
    

    Expected output

    Success! The configuration is valid.
  11. 11Plan

    Run
    terraform plan -out=tfplan
    
    Check:

    Plan: 8 to add, 0 to change, 0 to destroy. — the resource group first, the VM last.

  12. 12Apply and open the page

    Run
    terraform apply tfplan
    curl $(terraform output -raw url)
    
    Check:

    Apply complete! Resources: 8 added. Within two or three minutes curl returns <h1>shop dev</h1>.

  13. 13Check the state is remote

    Run
    az storage blob list --account-name acmetfstate12345 -c tfstate --auth-mode login --query "[].name" -o tsv
    
    Check:

    The list contains shop/dev/azure-web.tfstate.

Clean up

terraform destroy
az group delete -n tfstate-rg --yes

Check for Destroy complete! Resources: 8 destroyed., then delete the state resource group last. In the portal, the shop-dev-rg resource group should no longer exist.

In production

What changes

In this lab In production
One subscription Subscriptions per environment under management groups (an Azure landing zone), with Azure Policy guardrails
VM with a public IP VM Scale Sets or App Service/Container Apps behind Application Gateway or Front Door with TLS; VMs without public IPs
Access by SSH key Azure Bastion or Entra ID login for VMs, with just-in-time access
az login as you CI signs in with workload identity federation (OIDC) to a service principal or managed identity — no client secrets
NSG on the subnet only NSGs plus application security groups, central firewall or NAT gateway for outbound traffic

Identity instead of keys

This lab already avoids every shared secret: no VM password, no storage account key for state (use_azuread_auth), and a managed identity for the VM. Keep it that way in production.

Production checklist

  • Resources grouped by lifecycle: one resource group per application and environment
  • No public IPs on VMs; access through Bastion or private connectivity
  • Password authentication disabled; Entra ID or SSH keys only
  • Managed identities instead of secrets for VM and app access to Azure services
  • State in a storage account with shared-key access disabled and blob versioning on
  • Tags on every resource; budgets and Azure Policy enforce required tags

Last reviewed · By the ByteCamel team · How we write content

Was this page helpful?

Report a mistake