- Initialize Terraform in a pipeline using a remote state backend.
- Run
terraform planinside CI to validate changes and produce an inspectable plan artifact. - Separate plan and apply stages to enforce controlled deployments.
- Configure approval gates and environment checks to protect sensitive environments.
- Design and understand an end-to-end Terraform CI/CD pipeline in Azure DevOps that fits organizational governance and security requirements.
Prerequisites: an Azure DevOps project, an Azure service connection (or equivalent cloud provider connection), and a remote state backend such as an Azure Storage account or Terraform Cloud. Ensure build agents have the Terraform CLI available or use pipeline tasks that install Terraform. Keep secrets and backend credentials in secure pipeline variables or variable groups.
High-level design
A production-ready pipeline separates validation from change. Typical stages are:Example Azure Pipelines YAML
Below is a concise example that demonstrates the recommended flow: init, plan (produces an artifact), and apply (deployed to an environment so approvals can be attached). Adapt paths, service connections, and backend configuration to your repository.- Use secure pipeline variables or variable groups for sensitive values (storage account keys, backend secrets).
- The
environment: 'production'line enables the use of environment-level approvals and checks in Azure DevOps (configure them in the UI). - Publishing the plan artifact allows reviewers and auditors to inspect exactly what will change.
Never enable unattended
terraform apply against production without proper approvals and checks. Always produce an immutable plan artifact (terraform plan -out=...) in CI and require either manual approval or an automated policy that validates the plan before applying.Implementation tips and recommended practices
- Always use a remote backend for state locking (for example, Azure Storage with blob locking) to avoid concurrent writes.
- Keep state backend credentials and sensitive variables in secure pipeline variable groups or Azure Key Vault.
- Produce and store plan artifacts in CI so changes are reviewable and auditable. You can also convert plans to JSON with
terraform show -json tfplanfor automated validation tooling. - Prefer
deploymentjobs andenvironmenttargets in Azure DevOps for apply steps. This enables approvals, resource checks, and traceability. - Use Terraform workspaces or separate state keys/directories per environment (dev, staging, prod) to isolate state.
- Consider running
terraform fmt -checkandterraform validateon pull requests to catch issues early.
Links and references
- Terraform CLI commands: plan
- Azure Pipelines documentation
- Azure DevOps service connections
- Remote state with Azure Storage
- Terraform Cloud