Skip to main content

Terraform Modules

Reference Azure

DOCUMENT CATEGORY: Reference SCOPE: Terraform infrastructure-as-code modules PURPOSE: Document reusable Terraform modules for Azure Local MASTER REFERENCE: Terraform Azure Provider

Status: Active


Overview​

Six Terraform modules provision the Azure foundation for Azure Local deployments. These modules handle management groups, networking, identity, monitoring, security, and management VMs. Guest OS and on-premises configuration is handled separately by PowerShell or Ansible.

Provider Requirements: azurerm ~> 4.0, azuread ~> 3.0, random ~> 3.0

Module Architecture​

environments/azure-local/main.tf
│
├── modules/landing-zone (Management Groups, Resource Groups)
│ ↓
├── modules/networking (VNet, Subnets, NSGs, VPN, Bastion)
│ ↓
├── modules/identity (Key Vault, RBAC, Managed Identities)
│ ↓
├── modules/monitoring (Log Analytics, Alerts, Action Groups)
│ ↓
├── modules/security (Defender, Azure Policy)
│ ↓
└── modules/compute (Management VMs — DC, Jumpbox, WAC, Syslog)

Available Modules​

ModulePurposeKey Resources
landing-zoneManagement group hierarchy and resource groupsazurerm_management_group, azurerm_resource_group
networkingHub VNet with subnets, NSGs, optional VPN/Bastion/NATazurerm_virtual_network, azurerm_subnet, azurerm_network_security_group
identityPlatform Key Vault, SPN role assignments, managed identitiesazurerm_key_vault, azurerm_role_assignment, azurerm_user_assigned_identity
monitoringLog Analytics workspace, solutions, action groups, alertsazurerm_log_analytics_workspace, azurerm_monitor_action_group
securityAzure Policy assignments, Defender for Cloud security contactazurerm_subscription_policy_assignment, azurerm_security_center_contact
computeManagement VMs (domain controllers, jumpbox, WAC, syslog)azurerm_windows_virtual_machine, azurerm_network_interface

Backend Bootstrap​

A separate bootstrap module provisions the remote state storage. Its values come from devops.state through the generated variable file (step 1 below):

cd src/terraform/backend
terraform init
terraform apply -var-file=D:\work\iac\terraform\backend\terraform.tfvars.json

Creates: the resource group, the storage account and the blob container of devops.state (resource_group, storage_account, container), in devops.state.subscription_id (else azure.subscription_id). The account settings follow the devops.state keys added in registry 5.0.62:

KeyTerraform variableWhat it sets
devops.state.replication_typereplication_typeRedundancy: LRS, ZRS, GRS, RAGRS, GZRS or RAGZRS
devops.state.public_network_accesspublic_network_access_enabledFalse: private endpoints only, and allowed_ip_ranges must be empty
devops.state.allowed_ip_rangesallowed_ip_rangesPublic IP addresses or CIDR ranges allowed to reach the account
devops.state.versioningversioning_enabledBlob versioning
devops.state.blob_soft_delete_daysblob_soft_delete_retention_daysDays a deleted state blob stays recoverable, 1 to 365
devops.state.container_soft_delete_dayscontainer_soft_delete_retention_daysDays a deleted container stays recoverable, 1 to 365
devops.state.network_bypassnetwork_bypassAzureServices, Logging, Metrics or None
devops.state.azure_local_key(backend.hcl and TF_BACKEND_KEY)The state file of the azure-local environment

Usage​

1. Write the variable files from infrastructure.yml​

# Keep the output folder out of the repository.
./config/variables/scripts/New-IacVariableFiles.ps1 -InfrastructureFile ./infrastructure.yml -OutputDirectory D:\work\iac

This writes terraform.tfvars.json and backend.hcl for each environment. A secret is never written: the script writes not-written.txt next to the variable file and names the environment variable that Terraform reads at run time:

$env:TF_VAR_vm_admin_password = '<resolve landing_zone.virtual_machines[].admin_password>'
$env:TF_VAR_vpn_shared_key = '<resolve landing_zone.connectivity.vpn_gateway.site_to_site[0].shared_key>'

