Bird
Raised Fist0
Terraformcloud~10 mins

Drift detection in CI/CD in Terraform - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Process Flow - Drift detection in CI/CD
Start CI/CD Pipeline
Run terraform plan
Compare current infra vs code
Is there drift?
NoContinue deployment
Yes
Alert or fail pipeline
Fix drift manually or update code
Re-run pipeline
The pipeline runs terraform plan to compare real infrastructure with code. If differences (drift) exist, it alerts or stops deployment until fixed.
Execution Sample
Terraform
terraform init
terraform plan -detailed-exitcode
if [ $? -eq 2 ]; then
  echo "Drift detected!"
  exit 1
fi
This script initializes terraform, runs plan with detailed exit codes, and exits with error if drift is detected.
Process Table
StepCommandExit CodeDrift Detected?Action TakenOutput
1terraform init0NoInitialize terraformTerraform has been successfully initialized!
2terraform plan -detailed-exitcode2YesFail pipelinePlan: 1 to add, 0 to change, 0 to destroy.
3Check exit code2YesPrint alert and exitDrift detected!
4Pipeline stops---Pipeline failed due to drift.
💡 Exit code 2 from terraform plan means drift detected, so pipeline stops to prevent unintended changes.
Status Tracker
VariableStartAfter terraform initAfter terraform planFinal
exit_codeN/A022
drift_detectedfalsefalsetruetrue
pipeline_statusrunningrunningfailedfailed
Key Moments - 2 Insights
Why does terraform plan return exit code 2 when drift is detected?
Terraform plan with -detailed-exitcode returns 2 specifically to indicate that the real infrastructure differs from the code, signaling drift. See execution_table row 2.
What happens if drift is not fixed before continuing the pipeline?
The pipeline fails and stops deployment to avoid applying unexpected changes. This is shown in execution_table rows 3 and 4.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the exit code after running terraform plan?
A0
B2
C1
D3
💡 Hint
Check the 'Exit Code' column in row 2 of the execution_table.
At which step does the pipeline detect drift and decide to fail?
AStep 3
BStep 2
CStep 1
DStep 4
💡 Hint
Look at the 'Action Taken' column where the alert is printed and pipeline exits.
If terraform plan returned exit code 0 instead of 2, what would happen?
APipeline would alert but continue
BPipeline would fail due to drift
CPipeline would continue deployment
DPipeline would restart terraform init
💡 Hint
Refer to the 'Drift Detected?' column and 'Action Taken' for exit code 0 in execution_table.
Concept Snapshot
Drift detection in CI/CD with Terraform:
- Run 'terraform plan -detailed-exitcode' to detect drift
- Exit code 0: no drift, continue
- Exit code 2: drift detected, fail pipeline
- Fix drift manually or update code before redeploy
- Prevents unintended infrastructure changes
Full Transcript
In a CI/CD pipeline using Terraform, drift detection means checking if the real infrastructure matches the code. The pipeline runs 'terraform plan' with the '-detailed-exitcode' flag. If the exit code is 2, it means drift exists. The pipeline then alerts and stops deployment to avoid unexpected changes. If the exit code is 0, no drift is found and deployment continues. This process helps keep infrastructure consistent and safe.

Practice

(1/5)
1. What is the main purpose of drift detection in a Terraform CI/CD pipeline?
easy
A. To find differences between the Terraform code and the actual infrastructure
B. To speed up the deployment process by skipping validation
C. To automatically delete unused resources without approval
D. To generate documentation for the infrastructure

Solution

  1. Step 1: Understand drift detection concept

    Drift detection compares the current real infrastructure state with the Terraform code to find differences.
  2. Step 2: Identify the purpose in CI/CD

    In CI/CD, drift detection helps catch unexpected changes before applying new updates.
  3. Final Answer:

    To find differences between the Terraform code and the actual infrastructure -> Option A
  4. Quick Check:

    Drift detection = find differences [OK]
