Skip to content
Visual explainer 4h to learn 4 steps

Jenkins pipelines (for interviews and legacy shops)

Read and write a declarative Jenkinsfile.

By Invicly Tech, , in Full DevOps with Python. About 11 minutes to read.

Topic 19 of 34

In short

Jenkins is a self-hosted automation server still common in older and enterprise setups. A declarative Jenkinsfile in the repo defines stages, agents, credentials and post-build actions.

Explained simply

Jenkins is an open-source automation server. Companies install it on their own machines and use it to build, test and deploy code. It has been around since 2011 (it started as Hudson), so many banks, telecoms and large enterprises still run it.

Jenkins has a main server, called the controller, and worker machines, called agents. The controller shows the web interface, stores job settings and decides what runs where. Agents do the actual work, like running tests or building images.

Today, the pipeline is written as code in a file named Jenkinsfile, stored in the same Git repository as the app. The file lists stages, such as Test and Build, and the steps inside each stage. Changes to the pipeline then go through normal code review.

Almost everything in Jenkins comes from plugins: Git support, Docker agents, credentials, Slack messages. Plugins make Jenkins very flexible, but you must keep them updated, because old plugins are a common security risk.

Press Play on a diagram to walk through it one step at a time.

CompareJenkins vs GitHub Actions
Jenkins
  • You host and patch it
  • Huge plugin ecosystem
  • Groovy Jenkinsfile
  • Works with any Git host
GitHub Actions
  • Hosted by GitHub
  • Marketplace actions
  • YAML workflows
  • Tightly integrated with PRs
SequenceA push triggers a multibranch pipeline
GitHub
Controller
Agent
  1. 1Webhook: push to feature/login
    GitHub to Controller: Webhook: push to feature/login
  2. 2Fetch Jenkinsfile from that branch
    Controller to GitHub: Fetch Jenkinsfile from that branch
  3. 3Schedule build on an agent with label docker
    Controller to Agent: Schedule build on an agent with label docker
  4. 4Checkout the code
    Agent to GitHub: Checkout the code
  5. 5Stream logs and test results
    Agent to Controller: Stream logs and test results
  6. 6Report commit status: success
    Controller to GitHub: Report commit status: success

In depth

Controller, agents, executors and jobs

The controller is a Java web application (it runs on Java 17 or newer, by default on port 8080). Its home directory, usually /var/jenkins_home in the official Docker image, holds job configs, build history and plugins, so it must be backed up.

Agents connect to the controller in two main ways: the controller opens an SSH connection to the agent, or the agent connects inbound to the controller (over TCP port 50000 or WebSocket). Each agent has a number of executors, the slots that run builds at the same time. Labels like linux or docker let a pipeline choose suitable agents. Agents can also be created on demand as Docker containers or Kubernetes pods and thrown away after the build.

Run builds on agents, not the controller. Builds on the controller can read its files, including secrets, so the recommended setting is zero executors on the controller.

LayersJenkins from the user down to the build
  1. 1
    Web UI and webhooks

    Users and GitHub trigger jobs

  2. 2
    Controller

    Schedules builds, stores config and history

  3. 3
    Plugins

    Git, credentials, Docker, Kubernetes agents

  4. 4
    Agents

    Machines, containers or pods with labels

  5. 5
    Executors

    Slots on an agent that each run one build

Declarative pipeline structure

A declarative Jenkinsfile starts with pipeline and must contain agent and stages. agent any runs on any available agent; agent { label 'docker' } picks by label; agent { docker { image 'python:3.12-slim' } } runs the steps inside a container. You can also set agent none at the top and choose an agent per stage.

Optional blocks give control. environment sets variables. options can add timeout(time: 30, unit: 'MINUTES') or disableConcurrentBuilds(). parameters adds inputs for manual runs. triggers can poll or run on a cron schedule, though webhooks from GitHub are better than polling.

Inside stages, each stage has steps such as sh, echo or junit. when decides whether a stage runs: when { branch 'main' } works in multibranch pipelines. parallel runs stages side by side. input pauses for a human to approve, which is how many teams gate production.

