Infrastructure as Code in a Pipeline
Running terraform plan on every pull request, and catching drift before it catches you.
On this page4 sections
This lesson is the capstone that ties the whole curriculum together: infrastructure changes reviewed and shipped exactly the way application code is, using the CI/CD machinery from earlier in this track.
Plan on every pull request
A common, high-value pattern: every pull request that touches Terraform files automatically triggers a pipeline stage that runs terraform plan and posts the output as a comment on the PR itself. Reviewers see exactly what infrastructure will change - not just the HCL diff, but its real, computed effect - before approving anything.
stage('Terraform Plan') {
steps {
sh 'terraform plan -out=tfplan'
}
}
Apply only after merge
terraform apply runs separately, triggered only once that reviewed, approved plan merges to the main branch - the exact same "build once, promote everywhere" discipline from the Jenkins deploy lesson, just applied to infrastructure instead of application artifacts. Nobody applies a plan that wasn't the one actually reviewed.
Catching drift on a schedule
Code review catches changes made through the pipeline. It can't catch someone changing something by hand in the cloud console at 2 AM. A separate, scheduled job - a nightly terraform plan with no corresponding apply - catches that: any unexpected diff in its output means something drifted outside the pipeline's view, and it's worth paging someone to go find out why.
Try it
Real cron handles the "nightly" part, the same way it did for the scheduled Jenkins builds earlier in this curriculum:
echo '0 3 * * * /usr/local/bin/terraform-plan-check.sh' > drift-check
When you're ready, hit Mark complete. You've completed the Infrastructure as Code track!
Challenge
Write a crontab line into a file called drift-check that runs /usr/local/bin/terraform-plan-check.sh every night at 3:00 AM, using a single redirected echo.
Want to experiment first? Try things in the practice terminal (opens in a new tab), then enter the command that solves the task here.
Quiz
Lock in the concepts. Score at least 80% to mark the lesson complete.
Done with this one?
Skipped the challenge? You can mark the lesson complete by hand.