Every value comes from infrastructure.yml (a key the file leaves out gets its registry default); a variable with a default is a setting of the code (class c in the registry). Add no .tfvars file of your own: a later -var-file overrides the generated values. The terraform.tfvars.example files hold comments only, and the earlier extra.tfvars step is gone: the NSG rules, Key Vault IP ranges and policy assignments now have keys (landing_zone.network_security_groups[], key_vaults[].allowed_ip_ranges, landing_zone.policy.assignments[] and resource_group_assignments[]).

2. Initialize and Plan​

cd src/terraform/environments/azure-local
terraform init -backend-config=D:\work\iac\terraform\azure-local\backend.hcl
terraform plan -var-file=D:\work\iac\terraform\azure-local\terraform.tfvars.json -out=tfplan

3. Apply​

terraform apply tfplan

Module Details​

landing-zone​

Creates the management groups of landing_zone.management_groups[] in the tree their parent keys describe, puts each subscription of landing_zone.subscriptions[] under the management group its management_group key names, and creates the resource groups. An Azure Landing Zone tree, for example:

Root (IIC)
├── Platform
│ ├── Identity
│ ├── Connectivity
│ ├── Management
│ └── Security
└── Landing Zones

is five entries whose parent names the group above. A group whose parent is not in the list (or is not set) sits under that parent as it exists already (not set: the tenant root group). A tree has at most six levels below the tenant root, so the module creates the groups level by level (What are Azure management groups?).

Variables: management_groups (list of name, display name and parent), subscriptions (with the management group of each), resource_groups (with location and tags).

State move on an existing deployment

Before registry 5.0.62 the module built a fixed hierarchy. The management groups and the subscription placements now have new state addresses: azurerm_management_group.root, .platform, .identity, .connectivity, .management, .security and .landing_zones became azurerm_management_group.level0 to .level5 keyed by group name, and the five azurerm_management_group_subscription_association resources became .subscriptions. A state that an earlier version of the module created needs a state move (terraform state mv, or a moved block in your root module) before the next apply; otherwise the plan destroys and re-creates the groups. Read the plan before you apply it.

networking​

Provisions the hub virtual network with dynamic subnet and NSG creation:

  • NSG rules are flattened from nsgs[].rules[] and applied via for_each
  • VPN Gateway, NAT Gateway, and Bastion Host are all conditional (enable_* booleans)
  • Subnets are created via for_each from a map variable

identity​

Manages Key Vault with RBAC authorization and SPN role assignments:

  • Platform Key Vault for shared secrets
  • Optional Azure Local cluster Key Vault (conditional)
  • SPN roles at both subscription and resource group scope
  • Managed identities output for use by other modules

The Key Vault rules follow the registered keys (registry 5.0.60 and 5.0.61), the same rules as Deploy-KeyVaults.ps1 and the ARM deployment:

VaultPurge protectionSoft-delete retention
Platform Key VaultOn, except when scenario.environment_class is lab, test or dev, where a vault has to be removablekey_vaults[purpose=management].soft_delete_retention_days, 7 to 90 (default 90)
Cluster Key Vault (cluster.key_vault)Off, as Microsoft's deployment template creates itcluster.key_vault.soft_delete_retention_days, 7 to 90 (default 30)

Purge protection cannot be switched off once it is on. A cluster vault that an earlier version of the module created keeps its purge protection: the module ignores that attribute on an existing vault, so the plan does not try to change it.

monitoring​

Deploys Log Analytics and alerting infrastructure:

  • Log Analytics workspace with configurable retention
  • Solutions: Updates, SecurityCenterFree
  • Action group for critical alerts (email + webhook)
  • Optional cluster health metric alert

security​

Configures Azure Policy and the Defender for Cloud security contact. It sets no Defender pricing tier, so it turns on no paid plan:

  • Policy assignments at subscription and resource group level
  • Security contact email configuration

compute​

Provisions management VM shells (guest OS configuration handled by Ansible/PowerShell):

  • Filters VMs by deployment_target == "azure" from the variable map
  • Stores admin password as Key Vault secret
  • Outputs VM IDs, private IPs, and managed identity principal IDs

