Automating HashiCorp Terraform Plan and Apply in Azure DevOps
HashiCorp Terraform enables Azure teams to define networking, identity, compute, and security resources as code, while Azure DevOps provides version control, permissions, agents, artefact storage, and approval gates. Together, they turn infrastructure changes from undocumented console actions into reviewable and repeatable deployments.
Automation becomes dependable when operational boundaries are explicit. The pipeline must separate plan generation from apply, bind approval to a known configuration and plan, and preserve the state and version information required to reproduce exactly what reviewers saw.
| Execution pattern | Review boundary | Apply behaviour | Best suited to |
|---|---|---|---|
| Combined job | Limited independent review | Applies from the live workspace | Prototypes and sandboxes |
| Separate jobs with artefact | Approval follows plan publication | Applies an exact saved .tfplan |
Controlled production changes |
| Fresh plan before apply | Approval follows a new plan | Applies newly generated changes | Frequently updated services |
| Terraform Cloud remote runs | Remote policy and approvals | Executes through the remote platform | Centralised platform teams |
Establishing the execution boundary
Choose between a combined plan-and-apply job and separate stages according to the change risk. Production infrastructure normally benefits from a dedicated plan stage, an Azure DevOps environment approval, and a separate apply job. Disposable development environments can use a combined job when speed matters more than independent authorisation.
Runner placement affects latency, private connectivity, and data transfer. Australian workloads may use Azure Australia East in Sydney, Australia Southeast in Melbourne, or Australia Central in Brisbane. A self-hosted agent located near the state store can reduce transfer time and reach private endpoints, although the agent’s location does not determine where Terraform creates the declared resources.
Preparing the repository and state
Keep configuration, variable definitions, and provider requirements under version control. Commit the .terraform.lock.hcl file so every pipeline selects the same provider versions, while excluding .terraform, state files, and plan files from source control. Module paths and variable files must remain identical between the plan and apply stages because Terraform saved plans depend on their original working directory and configuration.
Use an encrypted remote azurerm backend with state locking rather than storing state locally. The backend should reside in an approved Australian region when data-residency requirements apply to the workloads. Terraform state can contain sensitive values even when they are marked sensitive, so restrict read access, enable appropriate encryption controls, and define retention rules for backups.
Configuring identity and permissions
Prefer workload identity federation for Azure authentication. An Azure Resource Manager service connection backed by workload identity federation lets an AzureCLI@2 task obtain a short-lived token without placing client secrets in pipeline variables. This reduces credential exposure and removes the operational burden of rotating long-lived service principal secrets.
Give the planning identity read access and the applying identity narrowly scoped create, update, and delete permissions. A custom role at the target resource-group level is often preferable to subscription-level Contributor access, while Owner should remain unused. Terraform records the identity and pipeline run in Azure activity logs, supporting change traceability for Australian organisations subject to the Privacy Act and internal audit requirements.
Building the plan stage
Install a pinned Terraform version, retrieve the repository, and run terraform init -input=false. Validate the configuration with terraform fmt -check -recursive and terraform validate before planning. These checks catch formatting drift, invalid references, and provider configuration errors without changing infrastructure.
Generate the plan with terraform plan -input=false -detailed-exitcode -out=tfplan. Exit code 2 indicates proposed changes, so the Azure DevOps task must treat that result differently from an execution error. Publish the binary plan as a pipeline artefact and produce a readable terraform show -no-color tfplan output for reviewers, naming both with the commit identifier.
Reviewing and approving changes
Use branch policies to require a successful plan before merge, then place the apply job in an Azure DevOps environment with approval checks and restricted access. Build the plan and apply stages within the same release pipeline when possible. If a plan generated during pull-request validation is reused later, verify that the approved artefact belongs to the exact commit being deployed.
Terraform plan files can contain sensitive values in clear text. Limit artefact access, avoid broad pipeline sharing, and use short retention periods. Australian teams should also account for AEST, AEDT, and Perth’s AWST when defining approval windows, particularly for changes requiring operations staff from different states to participate.
Executing the apply stage
The apply job downloads the approved artefact, verifies its checksum, checks out the same commit, and installs the identical Terraform version. Re-run terraform init -input=false with the same backend configuration, retain the committed provider lock file, and execute terraform apply -input=false tfplan. Using the saved plan ensures that apply performs the reviewed actions instead of discovering a different set of changes.
Backend locking protects against concurrent state updates, but operational checks still matter. A failed apply can leave state partially updated, requiring inspection before another attempt. When the repository changes frequently, generate a fresh plan after approval and revalidate its digest rather than applying a stale artefact.
Operating the pipeline reliably
Publish sanitised logs, apply results, and state references into an operational dashboard. Scheduled plans can detect configuration drift, while alerts should identify failed approvals, expired credentials, unexpected apply activity, and policy violations. For Australian budgeting, report expected resource consumption in AUD and account for GST shown on taxable business invoices. Terraform also supports evidence collection aligned with ACSC Essential Eight controls, although generated evidence does not by itself establish compliance.
The same operational discipline applies outside core infrastructure. IT Diversified’s poker tournament late registration guide illustrates another workflow where registration deadlines, controlled updates, and dependable execution determine the user experience. For Australian freight operators and customs brokers, reliable automation and auditable change histories provide a practical foundation for consistent infrastructure operations.