Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 40 ยท Scaling and Operating Jenkins

Jenkins Configuration as Code (JCasC)

Describe a whole Jenkins controller in a YAML file: jenkins.yaml, plugins baked into a Docker image, secrets from the environment, seed jobs and drift checks.

A Jenkins controller that was set up by clicking through the web interface is a snowflake. Nobody remembers which boxes were ticked, a lost disk means a lost server, and a second controller for testing never quite matches production. Configuration as Code fixes this by moving the settings out of the UI and into a text file that lives in Git, just like your Jenkinsfile.

The tool for this is the Configuration as Code plugin, usually called JCasC. You write a YAML file (conventionally jenkins.yaml), point Jenkins at it, and on startup Jenkins configures itself to match. This lesson shows the file format, how to bake plugins and config into a Docker image, how to keep secrets out of the file, how seed jobs create pipelines, and how to notice when someone changed the server by hand. The real controller cannot run on this site, so the YAML and Docker files are read-only, and the runnable examples are Node stand-ins that apply and compare configuration.

Click-ops versus config as code

Click-ops Settings live only inside the running server.
jenkins.yaml Settings live in a reviewed file in Git.
Reproducible Rebuild the same controller in minutes.

If the server dies, the file is the recovery plan.

1 / 2

What a jenkins.yaml looks like

The file has a few top-level keys that mirror sections of the Manage Jenkins pages: jenkins for core settings, security for some security options, unclassified for plugin settings that live on the "System" page, tool for tool installations, credentials for the credential store, and jobs for Job DSL. Here is a compact, realistic example (read-only):

YAML
jenkins:
  systemMessage: "Managed by code. Do not edit settings in the UI."
  numExecutors: 0
  securityRealm:
    local:
      allowsSignup: false
      users:
        - id: "admin"
          password: "${ADMIN_PASSWORD}"
  authorizationStrategy:
    loggedInUsersCanDoAnything:
      allowAnonymousRead: false
  nodes:
    - permanent:
        name: "linux-1"
        remoteFS: "/home/jenkins"
        numExecutors: 2
        labelString: "linux java21"
        launcher:
          inbound:
            workDirSettings:
              disabled: false

unclassified:
  location:
    url: "https://jenkins.example.com/"

credentials:
  system:
    domainCredentials:
      - credentials:
          - string:
              scope: GLOBAL
              id: "slack-token"
              description: "Slack bot token"
              secret: "${SLACK_TOKEN}"

Read it from the top. Setting numExecutors: 0 follows the advice from Jenkins Architecture: the controller orchestrates and agents build. The local user database creates one admin whose password is not in the file; ${ADMIN_PASSWORD} is a placeholder filled in at startup. The agent linux-1 is declared as code, so a new controller comes up with the same labels.

You do not have to remember the schema. The plugin adds Manage Jenkins > Configuration as Code, where you can view the current configuration exported as YAML, open a reference of every key your installed plugins accept, and reload the file. A good workflow is to configure something once in the UI on a throwaway controller, export the YAML, and paste the relevant part into your repository.

Telling Jenkins where the file is

Jenkins finds the configuration through the CASC_JENKINS_CONFIG environment variable. It can be a path to one file, a path to a folder (every .yaml, .yml and .json file in it is merged), or an HTTPS URL.

Splitting configuration into several files keeps reviews small:

TEXT
casc/
  00-core.yaml           numExecutors, security realm, authorization
  10-agents.yaml         permanent agents and cloud templates
  20-credentials.yaml    credential references (values come from the environment)
  30-jobs.yaml           the seed job

Merged files must not define the same setting twice with conflicting values, and Jenkins reports an error when they do. Numeric prefixes only make the intent obvious to humans.

A controller you can rebuild: the Docker image

The most robust setup bakes both plugins and configuration into a custom image. Every build of the image is then a complete, versioned controller. The official image ships a command called jenkins-plugin-cli for installing plugins from a list.

plugins.txt:

TEXT
configuration-as-code:latest
job-dsl:latest
workflow-aggregator:latest
git:latest
credentials-binding:latest
prometheus:latest

For real systems, replace latest with exact versions you have tested (see Plugins: Finding, Managing and Pinning); latest is used here only to keep the example short.

Dockerfile:

DOCKERFILE
FROM jenkins/jenkins:lts-jdk21

# Skip the interactive setup wizard: JCasC creates the admin user
ENV JAVA_OPTS="-Djenkins.install.runSetupWizard=false"
ENV CASC_JENKINS_CONFIG=/var/jenkins_home/casc

COPY plugins.txt /usr/share/jenkins/ref/plugins.txt
RUN jenkins-plugin-cli --plugin-file /usr/share/jenkins/ref/plugins.txt

COPY casc/ /var/jenkins_home/casc/

Run it and pass the secrets as environment variables:

Terminal
docker build -t my-jenkins:2024-01 .
docker run -d --name jenkins -p 8080:8080 \
  -e ADMIN_PASSWORD="$(cat admin.pw)" \
  -e SLACK_TOKEN="$(cat slack.token)" \
  -v jenkins_home:/var/jenkins_home \
  my-jenkins:2024-01

Because the image contains the plugins, startup does not depend on the update center being reachable, and an upgrade is "build a new image, run it". For the Docker commands themselves, see the Docker tutorial.