Variable Mapping​

Variables flow from infrastructure.yml to terraform.tfvars.json. The registry says, for every Terraform variable, which key it comes from (tools.terraform.variables):

infrastructure.yml keyTerraform VariableExample
landing_zone.management_groupsmanagement_groupsManagement group hierarchy
landing_zone.networks[]vnet_*, subnetsHub VNet configuration
key_vaults[]key_vault_*Key Vault settings
cluster.key_vault.soft_delete_retention_daysazl_key_vault_soft_delete_retention_daysRetention of the cluster Key Vault
scenario.environment_classenvironment_classPurge protection of the platform Key Vault
operations.monitoringlog_analytics_*Log Analytics config
landing_zone.policy.assignments[]policy_assignmentsAzure Policy at the scope of the Azure Local subscription: name, policy_definition_id, display_name, description, enforce (default true), non_compliance_message
landing_zone.policy.resource_group_assignments[]rg_policy_assignmentsThe same, at the scope of a resource group of landing_zone.resource_groups (resource_group)
landing_zone.virtual_machines[]management_vmsVM definitions, with os_disk_size_gb (default 128), os_disk_type (default Premium_LRS), os_disk_caching (default ReadWrite) and image_version (default latest)
landing_zone.network_security_groups[]nsgsNSGs and their rules
landing_zone.connectivity.nat_gateway.public_ip_name, .skuNAT gateway objectName of its public IP; SKU Standard (default) or StandardV2
landing_zone.connectivity.vpn_gateway.public_ip_name, .secondary_public_ip_name, .active_activeVPN gateway objectNames of the public IPs; active-active mode (default false; needs the second public IP)
landing_zone.connectivity.bastion.public_ip_nameBastion objectName of the public IP of the Bastion host
key_vaults[purpose=management].allowed_ip_ranges, .soft_delete_retention_dayskey_vault_allowed_ips, key_vault_soft_delete_retention_daysNetwork rules and retention of the platform Key Vault
azure.automation_identity.resource_group_roles[]spn_resource_group_rolesRoles of the deployment identity at resource group scope (resource_group, roles)
security.defender_for_cloud.alert_notifications, .alerts_to_adminsalert_notifications, alerts_to_adminsDefender for Cloud sends the security alerts to the security contact, and to the subscription owners (both default true)

The keys in the last rows were added in registry 5.0.62 (schema 5.6.28, all optional), so that no Terraform variable keeps a deployment value of its own.

Remote State​

State is stored in Azure Storage with blob lease locking:

backend "azurerm" {
resource_group_name = "rg-iic-terraform-01"
storage_account_name = "stiictfstatelab"
container_name = "tfstate"
key = "azure-local.tfstate"
}

New-IacVariableFiles.ps1 writes these values to backend.hcl. The container comes from devops.state.container; the state file of the azure-local environment is devops.state.azure_local_key (default azure-local.tfstate). The Azure DevOps, GitHub and GitLab pipelines pass the same values to terraform init as TF_BACKEND_RG, TF_BACKEND_SA, TF_BACKEND_CONTAINER and TF_BACKEND_KEY, which task 05 of the CI/CD setup sets.

Repository​

Source: azurelocal-toolkit/src/terraform/

src/terraform/
├── backend/ # State storage bootstrap (devops.state)
├── modules/
│ ├── landing-zone/ # Management groups, resource groups
│ ├── networking/ # VNet, subnets, NSGs, VPN gateway, Bastion, NAT gateway
│ ├── identity/ # Key Vaults, role assignments, managed identities
│ ├── monitoring/ # Log Analytics workspace and action group
│ ├── security/ # Defender for Cloud security contact, Azure Policy
│ ├── compute/ # Management VMs
│ └── cicd-runner/ # Self-hosted CI/CD runners (Linux, Windows, ZTP)
├── environments/
│ ├── azure-local/ # Root module that calls the modules above
│ └── cicd-infra/ # CI/CD runners (task 06 of the CI/CD setup)
└── README.md

PreviousUpNext
Part 3: Automation GuidesPart 3: Automation GuidesAnsible Playbooks