Jenkins Configuration as Code (JCasC): Define Jenkins in YAML, Job DSL and a Reproducible Docker Image
The Problem With Click Configuration
Configuring Jenkins by clicking in the UI is quick, but nobody knows what changed, when or why, and a lost server means you must remember everything. Configuration as Code (JCasC) writes the configuration in a YAML file kept in Git: reviewable, repeatable, restorable.
| UI clicks | JCasC |
| Hidden, hard to review | Visible in pull requests |
| Disaster = rebuild from memory | Start a new container and it configures itself |
| Staging and production drift apart | Same file, different variables |
| Manual plugin installs | Plugin list in a file |
What JCasC Can Configure
- Security realm and authorization
- System settings: URL, message, number of executors, global libraries
- Tools: JDK, Maven, Git, Node
- Credentials (with secrets from variables)
- Agents and clouds (Kubernetes, Docker, EC2)
- Plugin settings: Slack, SonarQube, Artifactory, GitHub servers
Install and Point Jenkins at the File
- Install the Configuration as Code plugin (
configuration-as-code)
- Create
jenkins.yaml
- Set the environment variable
CASC_JENKINS_CONFIG to the file path, a folder, or a URL
- Start Jenkins. Configuration applies at startup
- Check Manage Jenkins → Configuration as Code: view, reload, or export current settings
bash
docker run -d --name jenkins -p 8080:8080 \
-e CASC_JENKINS_CONFIG=/var/jenkins_home/casc/ \
-e JENKINS_ADMIN_PASSWORD=ChangeMe123 \
-v $PWD/casc:/var/jenkins_home/casc:ro \
-v jenkins_home:/var/jenkins_home \
jenkins/jenkins:lts-jdk21
A Complete jenkins.yaml
yaml
jenkins:
systemMessage: "Managed by JCasC. Change via Git, not by clicking."
numExecutors: 0
mode: EXCLUSIVE
scmCheckoutRetryCount: 2
securityRealm:
local:
allowsSignup: false
users:
- id: "admin"
password: "${JENKINS_ADMIN_PASSWORD}"
authorizationStrategy:
globalMatrix:
entries:
- user:
name: "admin"
permissions: ["Overall/Administer"]
- group:
name: "authenticated"
permissions: ["Overall/Read", "Job/Read"]
nodes:
- permanent:
name: "linux-1"
remoteFS: "/home/jenkins"
labelString: "linux docker"
numExecutors: 4
launcher:
ssh:
host: "agent1.example.com"
port: 22
credentialsId: "agent-ssh-key"
sshHostKeyVerificationStrategy: "knownHostsFileKeyVerificationStrategy"
unclassified:
location:
url: "https://jenkins.example.com/"
adminAddress: "devops@example.com"
slackNotifier:
teamDomain: "mycompany"
tokenCredentialId: "slack-token"
tool:
git:
installations:
- name: "Default"
home: "git"
maven:
installations:
- name: "maven-3.9"
properties:
- installSource:
installers:
- maven: {id: "3.9.9"}
credentials:
system:
domainCredentials:
- credentials:
- usernamePassword:
scope: GLOBAL
id: "registry-creds"
username: "ci-bot"
password: "${REGISTRY_PASSWORD}"
description: "Docker registry"
- string:
scope: GLOBAL
id: "slack-token"
secret: "${SLACK_TOKEN}"
description: "Slack bot token"
${NAME} reads an environment variable or a file secret (for example Docker secrets in /run/secrets)
- Never write real secrets in the YAML file. Use variables or a secret source (Vault, Kubernetes secrets, Docker secrets)
- To keep a literal
${, escape with ^${
Find the Right YAML Keys
Do not guess. Open Manage Jenkins → Configuration as Code → Documentation to see every key available for your installed plugins, or use View Configuration to see the YAML of your current settings, then copy it into Git.
Create Jobs With Job DSL
JCasC configures the controller; Job DSL creates jobs from code. A seed job reads DSL scripts and generates or updates many jobs.
yaml
jobs:
- script: >
multibranchPipelineJob('shop') {
branchSources {
github {
id('shop-repo')
scanCredentialsId('github-app')
repoOwner('mycompany')
repository('shop')
}
}
orphanedItemStrategy { discardOldItems { numToKeep(20) } }
}
- script: >
folder('team-a') { displayName('Team A') }
- script: >
pipelineJob('team-a/nightly') {
triggers { cron('H 2 * * *') }
definition {
cpsScm {
scm { git { remote { url('https://git.example.com/team-a/nightly.git') } branch('main') } }
scriptPath('Jenkinsfile')
}
}
}
Folder of scripts: For many jobs, keep DSL files in a Git repository and use url: or a seed pipeline that checks them out and runs jobDsl targets: 'jobs/**/*.groovy'. Adding a file adds a job.
A Reproducible Image
text
# plugins.txt
configuration-as-code
job-dsl
git
workflow-aggregator
credentials-binding
matrix-auth
kubernetes
slack
sonar
prometheus
timestamper
ws-cleanup
docker
FROM jenkins/jenkins:lts-jdk21
USER root
RUN apt-get update && apt-get install -y --no-install-recommends git curl jq && rm -rf /var/lib/apt/lists/*
USER jenkins
ENV JAVA_OPTS="-Djenkins.install.runSetupWizard=false"
ENV CASC_JENKINS_CONFIG=/usr/share/jenkins/ref/casc
COPY --chown=jenkins:jenkins plugins.txt /usr/share/jenkins/ref/plugins.txt
RUN jenkins-plugin-cli --plugin-file /usr/share/jenkins/ref/plugins.txt
COPY --chown=jenkins:jenkins casc/ /usr/share/jenkins/ref/casc/
runSetupWizard=false skips the unlock screen: security comes from JCasC, so configure it before exposing the server
jenkins-plugin-cli resolves dependencies and installs plugins at build time
- Pin plugin versions in
plugins.txt (git:5.7.0) for repeatable builds, update by pull request
- Mount
/var/jenkins_home as a volume for job history and build data
Reload and Verify
bash
# Reload after changing the file (needs admin API token)
curl -sS -X POST -u admin:$TOKEN https://jenkins.example.com/configuration-as-code/reload
# Check the file before applying
curl -sS -X POST -u admin:$TOKEN --data-binary @casc/jenkins.yaml https://jenkins.example.com/configuration-as-code/checkNewSource
- Run a staging Jenkins with the new file first
- Add a CI job for the config repo that starts a temporary Jenkins container with the YAML and fails if it does not start
Workflow Through Git
- Developer opens a pull request that changes
casc/jenkins.yaml or plugins.txt
- A test pipeline builds the image and starts it, checking the health page
- Reviewers approve, the change merges
- A deployment applies the new image or reloads the config
- Rollback is
git revert
Manual changes are overwritten: After the file is applied, UI changes can disappear on restart or reload. Make the change in Git. Use the export feature to copy UI experiments into YAML.
Practice Tasks
- Start Jenkins with JCasC and a
jenkins.yaml that sets the system message and one admin user
- Add a credential, a Maven tool and a Slack setting
- Create a folder and a multibranch job with Job DSL
- Build a Docker image with
plugins.txt and casc/
- Change the setting in YAML and reload without a restart
Conclusion
JCasC describes Jenkins in YAML, Job DSL creates jobs from code, and plugins.txt plus a Docker image make a repeatable controller. Keep secrets in variables, change through pull requests, and rebuild a whole Jenkins from Git in minutes.
Quick Summary: JCasC plugin + CASC_JENKINS_CONFIG; jenkins.yaml sections; ${VAR} secrets; Job DSL jobs; plugins.txt + Dockerfile; reload; Git workflow.