# Jenkins: the controller, agents, Jenkinsfile and shared libraries

Jenkins still runs a huge share of company pipelines: a controller handing work to agents, shop-api's pipeline as a declarative Jenkinsfile, plugins and their risks, and shared libraries.

Course: [CI/CD Pipelines](https://devops.rajeev.pro/courses/cicd), lesson 8. About 40 minutes, intermediate. Source: https://devops.rajeev.pro/courses/cicd/08-jenkins

## What you will learn

- Explain the controller and agents, and why builds should never run on the controller
- Read and write a declarative Jenkinsfile with stages, agents, environment, when and post
- Use credentials safely with withCredentials, and know how Jenkins masks them
- Choose and maintain plugins, and know why they are Jenkins's biggest risk
- Share pipeline code between teams with a shared library
- Map Jenkins ideas to GitHub Actions, and know when Jenkins is the right choice

## Why learn Jenkins

Jenkins is the open-source automation server most companies started their CI on, and many still run it: you
host it yourself, it connects to any Git server, and thousands of plugins extend it. You'll meet it in banks,
telecoms and any team with years of pipelines behind it. The ideas are the ones you already know; the spelling
is Groovy.

Before hosted runners were common, teams installed a controller and agents inside their own network. Jenkins
still fits when builds require private systems, unusual hardware or an existing plugin ecosystem. The trade-off
is that your team patches and secures the controller, agents and plugins. In this lesson, you'll express
shop-api's checks in a Jenkinsfile and compare that operating burden with hosted CI.

## The controller and agents

> **Figure.** Jenkins architecture. The controller is the central server: web UI, job configuration, plugins, credentials and the build queue. It runs no builds itself, with executors set to 0. When a commit arrives through a webhook, the controller reads the Jenkinsfile from the repository and schedules each stage on an agent with a matching label. Agents do the work: a static Linux VM, a Docker container started for the build, or a Kubernetes pod created per build and deleted afterwards. Agents send logs and results back to the controller. Credentials are handed to a build only inside withCredentials blocks.
>
> The controller plans and stores; agents build. Keep builds off the controller, where every credential lives.

| Part           | Does                                                        | GitHub Actions equivalent |
| -------------- | ----------------------------------------------------------- | ------------------------- |
| **Controller** | UI, jobs, plugins, credentials, queue, logs                 | GitHub itself             |
| **Agent**      | runs builds, connected by SSH or JNLP, or created per build | a runner                  |
| **Executor**   | one build slot on an agent                                  | one job on a runner       |
| **Label**      | which agents may run a stage (`linux && docker`)            | `runs-on:` labels         |

Set the controller's **number of executors to 0** (_Manage Jenkins → Nodes → Built-In Node_). A build on the
controller runs with access to `JENKINS_HOME`, where every job, credential and secret is stored. With the
Kubernetes plugin, each build gets a fresh pod that's deleted afterwards: the same "clean machine every time" that
GitHub-hosted runners give you.

> **Video.** [Learn Jenkins! Complete Jenkins Course - Zero to Hero](https://www.youtube.com/watch?v=6YZvp2GwT0A&t=99s) (DevOps Journey)

## The Jenkinsfile

A **Jenkinsfile** in the repository defines the pipeline as code, like `.github/workflows/`. Use the
**declarative** syntax: structured and validated. Here's shop-api's pipeline from the earlier lessons:

```groovy
// Jenkinsfile
pipeline {
  agent { docker { image 'node:22-alpine' } }        // every stage runs in this container

  options {
    timeout(time: 20, unit: 'MINUTES')
    disableConcurrentBuilds()
    buildDiscarder(logRotator(numToKeepStr: '30'))
  }

  environment {
    VERSION = "1.0.${env.BUILD_NUMBER}-${env.GIT_COMMIT.take(7)}"
  }

  stages {
    stage('Install') {
      steps { sh 'npm ci' }
    }
    stage('Checks') {
      parallel {                                       // lint and unit at the same time
        stage('Lint') { steps { sh 'npm run lint' } }
        stage('Unit') { steps { sh 'npm run test:coverage' } }
      }
    }
    stage('Integration') {
      steps { sh 'npm run test:integration' }
    }
    stage('Package') {
      steps {
        sh 'mkdir -p dist && cp -r src package.json dist/ && tar -czf shop-api-${VERSION}.tgz -C dist .'
        archiveArtifacts artifacts: 'shop-api-*.tgz', fingerprint: true
      }
    }
    stage('Deploy to production') {
      when { branch 'main' }
      input { message 'Deploy to production?'; ok 'Deploy' }   // waits before taking an agent
      agent { label 'deploy' }                         // an agent that can reach the servers
      steps {
        withCredentials([sshUserPrivateKey(credentialsId: 'deploy-key', keyFileVariable: 'SSH_KEY')]) {
          sh './scripts/deploy-ssh.sh deploy@shop.example.com "$VERSION" shop-api-*.tgz'
        }
      }
    }
  }

  post {
    failure { echo "Build ${env.BUILD_NUMBER} failed: ${env.BUILD_URL}" }
    always  { cleanWs() }
  }
}
```

| Jenkinsfile                 | Means                                        | Actions equivalent           |
| --------------------------- | -------------------------------------------- | ---------------------------- |
| `agent`                     | where the pipeline or a stage runs           | `runs-on:` / `container:`    |
| `stages { stage {} }`       | ordered steps of the pipeline                | jobs and steps               |
| `parallel { }`              | stages at the same time                      | jobs without `needs`         |
| `environment { }`           | variables for every step                     | `env:`                       |
| `when { branch 'main' }`    | run a stage only sometimes                   | `if:`                        |
| `input { }` on a stage      | pause for approval, before an agent is taken | environment reviewers        |
| `withCredentials`           | a secret, only inside the block              | `${{ secrets.X }}` in `env:` |
| `post { always / failure }` | after the stages                             | `if: always()` / `failure()` |
| `archiveArtifacts`          | keep files with the build                    | `upload-artifact`            |

The `docker` agent needs the _Docker Pipeline_ plugin and agents with Docker; `cleanWs()` comes from the
_Workspace Cleanup_ plugin. Note the quotes: Groovy expands `"${VERSION}"` in double quotes itself, while in `sh
'…$VERSION…'` (single quotes) the shell does, which is the safe way to pass values, for the same reason as `env:` in
Actions (lesson 11).

**Multibranch pipelines** find every branch and pull request with a Jenkinsfile and build each one, and a webhook
from GitHub or GitLab triggers them on push. The job's _Pipeline Syntax_ page generates the code for any step from a
form.

## Plugins: power and risk

Almost everything in Jenkins is a plugin: Git, credentials, pipelines, Docker, Kubernetes agents, Slack messages.
That flexibility is also its weakest point:

- Each plugin is maintained separately, and several have had serious vulnerabilities over the years.
- Plugins depend on each other and on the Jenkins version, so upgrades can break pipelines.
- They all run inside the controller, with its access to every credential.

Install only what you use, update Jenkins and plugins regularly (test upgrades on a copy first), and remove
plugins nobody needs. Follow the official **security advisories** (linked below). Manage the controller itself as
code: the _Configuration as Code_ plugin describes its settings in YAML, and a Dockerfile can pin the plugin list,
so a broken controller can be rebuilt instead of repaired by hand.

## Shared libraries

With fifty services, fifty copies of the same Jenkinsfile drift apart, just like workflow files (lesson 12). A
**shared library** is a Git repository of pipeline code that Jenkinsfiles load:

```text
jenkins-shared-library/
└── vars/
    └── nodePipeline.groovy      # becomes a step called nodePipeline
```

```groovy
// vars/nodePipeline.groovy
def call(Map config = [:]) {
  pipeline {
    agent { docker { image "node:${config.node ?: '22'}-alpine" } }
    stages {
      stage('Install') { steps { sh 'npm ci' } }
      stage('Lint')    { steps { sh 'npm run lint' } }
      stage('Test')    { steps { sh 'npm run test:coverage' } }
    }
    post { always { cleanWs() } }
  }
}
```

```groovy
// Jenkinsfile in each service
@Library('company-pipelines@v1') _
nodePipeline(node: '22')
```

Register the library once under _Manage Jenkins → System → Global Pipeline Libraries_, pin it to a tag such as
`@v1`, and version it like any shared code.

Jenkins loads library code into the pipeline before it runs. A global library can provide steps and helpers that
many Jenkinsfiles call, keeping repeated logic in one reviewed place. Pinning a version makes caller behavior
predictable; moving a shared library without review can change many services at once. Keep credentials in
Jenkins's credentials store and expose only the credential ID needed by a pipeline step. A shared library is
code reuse, not a permission boundary.

> **Video.** [Getting Started With Shared Libraries in Jenkins](https://www.youtube.com/watch?v=Wj-weFEsTb0&t=720s) (CloudBeesTV)

## Jenkins or GitHub Actions?

| Choose Jenkins when                                                  | Choose a hosted CI when                             |
| -------------------------------------------------------------------- | --------------------------------------------------- |
| builds must stay inside your network, with no cloud service involved | your code is on GitHub or GitLab already            |
| you need unusual hardware, OSes or tools                             | you'd rather not run and patch a CI server          |
| years of pipelines and plugins already depend on it                  | you want fresh runners and a marketplace of actions |

Plenty of companies run both: Jenkins for legacy and on-premises builds, Actions for new services. The pipeline
shape you've built in this course works in either.

Jenkins gives the team control over where the controller and agents run, but that control comes with patching,
backups, plugin review and access management. Hosted CI outsources much of that infrastructure and can start a
fresh runner for each job. Compare the network access and hardware the build needs with the staff available to
operate Jenkins. Keep pipeline concepts portable, and avoid migrating a working system only because another tool
has a newer interface.

> **In production.** Put the controller behind SSO with role-based access (the *Role-based Authorization Strategy* plugin), run builds only on ephemeral agents, keep `JENKINS_HOME` backed up, and store credentials in Jenkins's credentials store or an external vault, never in job configuration or Jenkinsfiles.

## Mission: Run shop-api's pipeline on Jenkins

Start Jenkins locally in Docker, create a Pipeline job that reads shop-api's Jenkinsfile from Git, and get Install, Checks (lint and unit in parallel), Integration and Package passing, with the package archived on the build page.

- You need: Docker, and the shop-api repository with the Jenkinsfile from this lesson.tgz archived"
>

```sh
$ docker volume create jenkins_home
$ docker run -d --name jenkins -p 8080:8080 -v jenkins_home:/var/jenkins_home jenkins/jenkins:lts-jdk21
$ docker exec jenkins cat /var/jenkins_home/secrets/initialAdminPassword   # paste into http://localhost:8080
```

Install the suggested plugins, plus _Docker Pipeline_ if your agent has Docker. Create _New Item → Pipeline_,
choose _Pipeline script from SCM_, give it the repository URL and branch `main`, and save. The controller in this
container has no Docker, so for the first run change the top line to `agent any` and install Node on the agent, or
add a Docker-capable agent with the label `docker`. _Build Now_: the stage view shows Install, then Lint and Unit side
by side, then Integration and Package, and the build page lists the archived `.tgz`. Delete the Deploy stage, or
leave it: `when { branch 'main' }` and `input` stop it until you approve.

## Try it

- Run Jenkins locally with `docker run -p 8080:8080 jenkins/jenkins:lts-jdk21` and finish the setup wizard.
- Create a Pipeline job that reads the Jenkinsfile from shop-api's repository.
- Set the controller's number of executors to 0 and add an agent, so builds run there only.
- Add a credential with ID `deploy-key` and use it in a stage with withCredentials.
- Use the *Pipeline Syntax* link in a job to generate a step, and compare it with what you'd write by hand.
- Move the npm steps into a shared library function and call it from the Jenkinsfile.

## Quiz

1. Why should builds run on agents, not on the Jenkins controller?
   - Agents are faster
   - **A build on the controller can read Jenkins's own files, including every stored credential; agents isolate builds from it** (answer)
   - The controller can't run shell commands
   - Licensing
   Why: Set the controller's executors to 0. Agents can be static machines, Docker containers or Kubernetes pods created per build.

2. What does the post { always { ... } } block in a Jenkinsfile do?
   - Runs before the pipeline
   - **Runs after the stages whatever the result, for cleanup or publishing test reports** (answer)
   - Posts to Slack
   - Retries failed stages
   Why: post has conditions like always, success, failure and unstable, the equivalent of if: always() and if: failure() in Actions.

3. How should a Jenkinsfile use a deploy key stored in Jenkins?
   - Paste it into the Jenkinsfile
   - **withCredentials, which exposes it only inside that block as a temporary file or variable and masks it in logs** (answer)
   - Store it in an environment variable at the top
   - Read it from the controller's disk
   Why: The secret exists only for the steps that need it. As in Actions, masking can't catch transformed values, so never print it.

4. Why are plugins a security concern in Jenkins?
   - They are slow
   - **Jenkins depends on many community plugins, each with its own update schedule and vulnerabilities, running with the controller's rights** (answer)
   - They cost money
   - They can't be removed
   Why: Install few, keep them and Jenkins updated, remove unused ones, and watch the Jenkins security advisories.

5. What is a Jenkins shared library?
   - A folder of build artifacts
   - **A Git repository of reusable pipeline code (vars/ steps) that Jenkinsfiles load with @Library** (answer)
   - A plugin marketplace
   - A list of agents
   Why: It's Jenkins's answer to reusable workflows: platform teams own the standard steps, and each Jenkinsfile stays short.

## Resources

- [Jenkins: pipeline syntax](https://www.jenkins.io/doc/book/pipeline/syntax/) (Jenkins)
- [Jenkins: using a Jenkinsfile](https://www.jenkins.io/doc/book/pipeline/jenkinsfile/) (Jenkins)
- [Jenkins: extending with shared libraries](https://www.jenkins.io/doc/book/pipeline/shared-libraries/) (Jenkins)
- [Jenkins: securing Jenkins](https://www.jenkins.io/doc/book/security/) (Jenkins)
- [Jenkins security advisories](https://www.jenkins.io/security/advisories/) (Jenkins)