The older scripted pipeline (node { ... }) is plain Groovy: more freedom, but harder to read and validate.

  • Required: pipeline, agent, stages, stage, steps
  • when { branch 'main' } limits a stage to main
  • input pauses for manual approval
  • options { timeout(...) } stops hung builds

Post steps and credentials

The post block runs after the pipeline or a stage, depending on the result. always runs every time, success and failure run on those results, unstable runs when tests failed but the build finished, changed runs when the result differs from the previous build, and cleanup runs last of all. Typical uses: publish JUnit test reports in always, send a chat message in failure, and delete the workspace in cleanup.

Secrets live in the Jenkins credentials store, not in the Jenkinsfile. There are two common ways to use them. In environment, CREDS = credentials('dockerhub') for a username and password credential sets CREDS_USR and CREDS_PSW. In steps, withCredentials binds them only inside a block.

Jenkins masks secret values in the console log. Use single quotes in sh steps, like sh 'echo $PASS | docker login -u $USER --password-stdin', so the shell expands the variable and Groovy never puts the secret into the command string.

Mappost conditions
post { }
  • always
    • Publish test reports
  • success
    • Tag or announce the build
  • failure
    • Notify the team
  • unstable
    • Tests failed, build finished
  • changed
    • Result differs from last build
  • cleanup
    • Runs last, delete workspace

Jenkins vs GitHub Actions in practice

The biggest difference is who runs it. With Jenkins you own the server: installing, scaling agents, upgrading Jenkins and plugins, backups and security. In return you get full control, it works with any Git host, and it can run inside a private network with access to internal systems.

GitHub Actions is hosted, needs no maintenance for GitHub-hosted runners, and shows results right on the pull request. Reusable logic is shared as actions or reusable workflows; in Jenkins it is shared as plugins or shared libraries (Groovy code loaded with @Library).

Concepts map closely, which helps in interviews: a Jenkinsfile is like a workflow file, a stage is like a job or a group of steps, an agent is like a runner, credentials are like secrets, post failure is like if: failure(), and a multibranch pipeline is like on: push for every branch. Many companies migrate from Jenkins to Actions or GitLab CI, so being able to read both is valuable.

Learn it in 4 short steps

About 1h each. Track them with a timer in your plan.

  1. 1
    Learn Jenkins agents, jobs and plugins~1h
  2. 2
    Write a declarative Jenkinsfile~1h
  3. 3
    Add stages, post steps and credentials~1h
  4. 4
    Compare Jenkins with GitHub Actions~1h

Key points

  • The controller schedules jobs; agents are the machines that run them.
  • A declarative pipeline has pipeline, agent, stages and steps blocks.
  • post { always / failure } runs clean-up or notifications after stages.
  • Store secrets in Jenkins credentials and bind them with withCredentials.

Key terms

Tap a card to flip it. 0/5 known

Examples

groovy
pipeline {
  agent { docker { image 'python:3.12-slim' } }
  stages {
    stage('Test') {
      steps { sh 'pip install -r requirements.txt && pytest -q' }
    }
    stage('Build') {
      when { branch 'main' }
      steps { sh 'docker build -t api:${GIT_COMMIT} .' }
    }
  }
  post {
    failure { echo 'Build failed, notify the team' }
  }
}

A declarative Jenkinsfile with test, build and a failure hook.

A Jenkinsfile with tests, credentials and test reports

Step 1: a timeout stops builds that hang. Step 2: Test installs dependencies into a virtualenv, runs pytest and writes a JUnit XML report. Step 3: Push runs only on main and logs in with a stored username and password credential. Step 4: the shell, not Groovy, expands $P because the sh string uses single quotes, and Jenkins masks the value in the log. Step 5: post always publishes test results even when tests fail. The junit step comes from the JUnit plugin.

