Find and fix drift
In this task you'll find what changed outside Terraform and put it right.
Drift is when Azure no longer matches the code, usually after a change in the portal. terraform plan shows it: lines with ~ (change) or - (remove) on things you didn't touch in code.
Decide which is right. If the hand change was wrong, apply. If it was right, change the code to match first.
Example. During an outage someone opened RDP on a production NSG. The nightly drift check (terraform plan -detailed-exitcode) flagged it the next morning and apply removed it.
Before you start
You need: A Terraform stack. Time: 15 minutes.
Where to look
- terraform plan
- terraform apply
Steps
- Run
terraform planand read every change you didn't expect. - Decide: revert (apply) or adopt (edit the code).
- Apply, then plan again: it should say No changes.
- Schedule
terraform plan -detailed-exitcodein a pipeline to catch drift early.
Commands
export ARM_SUBSCRIPTION_ID=$(az account show --query id -o tsv)
terraform plan -detailed-exitcode; echo "exit code $?"
terraform apply
Watch out for
- Cost
- Free.
- Security
- Drift on security rules (NSGs, firewalls, roles) is an incident, not housekeeping.
- Common mistakes
- Fixing drift by hand again, so the state still doesn't match.
Clean up
Nothing to clean up.
Words to know
- Drift
- Differences between code, state and reality.
- -detailed-exitcode
- Makes plan exit with 2 when there are changes, handy in pipelines.
Tick off each step and track your progress in the guide.
Open this task in DevOps, Hands On