Skip to content

Infrastructure as Code with Terraform & Jenkins ๐ŸŒ

This tutorial walks through a declarative Jenkins pipeline (45-Jenkinsfile-terraform) that orchestrates the provisioning of infrastructure using Terraform across different environments (dev, qa, prod).

๐Ÿ“Š Pipeline Overview

Here is the high-level flow of our Terraform automation pipeline:

flowchart LR
    Jenkins([๐Ÿค– Jenkins]) --> P[Pipeline]
    P --> Init([Terraform Init])
    Init -->|plan| Plan([Terraform Plan])
    Plan --> Approval{Manual Approval}
    Approval -->|Approved| Apply([Terraform Apply])

Why Manual Approval?

Manual approval before terraform apply ensures that infrastructure changes are always reviewed and intentional, reducing the risk of accidental modifications in production.


๐Ÿ› ๏ธ Step-by-Step Breakdown

1. Configuration & Parameters

The pipeline begins by defining global options and the parameters required to trigger the build.

pipeline {
  agent any
  options {
    disableConcurrentBuilds()
    disableResume()
    buildDiscarder(logRotator(numToKeepStr: '10'))
    timeout(time: 1, unit: 'HOURS')
  }
  parameters {
    choice(name: 'ENVIRONMENT', choices: ['dev', 'qa', 'prod'], description: 'Choose Environment to deploy')
  }
  environment {
    TF_DIR = "deployment/terraform"
  }
  stages {
    stage('Deploy to Dev') {
      when {
        environment name: 'ENVIRONMENT', value: 'dev'
      }
      steps {
        terraformPipeline('dev')
      }
    }
    stage('Deploy to QA') {
      when {
        environment name: 'ENVIRONMENT', value: 'qa'
      }
      steps {
        terraformPipeline('qa')
      }
    }
    stage('Deploy to Prod') {
      when {
        environment name: 'ENVIRONMENT', value: 'prod'
      }
      steps {
        terraformPipeline('prod')
      }
    }
  }
  post {
    always {
      deleteDir()
    }
  }
}

def terraformPipeline(envName) {
  def tfvars = "${envName}.tfvars"
  dir(env.TF_DIR) {
    sh 'terraform init -reconfigure'
    sh "terraform plan -var-file=${tfvars} -out=tfplan"
    input message: "Approve Terraform apply for ${envName}?", ok: 'Proceed'
    sh 'terraform apply tfplan'
  }
}
  • Parameterization: Choose the environment at build time.
  • Centralized Logic: The terraformPipeline method handles all Terraform steps for each environment.
  • Approval: Manual approval is required before applying changes.
  • No Destroy Option: The pipeline only supports plan and apply for safety.

Why -reconfigure?

The -reconfigure flag in terraform init ensures the backend is always freshly initialized, which is important for CI/CD pipelines to avoid state or configuration drift.


How it Works

  1. Select Environment: User chooses dev, qa, or prod when triggering the pipeline.
  2. Terraform Flow:

  3. terraform init -reconfigure ensures backend is always fresh.

  4. terraform plan creates a plan file for the selected environment.
  5. Manual approval is required before applying.
  6. terraform apply tfplan applies the exact plan.
  7. Workspace Cleanup: Jenkins workspace is cleaned after every run.

Reference


๐Ÿง  Knowledge Check

#

Why is manual approval included before terraform apply in this pipeline?

#

What does the terraformPipeline method do in this Jenkinsfile?

#

What is the purpose of the -reconfigure flag in terraform init?

๐Ÿ“ฌ DevopsPilot Weekly โ€” Learn DevOps, Cloud & Gen AI the simple way.
๐Ÿ‘‰ Subscribe here