Skip to content

Intermediate · CI/CD pipelines · topic 27 of 53 · 30 min

Jenkins pipelines

Explanation

Jenkins is a free, self-hosted automation server that many companies, especially banks and large enterprises, still use for CI/CD. A controller schedules work and agents run the builds; a Jenkinsfile in the repository describes a declarative pipeline with stages, steps and post actions. Jenkins is very flexible thanks to its plugins, but you must run, update and secure it yourself.

What Jenkins is

Jenkins is an open-source automation server written in Java. It started in 2011 (as a fork of an older tool called Hudson) and is one of the oldest CI tools still in wide use. Unlike GitHub Actions, you host it yourself: on a VM, in a container, or on Kubernetes. That gives you full control, and full responsibility.

Controller and agents

The controller is the central Jenkins server. It stores job settings and build history, serves the web UI, and decides which build runs where. Agents (also called nodes) are the machines that actually run builds; each has a number of executors, which are slots for builds running at the same time. Agents can be permanent VMs, or created on demand as containers or Kubernetes pods.

Tip: Run builds on agents, not on the controller. A build runs whatever code is in the repository, and on the controller that code could read every stored credential.

Jobs: freestyle versus pipeline

A freestyle job is configured by clicking through forms in the web UI. It is quick to start but hard to review, copy or version. A Pipeline job is defined in code, in a file called Jenkinsfile, written in a Groovy-based language. There are two styles: declarative (a fixed, readable structure) and scripted (full Groovy code). Start with declarative.

output
pipeline {
    agent { label 'linux' }                      // run on an agent with this label

    environment {
        APP = 'shop-api'
        REGISTRY = credentials('registry-creds') // username and password from the Jenkins store
    }

    options {
        timeout(time: 30, unit: 'MINUTES')
    }

    stages {
        stage('Checkout') {
            steps { checkout scm }
        }
        stage('Install and test') {
            steps {
                sh 'npm ci'
                sh 'npm test'
            }
        }
        stage('Build image') {
            steps {
                sh "docker build -t registry.example.com/${APP}:${env.GIT_COMMIT} ."
            }
        }
        stage('Push image') {
            when { branch 'main' }
            steps {
                sh 'echo "$REGISTRY_PSW" | docker login registry.example.com -u "$REGISTRY_USR" --password-stdin'
                sh "docker push registry.example.com/${APP}:${env.GIT_COMMIT}"
            }
        }
        stage('Approve production') {
            when { branch 'main' }
            steps { input message: 'Deploy to production?' }
        }
    }

    post {
        always  { junit 'reports/**/*.xml' }     // publish test results every time
        success { echo 'Pipeline passed' }
        failure { echo 'Pipeline failed: tell the team' }
    }
}
Jenkinsfile (Groovy)

Reading it from top to bottom: pipeline wraps everything. agent says where to run. environment sets variables; credentials('registry-creds') reads a stored username and password and also creates REGISTRY_USR and REGISTRY_PSW. stages holds the stage blocks, each with steps such as sh (run a shell command). when runs a stage only in some cases. post runs after the stages: always, on success, or on failure.

Careful: Use single quotes for sh commands that contain secrets, as in the docker login line above. In double quotes, Groovy puts the secret into the command text itself, where it can leak into logs and process lists. With single quotes, the shell reads it from the environment instead.

Plugins, multibranch pipelines and webhooks

Most Jenkins features come from plugins: Git, Pipeline, Credentials, Kubernetes agents, JUnit reports and around two thousand more. A multibranch pipeline job scans a repository, finds every branch and pull request that has a Jenkinsfile, and creates a pipeline for each. A webhook is a message GitHub, GitLab or Bitbucket sends to Jenkins on every push, so builds start at once instead of Jenkins checking (polling) the repository every few minutes.

When teams choose Jenkins, and what it costs

  • Chosen for: running fully inside a company network (common in Indian banks and insurers with strict data rules), huge flexibility, many existing pipelines, and no per-minute fees.
  • Costs: someone must patch Jenkins and its plugins, back up its home folder, scale agents and handle plugin conflicts. Plugins are a common source of security advisories, so keep them few and up to date.