groovy
pipeline {
  agent { label 'docker' }
  options { timeout(time: 30, unit: 'MINUTES') }
  environment { IMAGE = "acme/api:${env.GIT_COMMIT}" }
  stages {
    stage('Test') { steps { sh 'python3 -m venv .venv && .venv/bin/pip install -r requirements.txt && .venv/bin/pytest -q --junitxml=report.xml' } }
    stage('Push') {
      when { branch 'main' }
      steps { withCredentials([usernamePassword(credentialsId: 'dockerhub', usernameVariable: 'U', passwordVariable: 'P')]) {
        sh 'echo $P | docker login -u $U --password-stdin && docker build -t $IMAGE . && docker push $IMAGE'
      } }
    }
  }
  post { always { junit 'report.xml' } }
}

Translate the Jenkinsfile to GitHub Actions

An interviewer asks how you would migrate. Step 1: the Jenkinsfile becomes .github/workflows/ci.yml. Step 2: agent label docker becomes runs-on: ubuntu-latest. Step 3: when branch main becomes an if on the job. Step 4: the credentials store becomes repository secrets. Step 5: input becomes a GitHub environment named production with required reviewers. Step 6: post always junit becomes a step with if: always() that uploads the report.

text
Jenkins                          GitHub Actions
pipeline { stages { ... } }   -> jobs: in .github/workflows/ci.yml
agent { label 'docker' }      -> runs-on: ubuntu-latest
when { branch 'main' }        -> if: github.ref == 'refs/heads/main'
withCredentials(...)          -> secrets.DOCKERHUB_TOKEN
input 'Deploy?'               -> environment: production (required reviewers)
post { always { junit } }     -> a step with if: always()
post { failure { ... } }      -> a step with if: failure()

Quick reference

  • Controller schedules and stores; agents run builds; set controller executors to 0
  • Declarative skeleton: pipeline { agent any; stages { stage('X') { steps { ... } } } }
  • when { branch 'main' } runs a stage only on main in a multibranch pipeline
  • post conditions: always, success, failure, unstable, changed, cleanup
  • environment { C = credentials('id') } gives C_USR and C_PSW for username and password
  • Use single quotes in sh with secrets so Groovy does not interpolate them
  • Initial admin password: /var/jenkins_home/secrets/initialAdminPassword
  • Validate a Jenkinsfile with the Replay button or the declarative linter before committing

Common mistakes

  • Running builds on the controller itself instead of on agents.
  • Letting plugins go unpatched; old plugins are a common attack path.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Why should the controller have zero executors?

Question 2

2Which post condition runs when tests failed but the build itself completed?

Question 3

3In environment { CREDS = credentials('dockerhub') } with a username and password credential, which variables are created?

Question 4

4Which step pauses a pipeline until a person approves?

Question 5

5What is the GitHub Actions equivalent of a Jenkins agent?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Run Jenkins locally in Docker, find the initial admin password and open the UI.

  2. Exercise 2medium

    Write a declarative Jenkinsfile that runs lint and tests in parallel inside a python:3.12-slim container and always publishes the JUnit report.

  3. Exercise 3hard

    Add a production deploy stage that runs only on main, asks for approval with a 1-hour limit, and sends a failure notice if anything in the pipeline fails.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Is Jenkins still worth learning in 2026?
Yes, as a second CI tool. Many large companies still run Jenkins, and interviews often ask about Jenkinsfiles, but new projects more often start on GitHub Actions or GitLab CI.
What is the difference between declarative and scripted pipelines?
Declarative pipelines use a fixed structure (pipeline, agent, stages, post) that is easier to read and validate. Scripted pipelines are plain Groovy inside node blocks and allow any logic, at the cost of readability.
What is a multibranch pipeline?
A job type that scans a repository and creates a pipeline for every branch (and pull request) that has a Jenkinsfile. It is what makes when { branch 'main' } meaningful.
How do I keep Jenkins secure?
Keep Jenkins and its plugins updated, run builds only on agents, store secrets in the credentials store, and limit who can configure jobs. Remove plugins you do not use.

Go deeper

ShareXLinkedInWhatsApp