Labs · DevOps
Lab: Build a Jenkins Pipeline That Scans Terraform, Saves a Plan, Waits for Human Approval and Applies Exactly That Plan
Course: DevOps · Chapter 41: Terraform Environments and Jenkins Plan Approval Apply Pipeline · Lesson: 41.2 Jenkins pipeline: scan, plan, approval, apply
Chapter 41 explains environments and every line of this pipeline; this lab runs it for dev and stage.
Chala mitrano! Prod la koNi pan laptop varun terraform apply karu naye. Aaj pipeline, scan ani approval ne apply karuya.
Suppose we are…
Suppose we are on an Infosys cloud team managing dev, stage and prod for a client. Today engineers run terraform apply from their laptops with their own keys, and nobody can say who changed prod last Friday. The fix is one pipeline: scan the code, save the plan, let an approver read it, and apply exactly what was approved.
In this lab we run that pipeline for dev (no approval) and stage (approval required), using the repository layout from Chapter 41.
Goal of this lab
By the end you will have:
- A Pipeline job from SCM with the
ENVchoice parameter. - A dev run that applies without approval, and a stage run that pauses at Approval.
plan.txtarchived on every build, and everything destroyed at the end.
What you need
- A Jenkins agent with label
terraformthat has Terraform, Checkov and tfsec, and an IAM instance role (no access keys in Jenkins). - A Git repository with
envs/dev,envs/stage(each withbackend.tf,main.tfand<env>.tfvars) and a shared module, as in lesson 41.1. A small private S3 bucket per environment is enough. - A Jenkins group or role named
release-approverswith your user in it. - 75 minutes.
Cost
Everything this pipeline creates is billed to your AWS account. Keep the environments tiny (one private bucket each) and destroy them at the end of the lab.
Part 1: The Jenkinsfile
Add this
Jenkinsfileto the root of the Terraform repository:Jenkinsfile
pipeline { agent { label 'terraform' } parameters { choice(name: 'ENV', choices: ['dev', 'stage', 'prod'], description: 'Target environment') } options { timeout(time: 60, unit: 'MINUTES'); disableConcurrentBuilds() } environment { TF_IN_AUTOMATION = 'true' TF_INPUT = '0' } stages { stage('Init and Validate') { steps { dir("envs/${params.ENV}") { sh 'terraform init -no-color' sh 'terraform fmt -check -recursive' sh 'terraform validate -no-color' } } } stage('Scan code') { steps { sh 'checkov -d . --framework terraform --quiet' sh 'tfsec .' } } stage('Plan') { steps { dir("envs/${params.ENV}") { sh "terraform plan -no-color -var-file=${params.ENV}.tfvars -out=tfplan" sh 'terraform show -no-color tfplan > plan.txt' sh 'terraform show -json tfplan > tfplan.json' sh 'checkov -f tfplan.json --framework terraform_plan --quiet' archiveArtifacts artifacts: 'plan.txt' } } } stage('Approval') { when { expression { params.ENV != 'dev' } } steps { input message: "Apply plan.txt to ${params.ENV}?", submitter: 'release-approvers' } } stage('Apply') { steps { dir("envs/${params.ENV}") { sh 'terraform apply -no-color tfplan' } } } } post { always { cleanWs() } } }Commit and push it, then create a Pipeline job named
infrawith Pipeline script from SCM pointing at this repo.Run Build Now once so Jenkins reads the parameters, then use Build with Parameters from now on.
What you should see: a drop-down
ENVwith dev, stage and prod.
Part 2: dev, no approval
Build with
ENV = dev.What you should see: stages Init and Validate, Scan code, Plan and Apply run in order; Approval is skipped because of the
whencondition. The console ends withApply complete!andFinished: SUCCESS.Open the build page and click
plan.txtunder Build Artifacts.What you should see: the plan in plain text, exactly what was applied.
Part 3: stage, with approval
Build with
ENV = stage.What you should see: the build pauses with
Apply plan.txt to stage? Proceed or Abort.Open
plan.txtfirst and read the add, change and destroy counts. Only then click Proceed.What you should see:
Approved by <your user>andApply complete!Prove the scan is a gate: remove the public access block from the stage bucket in a branch, push and build.
What you should see: Checkov fails with
CKV2_AWS_6, the build stops before Plan, and nobody is asked to approve it.Check: CKV2_AWS_6: "Ensure that S3 bucket has a Public Access block" FAILED for resource: aws_s3_bucket.assets File: /envs/prod/s3.tf:1-4 Passed checks: 41, Failed checks: 1, Skipped checks: 0 script returned exit code 1 Finished: FAILURE
Clean up: destroy every environment
From the agent (or a destroy job with the same approval), destroy each environment you applied:
cd envs/dev && terraform init && terraform destroy -var-file=dev.tfvars cd ../stage && terraform init && terraform destroy -var-file=stage.tfvarsWhat you should see:
Destroy complete!for each environment.
Ravindra Bagale's Tip
Approvers should read plan.txt, not the Jenkinsfile. If the plan says "destroy" anywhere you did not expect, click Abort and ask.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
Running terraform apply without the saved plan | Apply may differ from what was approved | Always apply tfplan |
| AWS access keys stored in Jenkins credentials for this | Long-lived keys can leak | Use an IAM role on the agent |
| Two builds at once on one environment | State lock errors or races | Keep disableConcurrentBuilds() and S3 locking |
| Approver group missing | Anyone can click Proceed | Set submitter: 'release-approvers' |
Self-check checklist
0 of 4 done
Try-at-home challenge
Add a Destroy boolean parameter that runs terraform plan -destroy -out=tfplan and still goes through the same Approval stage. Explain why destroys need approval as much as applies.
Samajla ka? Scan, plan, approve, apply: nobody types apply on prod from a laptop. Aata pudhe jaauya drift kade.