Keeping secrets out of the file

A YAML file in Git must never contain a password. JCasC supports placeholders that are resolved when the file is loaded:

  • ${NAME} reads an environment variable.
  • ${NAME:-fallback} uses a fallback when the variable is not set.
  • ${readFile:/run/secrets/admin_password} reads a file, which fits Docker and Kubernetes secrets that are mounted as files.
YAML
jenkins:
  securityRealm:
    local:
      users:
        - id: "admin"
          password: "${readFile:/run/secrets/admin_password}"

The placeholders are resolved in memory. Jenkins then stores credentials in its own encrypted store, so they are not shown back in the exported YAML (the export uses encrypted values or placeholders). Two warnings are worth remembering: whoever can read the container's environment can read the secrets, and a typo in a variable name makes startup fail, which is better than silently using an empty password. See Credentials and Secrets for the bigger picture.

Seed jobs: creating pipelines from code

Controller settings are only half of the story. You also want the jobs to be code. With the Job DSL plugin, a small Groovy script describes jobs, and a seed job runs it. JCasC can create the seed job itself through the jobs: key:

YAML
jobs:
  - script: >
      multibranchPipelineJob('shop') {
        branchSources {
          github {
            id('shop-source')
            repoOwner('example-org')
            repository('shop')
            scanCredentialsId('github-app')
          }
        }
        orphanedItemStrategy {
          discardOldItems {
            numToKeep(20)
          }
        }
      }

When the controller starts, this script runs and creates a multibranch job named shop (see Multibranch Pipelines). Growing teams usually keep a longer script, or a list of repository names, in a separate repository and create one job per entry. The effect is that adding a project is a pull request, not a series of clicks.

Job DSL runs Groovy with real power. Only let trusted people change the seed script, and review it like production code.

Reloading and drift

JCasC applies the file at startup. You can also press Reload existing configuration on the Configuration as Code page (or call the reload endpoint) to apply changes without a restart. Jenkins then overwrites the matching settings.

That raises the question of drift: someone changes a setting in the UI, and now the running server no longer matches Git. Three habits keep drift under control:

  1. Put a banner in systemMessage that says settings are managed by code.
  2. Treat the exported YAML from the running server as a diagnostic: compare it with the file in Git, and open a pull request when they differ for a good reason.
  3. Restart or reload regularly, so any unrecorded change disappears quickly and people learn to commit it.

Not every setting is covered by JCasC. Plugin support varies, and runtime data such as build history and secrets is not configuration. Treat JCasC as the source of truth for what it covers, and keep JENKINS_HOME backups for the rest (see Backup, Monitoring and Troubleshooting).

A stand-in that applies a config

The first stand-in is a toy controller. It takes a configuration object (JSON-shaped, like parsed YAML), resolves ${NAME} and ${NAME:-fallback} placeholders from an environment, stops with a clear error when a variable is missing, and then applies the result to a settings model. This is not the real plugin; it shows the idea of "load, resolve, apply, never print secrets".

JS A stand-in that resolves placeholders and applies config

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice the two behaviors that matter in real life. The missing ENVIRONMENT_NAME falls back to dev instead of failing, and the missing SLACK_TOKEN stops the load with an error that names the placeholder. Failing loudly is the safe choice for secrets.

A stand-in drift detector

The second stand-in compares the configuration in Git with what a "running" controller reports. It flattens both objects into dotted paths and prints the differences, which is the same idea as diffing an exported jenkins.yaml against the repository.

JS A stand-in drift detector

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Someone raised the executors on the controller to 2 and added a checkout retry count by hand. Both show up. The first is a policy violation to revert; the second may be worth committing to the file.

Start small. Move the security realm, authorization and agents into JCasC first, because losing those hurts most. Add the rest as you touch it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main benefit of Jenkins Configuration as Code?

    JCasC describes controller configuration (security, agents, settings) in YAML. It does not speed up builds and it does not replace pipelines.
  2. 2. How should the admin password appear in a jenkins.yaml that is stored in Git?

    Placeholders are resolved at load time from environment variables or files such as /run/secrets/..., so the secret never enters the repository.
  3. 3. Which environment variable tells Jenkins where its JCasC configuration is?

    CASC_JENKINS_CONFIG can point to a file, a folder of YAML files or a URL.
  4. 4. What does a seed job do?

    A seed job runs Job DSL code that generates job definitions, so adding a project becomes a change to code instead of UI clicks.
  5. 5. Someone changes a global setting in the UI on a JCasC-managed controller. What is the usual result after the next reload or restart?

    The file is the source of truth for the settings it covers, which is why drift checks and a visible 'managed by code' message are useful.

Summary

  • JCasC describes a controller in jenkins.yaml; CASC_JENKINS_CONFIG points Jenkins at it (a file, a folder or a URL).
  • Bake plugins (jenkins-plugin-cli, a pinned plugins.txt) and the config into a Docker image to get a reproducible controller.
  • Keep secrets out of Git with ${NAME}, ${NAME:-fallback} and ${readFile:...} placeholders.
  • Job DSL and a seed job create the pipeline jobs from code.
  • Compare the running configuration with Git to catch drift, and restore anything JCasC does not cover from backups.

Next, learn how to protect and monitor a controller in Backup, Monitoring and Troubleshooting.