ToolPipeline fileHostingTypical users
JenkinsJenkinsfile (Groovy)Self-hostedEnterprises with on-premises systems
GitHub Actions.github/workflows/*.ymlGitHub-hosted or self-hosted runnersTeams whose code is on GitHub
GitLab CI/CD.gitlab-ci.ymlGitLab.com or self-managed GitLabTeams on GitLab, often self-hosted
Azure Pipelinesazure-pipelines.ymlMicrosoft-hosted or self-hosted agentsTeams on Azure DevOps and Microsoft stacks
Careful: Common mistakes. (1) Running builds on the controller. (2) Updating all plugins at once on production Jenkins without a backup or a test instance. (3) Secrets in double-quoted Groovy strings. (4) Huge scripted pipelines copied into every repository: move shared logic into a shared library. (5) Never backing up the Jenkins home folder, which holds all jobs, history and credentials.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Jenkins pipelines · 1/7

Jenkins

In this lesson you will learn Jenkins, a self-hosted automation server that many enterprises use for CI and CD.

Prefer a video by a teacher? Find free videos on “jenkins declarative pipeline jenkinsfile tutorial” on YouTube ↗

In real life: A private bank keeps CI inside its data centre

A private bank in Mumbai is not allowed to send its core banking code to an outside build service. It runs Jenkins on its own servers: one controller, and agents created as Kubernetes pods for each build. Each repository has a Jenkinsfile; a multibranch pipeline builds every branch and pull request, and a webhook from the internal GitLab server starts builds within seconds. Production deploys stop at an input step that only the change-approval group may approve. A small platform team spends a few days each month testing plugin updates on a copy of Jenkins before applying them.

Practice (0/3 done)

Task 1 · Question

In Jenkins, which part actually runs the build steps?

Task 2 · Question

In a declarative pipeline, which block runs steps after the stages, whether the build passed or failed?

Task 3 · Practice

Write a declarative Jenkinsfile for a Java Maven app: run on agents labelled "maven"; stages Checkout, Build (mvn -B clean package), Test reports, and Deploy to staging that runs only on the main branch using a script ./deploy.sh staging; publish JUnit results from target/surefire-reports/*.xml in post always; and print a message on failure.

Quick quiz

Question 1

1.What is a multibranch pipeline in Jenkins?

Question 2

2.What does credentials('registry-creds') in an environment block do for a username-and-password credential?

Question 3

3.Why do teams use webhooks with Jenkins?

Question 4

4.Which is a real cost of choosing Jenkins?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

What is a multibranch pipeline in Jenkins?

Answer: A job that finds every branch and pull request with a Jenkinsfile and creates a pipeline for each

Multibranch jobs scan the repository and keep one pipeline per branch or PR.

What does credentials('registry-creds') in an environment block do for a username-and-password credential?

Answer: Sets a variable with the value and also _USR and _PSW variables

For REGISTRY = credentials(...), Jenkins sets REGISTRY, REGISTRY_USR and REGISTRY_PSW and masks them in logs.

Why do teams use webhooks with Jenkins?

Answer: So the Git server tells Jenkins about a push at once, instead of Jenkins polling

Webhooks start builds within seconds and avoid constant polling.

Which is a real cost of choosing Jenkins?

Answer: You must maintain, patch, back up and secure the server and its plugins yourself

Self-hosting gives control but adds operations work, and plugins need regular security updates.

What is an artefact in a DevOps pipeline?Related

Answer: A file produced by the build, such as a .jar or container image, that is stored and deployed

Artefacts are build outputs. Storing them means you deploy exactly what was tested.

From The DevOps toolchain and your learning roadmap

Why does the capstone Dockerfile use two stages?Related

Answer: So the final image contains only what is needed to run, not the build tools

Multi-stage builds keep compilers and dev dependencies out of the final image: smaller and fewer things to attack.

From Capstone project: from commit to monitored production

What does "pipeline as code" mean?Related

Answer: The pipeline definition is a file in the repository, reviewed and versioned with the code

A workflow YAML or a Jenkinsfile in the repo gives history, review and easy copying between projects.

From Continuous integration, delivery and deployment

Why do teams define required tags like owner and cost-centre?Related

Answer: To split the bill by team, find owners of resources and select resources for backups and policies

Tags drive cost reports, ownership and automation. AWS does not require them by default, so teams enforce them with policy.

From IaC in a team: reviews, pipelines and policy

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 2 more topics in “CI/CD pipelines” before its exam: Testing, quality gates and artefacts, Deployment strategies, feature flags and GitOps.
  2. Module 6 exam: CI/CD pipelines · 12 questions · 20 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Infrastructure as code with Terraform. 53 topics left in the course before the final exam.

← Previous: GitHub Actions