Ravindra BagaleCourses & study guides Track your progress

Labs · DevOps

Lab: Build a Jenkins Pipeline That Scans Terraform, Saves a Plan, Waits for Human Approval and Applies Exactly That Plan

Advanced75 minJenkins agent labelled terraform · Terraform 1.6+ · Checkov and tfsec · An AWS account (IAM role on the agent)

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 ENV choice parameter.
  • A dev run that applies without approval, and a stage run that pauses at Approval.
  • plan.txt archived on every build, and everything destroyed at the end.

What you need

  • A Jenkins agent with label terraform that has Terraform, Checkov and tfsec, and an IAM instance role (no access keys in Jenkins).
  • A Git repository with envs/dev, envs/stage (each with backend.tf, main.tf and <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-approvers with 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

  1. Add this Jenkinsfile to 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() }
      }
    }
    
  2. Commit and push it, then create a Pipeline job named infra with Pipeline script from SCM pointing at this repo.

  3. Run Build Now once so Jenkins reads the parameters, then use Build with Parameters from now on.

    What you should see: a drop-down ENV with dev, stage and prod.

Part 2: dev, no approval

  1. 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 when condition. The console ends with Apply complete! and Finished: SUCCESS.

  2. Open the build page and click plan.txt under Build Artifacts.

    What you should see: the plan in plain text, exactly what was applied.

Part 3: stage, with approval

  1. Build with ENV = stage.

    What you should see: the build pauses with Apply plan.txt to stage? Proceed or Abort.

  2. Open plan.txt first and read the add, change and destroy counts. Only then click Proceed.

    What you should see: Approved by <your user> and Apply complete!

  3. 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

  1. 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.tfvars
    

    What 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

MistakeWhat happensFix
Running terraform apply without the saved planApply may differ from what was approvedAlways apply tfplan
AWS access keys stored in Jenkins credentials for thisLong-lived keys can leakUse an IAM role on the agent
Two builds at once on one environmentState lock errors or racesKeep disableConcurrentBuilds() and S3 locking
Approver group missingAnyone can click ProceedSet 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.