Hint: Drift detection = spot differences before apply [OK]
Common Mistakes:
  • Thinking drift detection speeds deployment
  • Assuming it deletes resources automatically
  • Confusing it with documentation generation
2. Which Terraform command is commonly used in CI/CD pipelines to detect drift before applying changes?
easy
A. terraform plan
B. terraform apply
C. terraform init
D. terraform destroy

Solution

  1. Step 1: Recall Terraform commands

    terraform plan shows the changes Terraform will make without applying them.
  2. Step 2: Identify drift detection command

    terraform plan detects differences (drift) between code and real infrastructure before apply.
  3. Final Answer:

    terraform plan -> Option A
  4. Quick Check:

    Detect drift = terraform plan [OK]
Hint: Use terraform plan to preview changes [OK]
Common Mistakes:
  • Using terraform apply which changes infrastructure
  • Confusing terraform init with drift detection
  • Using terraform destroy which deletes resources
3. Given the following Terraform plan output snippet in a CI/CD pipeline:
  # aws_instance.example will be updated in-place
  ~ tags = {
      - "Environment" = "dev"
      + "Environment" = "prod"
    }

What does this output indicate about drift?
medium
A. Terraform will ignore the tag change
B. The instance will be destroyed and recreated
C. No drift is detected; tags remain unchanged
D. The tag "Environment" has drifted from "dev" to "prod" and will be updated

Solution

  1. Step 1: Analyze the plan output

    The '~' symbol means in-place update. The tag "Environment" changes from "dev" to "prod".
  2. Step 2: Understand drift implication

    This shows drift: the real infrastructure tag differs from code and will be updated.
  3. Final Answer:

    The tag "Environment" has drifted from "dev" to "prod" and will be updated -> Option D
  4. Quick Check:

    ~ means update tag from dev to prod [OK]
Hint: Look for ~ symbol to spot in-place updates [OK]
Common Mistakes:
  • Thinking resource will be destroyed instead of updated
  • Ignoring tag changes as no drift
  • Assuming Terraform ignores tag differences
4. You run terraform plan in your CI/CD pipeline but it does not detect drift even though manual changes were made outside Terraform. What is the most likely cause?
medium
A. Terraform automatically ignores manual changes
B. You forgot to run terraform apply first
C. Terraform state file is outdated or corrupted
D. The provider plugin is missing

Solution

  1. Step 1: Understand drift detection dependency

    Terraform relies on the state file to compare real infrastructure with code.
  2. Step 2: Identify cause of missed drift

    If the state file is outdated or corrupted, Terraform cannot detect manual changes (drift).
  3. Final Answer:

    Terraform state file is outdated or corrupted -> Option C
  4. Quick Check:

    State file outdated = missed drift detection [OK]
Hint: Check state file freshness if drift not detected [OK]
Common Mistakes:
  • Assuming terraform apply affects drift detection
  • Believing Terraform ignores manual changes by design
  • Thinking missing provider causes drift detection failure
5. In a CI/CD pipeline, you want to automatically detect drift and fail the pipeline if any drift is found before applying changes. Which approach best achieves this?
hard
A. Run terraform apply directly and rely on errors to detect drift
B. Run terraform plan and parse its output to detect changes, then fail if changes exist
C. Skip drift detection and always apply changes
D. Manually check infrastructure outside the pipeline

Solution

  1. Step 1: Understand CI/CD drift detection goal

    The goal is to detect drift and fail early before applying changes.
  2. Step 2: Choose correct command and method

    terraform plan shows drift without applying; parsing its output allows pipeline to fail if drift exists.
  3. Step 3: Evaluate other options

    Applying directly risks unwanted changes; manual checks are slow; skipping detection is unsafe.
  4. Final Answer:

    Run terraform plan and parse its output to detect changes, then fail if changes exist -> Option B
  5. Quick Check:

    Plan + parse output = fail on drift [OK]
Hint: Use terraform plan output to gate pipeline success [OK]
Common Mistakes:
  • Applying without checking drift first
  • Relying on manual checks in automated pipelines
  • Ignoring drift detection to speed up deploys