Skip to main content
Jenkins Pipeline
CHAPTER 17

Infrastructure as Code and Jenkins

Updated: May 15, 2026
25 min read

# CHAPTER 17

Infrastructure as Code and Jenkins

1. Introduction

In traditional IT, when a team needed a new server, they submitted a ticket. An administrator would log into the AWS console, click 20 different buttons to create a server, manually install software, and hand it over a week later. This manual process is slow, prone to human error, and impossible to replicate perfectly. The DevOps solution is Infrastructure as Code (IaC). We write scripts that define our hardware, and we use Jenkins to execute those scripts, spinning up entire data centers in minutes. In this chapter, we will integrate Jenkins with the two industry titans of IaC: Terraform and Ansible.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Define Infrastructure as Code (IaC) and its operational benefits.
  • Differentiate between Provisioning (Terraform) and Configuration Management (Ansible).
  • Understand how Jenkins orchestrates the execution of IaC tools.
  • Configure a declarative pipeline to deploy AWS infrastructure automatically.
  • Understand the concept of "Immutable Infrastructure."

3. Beginner-Friendly Explanation

Imagine building a hotel.
  • Terraform (The Architect & Construction Crew): Terraform looks at a blueprint (Code) and builds the physical structure. It pours the concrete, builds the walls, and installs the plumbing. (In the cloud, it creates the raw Linux server, the database, and the firewall).
  • Ansible (The Interior Designer): Ansible walks into the empty rooms built by Terraform. It paints the walls, arranges the furniture, and stocks the mini-fridge. (In the cloud, it logs into the empty Linux server, installs Apache, configures PHP, and starts the web service).
  • Jenkins (The General Contractor): Jenkins is the boss. Jenkins reads the master plan and tells Terraform to build the building, and the moment it is finished, tells Ansible to furnish it.

4. Terraform Basics (Provisioning)

Terraform is a declarative language. You write .tf files describing the *desired state* of your cloud environment.
hcl
12345678
# Example main.tf
resource "aws_instance" "web" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
  tags = {
    Name = "HelloWorld"
  }
}

If you run terraform apply, Terraform talks to the AWS API and creates this exact server.

5. Ansible Basics (Configuration)

Ansible is procedural. It reads a YAML "Playbook" and uses SSH to log into servers and run configuration commands.
yaml
1234567
# Example playbook.yml
- hosts: webservers
  tasks:
    - name: Ensure Apache is installed
      apt:
        name: apache2
        state: present

6. Mini Project: Deploy Infrastructure Automatically

Let's write a Jenkins pipeline that acts as the General Contractor, using Terraform to build a server.

Step-by-Step Pipeline Concept:

groovy
1234567891011121314151617181920212223242526272829303132
pipeline {
    agent any
    stages {
        stage('Initialize Terraform') {
            steps {
                // Downloads necessary cloud provider plugins
                sh 'terraform init'
            }
        }
        stage('Terraform Plan') {
            steps {
                // Calculates what will change (e.g., "I will create 1 server")
                sh 'terraform plan -out=tfplan'
            }
        }
        stage('Approval') {
            steps {
                // Pauses the pipeline. A human must review the plan and click "Approve"
                input message: 'Review the plan. Approve deployment to AWS?'
            }
        }
        stage('Terraform Apply') {
            steps {
                // Executes the plan and actually builds the server
                // We use withCredentials (Chapter 14) to inject the AWS API keys!
                withCredentials([aws(credentialsId: 'my-aws-keys', accessKeyVariable: 'AWS_ACCESS_KEY_ID', secretKeyVariable: 'AWS_SECRET_ACCESS_KEY')]) {
                    sh 'terraform apply -auto-approve tfplan'
                }
            }
        }
    }
}

7. Real-World Scenarios

A company experienced a catastrophic database failure, and their entire primary AWS region (us-east-1) went offline. Because their infrastructure was built manually over five years via clicking buttons in the AWS console, they had no idea how to rebuild it in a new region. It took them a week to manually piece the architecture back together. Following the disaster, they adopted IaC. They defined their entire network in Terraform and managed the deployments through Jenkins. A year later, during a similar outage, they simply changed one variable in their Jenkins pipeline from us-east-1 to us-west-2, clicked "Build," and Jenkins rebuilt their entire multi-tier architecture from scratch in 12 minutes.

8. Best Practices

  • Immutable Infrastructure: When a server needs a software update, do not use SSH to log in and update it. Instead, use Jenkins and Terraform to destroy the old server entirely and instantly replace it with a brand-new server containing the updated software. This prevents "Configuration Drift," where servers slowly degrade over time due to manual tweaks.

9. Security Recommendations

  • State File Security: Terraform relies on a "State File" (terraform.tfstate) to remember what it built. This file often contains highly sensitive data, including plaintext database passwords generated during infrastructure creation. Never commit the state file to Git. Jenkins must configure Terraform to store this file in a secure, encrypted remote backend (like an AWS S3 bucket with strict IAM access).

10. Troubleshooting Tips

  • Jenkins Plugins: To make managing AWS credentials easier, install the "CloudBees AWS Credentials" plugin in Jenkins. It provides the withCredentials([aws(...)]) syntax used in the mini-project, automatically handling the secure injection of the environment variables Terraform requires.

11. Exercises

  1. 1. Contrast the operational purposes of Terraform (Provisioning) and Ansible (Configuration Management).
  1. 2. Explain the concept of "Configuration Drift" and how Infrastructure as Code (IaC) prevents it.

12. FAQs

Q: Can Jenkins replace Terraform or Ansible? A: No. Jenkins is an orchestrator; it executes scripts. It is terrible at managing cloud state. You should use Jenkins to *trigger* Terraform, letting Terraform do what it does best (managing cloud infrastructure APIs).

13. Interview Questions

  • Q: Describe a comprehensive CI/CD pipeline architecture that integrates Terraform and Ansible. How do you handle the handoff of dynamically generated infrastructure IPs from Terraform to the Ansible inventory file within the Jenkins workspace?
  • Q: Why is the manual input approval stage critical between a terraform plan and terraform apply step within a Jenkins pipeline? What risk does it mitigate?

14. Summary

In Chapter 17, we elevated Jenkins from an application deployer to a true infrastructure orchestrator. We defined Infrastructure as Code (IaC), eliminating the fragile, undocumented manual processes of the past. We integrated Jenkins with Terraform to mathematically define and provision cloud resources, and introduced Ansible for automated configuration. By utilizing Jenkins to execute these tools sequentially, we gained the power to conjure, modify, and destroy entire data centers through automated, version-controlled pipelines.

15. Next Chapter Recommendation

Our infrastructure is in the cloud. But what about Jenkins itself? Should Jenkins run on a laptop, or should it live in the cloud too? Proceed to Chapter 18: Cloud CI/CD Pipelines.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·