TecnoShop's pipelines have lived in Git since module 3, but the Jenkins that runs them has not: the security and roles from 05-02, the agent, the kubernetes cloud, the tecnoshop-lib library, the SonarQube server, Slack, the Maven and npm managed files, the credentials and the jobs themselves (orders-api, catalog-web, orders-delivery/...) were all created by clicking. If a new Jenkins had to be set up tomorrow, the only way would be to restore a backup or fill in dozens of forms again from memory. In this lesson you will close the loop with the three layers of Jenkins as code: the Jenkinsfile (which you already have), Configuration as Code (JCasC) for the controller configuration and Job DSL for the jobs. You will create the tecnoshop/jenkins-config repository, write a casc/jenkins.yaml without a single secret in it, generate the jobs with the seed-jobs seed job, see how the whole of Jenkins is rebuilt from Git and give the repository itself its own CI pipeline.

The Three Layers of Jenkins as Code

Layer What it describes Tool Where it lives at TecnoShop
Pipeline What each build does: stages, steps, conditions Jenkinsfile (+ tecnoshop-lib) In each application repository, since 03-01
Jobs Which jobs exist and how they are configured: folders, multibranch, Jenkinsfile source, behaviors, retention Job DSL tecnoshop/jenkins-config, jobs/ directory
Controller What Jenkins looks like: security, nodes, clouds, credentials, libraries, integrations, tools JCasC (Configuration as Code plugin) tecnoshop/jenkins-config, casc/ directory

And, underneath all three, what you already versioned in 05-04: the controller image (Dockerfile + plugins.txt). Together they answer the question "what Jenkins do we have?" with a git log.

The tecnoshop/jenkins-config Repository

In 05-04 Laura started versioning the ~/tecnoshop-jenkins directory "in a platform repository". Now she gives it a name and a structure: tecnoshop/jenkins-config, private, with a protected main (PRs reviewed by the platform team) and a CODEOWNERS that assigns everything to @tecnoshop/platform.

jenkins-config/
├── Dockerfile                  # controller image (05-04), now with JCasC
├── plugins.txt                 # + configuration-as-code and job-dsl
├── docker-compose.yml          # the lab (without .env or secrets)
├── casc/
│   └── jenkins.yaml            # controller configuration
├── jobs/
│   ├── multibranch.groovy      # orders-api, catalog-web, jenkins-config
│   ├── orders-delivery.groovy  # folder and CD/rollback jobs
│   └── views.groovy            # the TecnoShop view
├── test-secrets/               # FAKE values for this repository's CI
├── ci/
│   └── Jenkinsfile             # this repository's CI (section 13)
├── linux-agent/                # tecnoshop/linux-agent image (07-05, 08-01, 08-02)
├── lab/                        # registry, kind, practice servers...
└── .gitignore                  # .env, secrets/, backups/

Add the two new plugins to plugins.txt, with their versions, and validate the image on jenkins-test as always:

configuration-as-code:<version>
job-dsl:<version>

Configuration as Code: How It Works

JCasC reads one or more YAML files when Jenkins starts (and whenever it is asked to reload) and applies what they say to the controller configuration:

flowchart LR
    Y["casc/*.yaml"] --> P["Configuration as Code plugin"]
    S["Secrets:<br/>environment variables,<br/>/run/secrets/..."] -->|"${...}"| P
    P --> J["jenkins:<br/>security, nodes, clouds"]
    P --> C["credentials:"]
    P --> U["unclassified:<br/>libraries, Sonar, Slack..."]
    P --> T["tool:"]
    P --> SEC["security:"]
    P --> JOBS["jobs: (Job DSL)"]
  • The YAML has a fixed set of roots: jenkins (core: security, nodes, clouds, messages), credentials, security (plugin security settings), unclassified (the global configuration of most plugins, what you see in Manage Jenkins → System), tool (Manage Jenkins → Tools) and jobs (Job DSL scripts).
  • Below them, the keys are the names of each component's fields. Each plugin declares its own; that is why the reference lives in your own installation: Manage Jenkins → Configuration as Code → Documentation (or Reference, depending on the version) lists every key of the installed plugins.
  • The CASC_JENKINS_CONFIG environment variable says where the files are: a path to a file, to a directory (all its .yaml/.yml files are loaded) or a URL.
  • Whatever the YAML does not mention is left as it is; but in many sections that are lists (nodes, clouds, system credentials) the file replaces the whole list: anything not in the YAML disappears when it is applied. The YAML is the source of truth.

Starting from What Exists: View/Export and Why Not to Copy It as Is

Once the plugin is installed, Manage Jenkins → Configuration as Code appears, with buttons to view the current configuration (View Configuration), download it (Download Configuration), reload it (Reload existing configuration) and apply a new file (Apply new configuration).

View Configuration generates the YAML of your current Jenkins. It is the best way to discover your plugins' keys, but not a file to version:

Problem with the exported YAML Why it matters
It includes every value, including the defaults Hundreds of lines of noise; nobody will know what was decided on purpose
Secrets appear encrypted ({AQAAABAAAAAQ...}) with the key of this installation They cannot be decrypted on another Jenkins; in Git, they are encrypted secrets that should not be there
The export is "best effort" Some components do not export well or cannot be applied again as they are
It mixes configuration with state (internal IDs, computed values) Spurious differences on every export

TecnoShop's method: export, find the section for each piece in the exported YAML, and rewrite it in casc/jenkins.yaml with only what differs from the defaults, with secrets as ${...} and with comments that explain the decisions.

casc/jenkins.yaml: The Controller

The complete file is long; it is presented in blocks, in the order in which they appear. First, the jenkins root:

# casc/jenkins.yaml - Configuration of the TecnoShop Jenkins controller.
# Source of truth: tecnoshop/jenkins-config. Changes made in the interface are lost on reload.
# The ${...} values are resolved at startup from environment variables or files in /run/secrets/.

jenkins:
  systemMessage: >-
    TecnoShop Jenkins. Configuration managed from tecnoshop/jenkins-config:
    any change made here will be lost. Questions: [email protected]
  numExecutors: 0                 # the controller does not build (05-01)
  mode: EXCLUSIVE
  slaveAgentPort: -1              # TCP agent port closed: WebSocket only (05-02)
  markupFormatter:
    safeHtml:
      disableSyntaxHighlighting: false
  crumbIssuer:
    standard:
      excludeClientIPFromCrumb: false
  remotingSecurity:
    enabled: true                 # agent → controller protection

  securityRealm:
    local:
      allowsSignup: false
      users:
        - id: "laura"
          name: "Laura Martin"
          password: "${LAURA_PASSWORD}"
        - id: "diego"
          name: "Diego (fictitious)"
          password: "${DIEGO_PASSWORD}"
        - id: "marta"
          name: "Marta (fictitious)"
          password: "${MARTA_PASSWORD}"
        - id: "metrics"
          name: "Prometheus technical user"
          password: "${METRICS_PASSWORD}"
  # When TecnoShop connects its SSO (05-02), the block above is replaced by something like this
  # (OpenId Connect Authentication plugin; the exact keys depend on its version):
  #  securityRealm:
  #    oic:
  #      clientId: "jenkins"
  #      clientSecret: "${OIDC_CLIENT_SECRET}"
  #      serverConfiguration:
  #        wellKnown:
  #          wellKnownOpenIDConfigurationUrl: "https://sso.tecnoshop.local/realms/tecnoshop/.well-known/openid-configuration"
  #      groupsFieldName: "groups"

  authorizationStrategy:
    roleBased:
      roles:
        global:
          - name: "admin"
            description: "Platform: full administration"
            permissions:
              - "Overall/Administer"
            entries:
              - user: "laura"
          - name: "user"
            description: "Entry point: view the Dashboard"
            permissions:
              - "Overall/Read"
              - "View/Read"
            entries:
              - group: "authenticated"
          - name: "metrics"
            description: "Metrics read access for Prometheus (05-05)"
            permissions:
              - "Overall/Read"
              - "Metrics/View"
            entries:
              - user: "metrics"
        items:
          - name: "orders-developer"
            pattern: "orders-.*"
            permissions:
              - "Job/Read"
              - "Job/Build"
              - "Job/Cancel"
              - "Job/Workspace"
            entries:
              - user: "diego"
              - group: "developers"
          - name: "catalog-developer"
            pattern: "catalog-.*"
            permissions:
              - "Job/Read"
              - "Job/Build"
              - "Job/Cancel"
              - "Job/Workspace"
            entries:
              - group: "developers"
          - name: "qa"
            pattern: "(orders|catalog)-.*"
            permissions:
              - "Job/Read"
              - "Job/Build"
            entries:
              - user: "marta"

  globalNodeProperties:
    - envVars:
        env:
          - key: "TECNOSHOP_REGISTRY"
            value: "registry.tecnoshop.local"
          - key: "TECNOSHOP_INSECURE_REGISTRY"
            value: "${TECNOSHOP_INSECURE_REGISTRY:-false}"   # true only in the lab (08-02)

  nodes:
    - permanent:
        name: "linux-agent-01"
        labelString: "linux docker"
        numExecutors: 2
        remoteFS: "/home/jenkins/agent"
        mode: NORMAL              # "Use this node as much as possible"
        launcher:
          inbound:
            webSocket: true
        nodeProperties:
          - envVars:
              env:
                - key: "MAVEN_OPTS"
                  value: "-Dmaven.repo.local=/home/jenkins/agent/.m2/repository"
                - key: "GRADLE_USER_HOME"
                  value: "/home/jenkins/agent/.gradle"
                - key: "npm_config_cache"
                  value: "/home/jenkins/agent/.npm"

  clouds:
    - kubernetes:
        name: "kubernetes"
        serverUrl: "${K8S_API_URL}"
        serverCertificate: "${readFile:/run/secrets/K8S_CA}"
        credentialsId: "k8s-jenkins-agents"
        namespace: "jenkins-agents"
        jenkinsUrl: "${AGENTS_JENKINS_URL}"
        webSocket: true
        containerCapStr: "4"
        podLabels:
          - key: "jenkins"
            value: "agent"
        podRetention: "never"

The most important points of this block:

  • systemMessage: the notice appears at the top of the Dashboard. Reminding everyone that the interface is not the source of truth avoids half the problems.
  • slaveAgentPort: -1: the key name keeps Jenkins' historical terminology (as happens in other parts of the code); the value -1 disables the TCP port for inbound agents.
  • securityRealm.local.users: the users of Jenkins' own user database, with the password taken from a secret. Heads-up: when it is applied, JCasC sets that password, so if Diego changes his in the interface, he will get the old one back on the next reload. That is another reason for SSO, which is ready as a comment: with it, Jenkins passwords disappear and the developers group becomes effective.
  • roleBased: the roles from 05-02, identical. The format of the assignments (entries with user/group) is the one used by current versions of the Role-based Authorization Strategy plugin; older ones used assignments with a list of names. The export will tell you which one yours uses.
  • ${TECNOSHOP_INSECURE_REGISTRY:-false}: the :- syntax provides a default value if the variable does not exist. The same file works for the lab (which sets the variable to true) and for TecnoShop.
  • nodes: linux-agent-01 with its labels, executors and node variables. The inbound launcher with webSocket: true is the one used by current versions (in older ones, jnlp). An important detail: the agent's connection secret is computed from the controller's internal key; if you rebuild Jenkins from scratch, it changes, and LINUX_AGENT_01_SECRET has to be updated in the .env (you can see it in Nodes → linux-agent-01).
  • clouds: the cloud from 08-02. The API URL and the Jenkins URL as seen from the pods are variables: they are not secrets, but they differ between the lab and TecnoShop. ${readFile:...} reads the contents of a file (here, the certificate of the cluster CA).

casc/jenkins.yaml: Credentials with No Secrets in Git

credentials:
  system:
    domainCredentials:
      - credentials:
          - gitHubApp:
              id: "github-tecnoshop"
              description: "GitHub App tecnoshop-jenkins (Contents/Metadata/PR read; Statuses/Checks write). Owner: Laura."
              appID: "${GITHUB_APP_ID}"
              privateKey: "${readFile:/run/secrets/GITHUB_APP_KEY}"
          - string:
              scope: GLOBAL
              id: "github-webhook-secret"
              description: "Signing secret for the GitHub webhooks (06-01)"
              secret: "${GITHUB_WEBHOOK_SECRET}"
          - usernamePassword:
              scope: GLOBAL
              id: "nexus-deployer"
              description: "Nexus: jenkins-deployer user (publishes jars and npm; no delete). Owner: Laura."
              username: "jenkins-deployer"
              password: "${NEXUS_DEPLOYER_PASSWORD}"
          - usernamePassword:
              scope: GLOBAL
              id: "registry-tecnoshop"
              description: "Registry registry.tecnoshop.local (push to docker-tecnoshop, no delete). Owner: Laura."
              username: "jenkins-push"
              password: "${REGISTRY_PUSH_PASSWORD}"
          - string:
              scope: GLOBAL
              id: "sonar-token"
              description: "SonarQube analysis token (06-04)"
              secret: "${SONAR_TOKEN}"
          - string:
              scope: GLOBAL
              id: "sonar-webhook-secret"
              description: "Secret for the SonarQube webhook to Jenkins (06-04)"
              secret: "${SONAR_WEBHOOK_SECRET}"
          - string:
              scope: GLOBAL
              id: "slack-token"
              description: "Bot token for the TecnoShop Slack app (06-07)"
              secret: "${SLACK_TOKEN}"
          - string:
              scope: GLOBAL
              id: "nvd-api-key"
              description: "NVD API key for Dependency-Check (07-05)"
              secret: "${NVD_API_KEY}"
          - string:
              scope: GLOBAL
              id: "k8s-jenkins-agents"
              description: "Token of the jenkins ServiceAccount (namespace jenkins-agents). Only creates build pods."
              secret: "${K8S_JENKINS_TOKEN}"
          - basicSSHUserPrivateKey:
              scope: GLOBAL
              id: "ssh-dev"
              description: "SSH for deployments to dev-01 (06-06). Owner: Laura."
              username: "deploy"
              privateKeySource:
                directEntry:
                  privateKey: "${readFile:/run/secrets/SSH_DEV_KEY}"
  • No secret value is in the file: only the names of the secrets. Anyone on the team can read the file without risk; what grants access is having the secrets, which live somewhere else.
  • The IDs are the usual ones, the ones the Jenkinsfiles use: no pipeline notices the change.
  • gitHubApp: the credential from 06-01. The private key must be in PKCS#8 format, as you already converted it back then.

Where the ${...} Values Come From

JCasC resolves each ${NAME} by querying its secret sources, in order:

Source How it is used Where it fits
Environment variables ${SONAR_TOKEN} looks for the SONAR_TOKEN variable Non-secret values (URLs) or simple environments
Files in /run/secrets/ (Docker secrets, and also Kubernetes Secrets mounted as files) ${SONAR_TOKEN} reads /run/secrets/SONAR_TOKEN TecnoShop's method: Compose and Kubernetes mount each secret as a file
Secret manager plugins (HashiCorp Vault, AWS Secrets Manager, Azure Key Vault...) The same, with the corresponding plugin When TecnoShop adopts a centralized manager
Functions ${readFile:/path}, ${base64:...}, ${fileBase64:/path} Multi-line contents, such as private keys

And two writing rules:

  • If a value must literally contain ${...} (for example, a Maven or Groovy variable inside a text), it is escaped as ^${...}: JCasC leaves it as ${...} without trying to resolve it.
  • A secret that cannot be found makes startup fail (or is left empty, depending on the version and configuration): better a Jenkins that does not start than one that starts with empty credentials without warning.

What JCasC Does Not Cover: Folder Credentials

JCasC describes system credentials. Folder credentials (ssh-staging and ssh-production in orders-delivery, kubeconfig-tecnoshop in the orders-api multibranch folder) belong to the items, not to the controller. They can be created from Job DSL with its dynamic API, but that forces you to pass secrets to the seed job. TecnoShop's decision: they are created by hand following a procedure written in the repository's README.md (which ID, which description, where each value comes from), they are protected by the backups from 05-03, and they will move to a secret manager once there is one. Knowing exactly what is left outside the code is part of doing it right.

casc/jenkins.yaml: Integrations, Tools and Managed Files

security:
  globalJobDslSecurityConfiguration:
    useScriptSecurity: false      # see "The seed job and Job DSL security"
  gitHostKeyVerificationConfiguration:
    sshHostKeyVerificationStrategy: "knownHostsFileVerificationStrategy"

unclassified:
  location:
    url: "${PUBLIC_JENKINS_URL}"
    adminAddress: "[email protected]"

  globalLibraries:
    libraries:
      - name: "tecnoshop-lib"
        defaultVersion: "main"
        implicit: false           # never "Load implicitly" (04-06)
        allowVersionOverride: true
        includeInChangesets: false
        retriever:
          modernSCM:
            scm:
              github:
                credentialsId: "github-tecnoshop"
                repoOwner: "tecnoshop"
                repository: "jenkins-shared-lib"
                repositoryUrl: "https://github.com/tecnoshop/jenkins-shared-lib"
                configuredByUrl: true
                traits:
                  - gitHubBranchDiscovery:
                      strategyId: 1
                  - gitHubTagDiscovery

  sonarGlobalConfiguration:
    buildWrapperEnabled: true
    installations:
      - name: "sonar-tecnoshop"
        serverUrl: "${SONAR_URL}"
        credentialsId: "sonar-token"
        webhookSecretId: "sonar-webhook-secret"

  slackNotifier:
    teamDomain: "tecnoshop"
    tokenCredentialId: "slack-token"
    botUser: true
    room: "#ci-orders"

  gitHubPluginConfig:
    hookSecretConfigs:
      - credentialsId: "github-webhook-secret"

  globalConfigFiles:
    configs:
      - mavenSettings:
          id: "maven-settings-tecnoshop"
          name: "TecnoShop Maven settings (Nexus mirror)"
          comment: "Managed from tecnoshop/jenkins-config"
          isReplaceAll: true
          content: |
            <?xml version="1.0" encoding="UTF-8"?>
            <settings xmlns="http://maven.apache.org/SETTINGS/1.2.0">
                <interactiveMode>false</interactiveMode>
                <mirrors>
                    <mirror>
                        <id>nexus-tecnoshop</id>
                        <mirrorOf>*</mirrorOf>
                        <url>${NEXUS_MAVEN_PUBLIC}</url>
                    </mirror>
                </mirrors>
            </settings>
      - mavenSettings:
          id: "maven-settings-tecnoshop-publish"
          name: "TecnoShop Maven settings for publishing to Nexus"
          comment: "Only for the Publish stage. Managed from tecnoshop/jenkins-config"
          isReplaceAll: true
          serverCredentialMappings:
            - serverId: "nexus-tecnoshop"
              credentialsId: "nexus-deployer"
          content: |
            <?xml version="1.0" encoding="UTF-8"?>
            <settings xmlns="http://maven.apache.org/SETTINGS/1.2.0">
                <interactiveMode>false</interactiveMode>
                <mirrors>
                    <mirror>
                        <id>nexus-tecnoshop</id>
                        <mirrorOf>*</mirrorOf>
                        <url>${NEXUS_MAVEN_PUBLIC}</url>
                    </mirror>
                </mirrors>
            </settings>
      # npmrc-tecnoshop (06-02) is declared the same way, with the npm file type
      # your export shows; its content: registry=${NEXUS_NPM_PUBLIC}

tool:
  nodejs:
    installations:
      - name: "node-22"           # only for the SonarQube analysis of catalog-web (08-01)
        properties:
          - installSource:
              installers:
                - nodeJSInstaller:
                    id: "22.x.y"  # exact validated version
  sonarRunnerInstallation:
    installations:
      - name: "sonar-scanner"
        properties:
          - installSource:
              installers:
                - sonarRunnerInstaller:
                    id: "<version>"
  • globalLibraries: the library from 04-06 with its decisions (implicit: false, default version main, requesting @v1.7.0 is allowed). The branch and tag discovery traits make it possible to resolve both main and the vX.Y.Z tags.
  • sonarGlobalConfiguration: the sonar-tecnoshop server with its token and the webhook secret. ${SONAR_URL} is http://sonarqube:9000 in the lab and https://sonar.tecnoshop.local at TecnoShop.
  • globalConfigFiles: the managed files of the Config File Provider plugin. Notice ${NEXUS_MAVEN_PUBLIC}: the mirror that 06-05 warned was duplicated in two files now comes from a single variable. serverCredentialMappings maps the nexus-tecnoshop <server> to the credential, just as in the interface. If the content of a settings file ever needs a Maven expression such as ${env.HOME}, write it as ^${env.HOME}.
  • tool: only what is left in Tools: node-22 (the NodeJS plugin is kept for the catalog-web scanner) and sonar-scanner. The installer keys (nodeJSInstaller, sonarRunnerInstaller) are the ones the export shows; the id values are the exact versions.
  • The rest of the plugin configuration (Email Extension, Prometheus, Audit Trail, Lockable Resources with env-staging and env-production...) is added the same way: export, find its section, keep what is not a default.

The Image and Startup: No Setup Wizard, and CASC_JENKINS_CONFIG

The controller Dockerfile gains three lines:

# TecnoShop Jenkins controller image: pinned plugins + configuration as code
FROM jenkins/jenkins:2.xxx.y-lts-jdk21

ENV JAVA_OPTS="-Djenkins.install.runSetupWizard=false"
ENV CASC_JENKINS_CONFIG=/usr/share/jenkins/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/casc/
  • -Djenkins.install.runSetupWizard=false: disables the setup wizard from 01-02 (initial password, suggested plugins, first user). With JCasC, all of that is already described; a pending wizard would leave Jenkins half configured. If you define your own JAVA_OPTS in Compose or Helm (for example, for the heap in 08-05), it replaces the image's: include this option too.
  • CASC_JENKINS_CONFIG points to a directory: all its YAML files are loaded. If the file grows, you can split it (security.yaml, credentials.yaml...), as long as no two files define the same key.
  • The configuration goes inside the image: the image tag identifies the plugins and the configuration. To iterate quickly in the lab, you can mount ./casc on top as a read-only volume and reload without rebuilding.

The service in docker-compose.yml, with the secrets as files:

  jenkins-controller:
    build: .
    image: tecnoshop/jenkins-controller:2.xxx.y-3
    container_name: jenkins-controller
    restart: unless-stopped
    environment:
      PLUGINS_FORCE_UPGRADE: "true"
      TRY_UPGRADE_IF_NO_MARKER: "true"
      PUBLIC_JENKINS_URL: "http://localhost:8080/"
      AGENTS_JENKINS_URL: "http://jenkins-controller:8080/"
      K8S_API_URL: "https://tecnoshop-control-plane:6443"
      SONAR_URL: "http://sonarqube:9000"
      NEXUS_MAVEN_PUBLIC: "http://nexus:8081/repository/maven-public/"
      NEXUS_NPM_PUBLIC: "http://nexus:8081/repository/npm-public/"
      TECNOSHOP_INSECURE_REGISTRY: "true"
      GITHUB_APP_ID: "123456"
    secrets:
      - LAURA_PASSWORD
      - DIEGO_PASSWORD
      - MARTA_PASSWORD
      - METRICS_PASSWORD
      - GITHUB_APP_KEY
      - GITHUB_WEBHOOK_SECRET
      - NEXUS_DEPLOYER_PASSWORD
      - REGISTRY_PUSH_PASSWORD
      - SONAR_TOKEN
      - SONAR_WEBHOOK_SECRET
      - SLACK_TOKEN
      - NVD_API_KEY
      - K8S_JENKINS_TOKEN
      - K8S_CA
      - SSH_DEV_KEY
    ports:
      - "8080:8080"
    volumes:
      - jenkins_home:/var/jenkins_home
    networks:
      - default
      - kind

secrets:
  LAURA_PASSWORD:
    file: ./secrets/LAURA_PASSWORD
  DIEGO_PASSWORD:
    file: ./secrets/DIEGO_PASSWORD
  # ... one per secret, all in ./secrets/ (in .gitignore, permissions 600)
  • environment: only non-secret values that change between environments (URLs, the public ID of the GitHub App).
  • secrets: Compose mounts each file from ./secrets/ at /run/secrets/<NAME> inside the container, which is where JCasC looks for them. They do not show up in docker inspect or in the process environment variables.
  • ./secrets/ is in .gitignore. In the lab you fill it in yourself; at TecnoShop, the files are generated by the deployment system from the secret manager or, on Kubernetes, they are Secrets mounted as a volume (the Helm chart from 08-02 supports mounting Secrets for JCasC).

Changing the Configuration: Apply, Reload and Keep Your Hands Off the Interface

The lifecycle of a configuration change is that of any code:

  1. A branch in jenkins-config, a change to casc/jenkins.yaml, a PR.
  2. The repository's CI validates the YAML and starts a test Jenkins with it (section 13).
  3. Review and merge.
  4. Apply: a new image with the configuration and recreating the container or, for configuration-only changes, a reload.

Ways to reload without restarting:

Method How
Interface Manage Jenkins → Configuration as Code → Reload existing configuration
CLI java -jar jenkins-cli.jar ... reload-jcasc-configuration (08-04)
HTTP POST /configuration-as-code/reload with an administrator user and their API token
Kubernetes The Helm chart includes a sidecar container that reloads when the JCasC ConfigMap changes

The team rule changes: nothing that JCasC manages is saved in Manage Jenkins on the production controller. If something is changed by hand in an emergency, it is carried over to the YAML that same day; otherwise, the next reload will undo it. Audit Trail (05-02) helps detect those changes.

Job DSL: Jobs as Code

The Job DSL plugin lets you describe jobs in a Groovy-based language. A Job DSL script is not a pipeline: it does not run on every build, but when it is processed by a special job, the seed job, which creates or updates the jobs it describes.

The API reference is in your own Jenkins: /plugin/job-dsl/api-viewer/index.html. It shows every method, including those contributed by your plugins (the so-called dynamic API), with their parameters. It is the reliable way to find out how each option is written in your version.

jobs/multibranch.groovy

// TecnoShop multibranch jobs (GitHub Branch Source). Processed by seed-jobs: do not edit these jobs by hand.

def multibranchTecnoShop(Map repo) {
    multibranchPipelineJob(repo.name) {
        description(repo.description)
        branchSources {
            branchSource {
                source {
                    github {
                        id("${repo.name}-github")   // STABLE: if it changes, Jenkins sees it as a different source
                        credentialsId('github-tecnoshop')
                        repoOwner('tecnoshop')
                        repository(repo.name)
                        repositoryUrl("https://github.com/tecnoshop/${repo.name}")
                        configuredByUrl(true)
                        traits {
                            gitHubBranchDiscovery {
                                strategyId(1)             // exclude branches that have an open PR
                            }
                            gitHubPullRequestDiscovery {
                                strategyId(1)             // PR merged with its target
                            }
                            gitHubForkDiscovery {
                                strategyId(1)
                                trust {
                                    gitHubTrustPermissions()   // authors with Admin or Write permission
                                }
                            }
                            if (repo.tags) {
                                gitHubTagDiscovery()
                            }
                        }
                    }
                }
            }
        }
        factory {
            workflowBranchProjectFactory {
                scriptPath(repo.jenkinsfile ?: 'Jenkinsfile')
            }
        }
        orphanedItemStrategy {
            discardOldItems {
                daysToKeep(7)
                numToKeep(20)
            }
        }
        triggers {
            periodicFolderTrigger {
                interval('1d')                    // safety net; webhooks are the normal path (06-01)
            }
        }
    }
}

[
    [name: 'orders-api',     tags: true,
     description: 'CI for orders-api (Java 21, Spring Boot). Pipeline: the repository Jenkinsfile.'],
    [name: 'catalog-web',    tags: false,
     description: 'CI for catalog-web (Node.js). Pipeline: the repository Jenkinsfile.'],
    [name: 'jenkins-config', tags: false, jenkinsfile: 'ci/Jenkinsfile',
     description: 'CI for the Jenkins configuration (image, JCasC, Job DSL). Platform team only.'],
].each { repo ->
    multibranchTecnoShop(repo)
}

What it describes and why it is written this way:

  • multibranchPipelineJob: the same job you created in 04-05, with the configuration from 06-01 (a daily scan as a fallback for the webhooks) and from 07-02 (tags in orders-api).
  • A function and a list: the three multibranch jobs share configuration; a new project is one line. It is the same idea as tecnoshop-lib, applied to jobs.
  • A stable id(...): Jenkins identifies each source by its id. Without it, the plugin generates a random one on every run of the seed, Jenkins thinks the source has changed, and it rediscovers and builds every branch again.
  • strategyId: the numbers encode the interface options. In gitHubBranchDiscovery, 1 = exclude branches with a PR, 2 = only branches with a PR, 3 = all; for PRs, 1 = merged, 2 = the PR head, 3 = both.
  • jenkins-config describes itself: its own multibranch job, with the Jenkinsfile in ci/. Its name does not match the item role patterns, so only the platform team can see it.
  • The clone options from 06-01 (Fetch tags, a 10-minute timeout) are added inside traits with the name the API viewer shows for Advanced clone behaviours.

jobs/orders-delivery.groovy

// orders-api delivery folder and its pipelines (07-03, 07-04).
// Folder credentials (ssh-staging, ssh-production) are NOT managed here: see README.md.

folder('orders-delivery') {
    description('Delivery (CD) pipelines for orders-api. Staging and production credentials. Owner: Laura.')
}

def pipelineFromOrdersApi(String jobName, String descriptionText, String scriptFile, Closure jobParameters) {
    pipelineJob("orders-delivery/${jobName}") {
        description(descriptionText)
        parameters(jobParameters)              // mirrors the parameters of the Jenkinsfile (see below)
        definition {
            cpsScm {
                scm {
                    git {
                        remote {
                            url('https://github.com/tecnoshop/orders-api.git')
                            credentials('github-tecnoshop')
                        }
                        branch('*/main')
                    }
                }
                scriptPath(scriptFile)
                lightweight(true)
            }
        }
    }
}

pipelineFromOrdersApi('orders-api-cd',
        'CD for orders-api: Nexus release → staging → acceptance → approval → production.',
        'ci/Jenkinsfile.cd') {
    stringParam {
        name('VERSION'); defaultValue(''); trim(true)
        description('Release X.Y.Z published in maven-releases (e.g. 1.1.0). Never a SNAPSHOT.')
    }
    stringParam {
        name('SHA256'); defaultValue(''); trim(true)
        description('SHA-256 of the jar tested in the tag build. Filled in by CI; empty when triggered by hand.')
    }
}

pipelineFromOrdersApi('orders-api-rollback',
        'Manual rollback of orders-api in production (07-04).',
        'ci/Jenkinsfile.rollback') {
    stringParam {
        name('TARGET_VERSION'); defaultValue(''); trim(true)
        description('Empty: the previous version on each node. Or a version present in releases/ on the servers (e.g. 1.1.0).')
    }
    stringParam {
        name('REASON'); defaultValue(''); trim(true)
        description('Reason for the rollback and incident reference.')
    }
}
  • folder and pipelineJob: the folder and the two jobs from 07-03 and 07-04, with Pipeline script from SCM from main and lightweight checkout.
  • Why repeat the parameters? The Jenkinsfile declares them and Jenkins stores them in the job configuration on the first build. If the seed regenerated the job without them, Job DSL would detect a difference and delete them, Build with Parameters would disappear until the next build, and triggering from CI (build job: ... parameters: ...) would fail in the meantime. Declaring them identically in both places keeps the configuration stable. The Jenkinsfile is still the reference: if they change there, they are changed here in the same PR.
  • stringParam { name(...); ... trim(true) } is the dynamic API form, which supports every option of the parameter (the short form stringParam('VERSION', '', '...') has no trim).

jobs/views.groovy

listView('TecnoShop') {
    description('TecnoShop jobs (02-01)')
    recurse(true)
    jobs {
        regex('(orders|catalog)-.*')
    }
    columns {
        status()
        weather()
        name()
        lastSuccess()
        lastFailure()
        lastDuration()
        buildButton()
    }
}

The seed-jobs Seed Job and Job DSL Security

Creating the Seed from JCasC

Who creates the job that creates the jobs? JCasC, with its jobs root, which runs Job DSL scripts when the configuration is applied. At the end of casc/jenkins.yaml:

jobs:
  - script: |
      job('seed-jobs') {
          description('Creates and updates the TecnoShop jobs from tecnoshop/jenkins-config (jobs/). Managed by JCasC.')
          label('linux')
          logRotator {
              numToKeep(30)
          }
          scm {
              git {
                  remote {
                      url('https://github.com/tecnoshop/jenkins-config.git')
                      credentials('github-tecnoshop')
                  }
                  branch('*/main')
              }
          }
          triggers {
              scm('H/15 * * * *')
          }
          steps {
              jobDsl {
                  targets('jobs/**/*.groovy')
                  removedJobAction('DISABLE')
                  removedViewAction('DELETE')
                  lookupStrategy('JENKINS_ROOT')
                  failOnMissingPlugin(true)
              }
          }
      }
      queue('seed-jobs')
  • job('seed-jobs'): a Freestyle job with the Process Job DSLs step (jobDsl), which reads the scripts in the repository's jobs/.
  • label('linux'): the repository checkout happens on the agent (the controller has 0 executors); the scripts are processed on the controller.
  • scm('H/15 * * * *'): checks every 15 minutes whether there are changes on main. You can replace it with githubPush() and a repository webhook, as in 06-01.
  • removedJobAction('DISABLE'): if a job stops appearing in the scripts, it is disabled, not deleted. Deleting would wipe its history; it is deleted by hand, deliberately, when it is no longer needed. Views are deleted (they have no history).
  • lookupStrategy('JENKINS_ROOT'): names (orders-delivery/orders-api-cd) are relative to the Jenkins root, not to the seed's folder.
  • failOnMissingPlugin(true): if a script uses a plugin that is not installed, the seed fails instead of ignoring it.
  • queue('seed-jobs'): queues a run of the seed every time the configuration is applied. On a freshly created Jenkins, the jobs appear on their own.
  • script: |: the YAML literal block keeps the line breaks. If the script contained Groovy ${...}, it would have to be written as ^${...} so that JCasC does not try to resolve it.

Job DSL Script Security

A Job DSL script is Groovy code that runs on the controller with the power to create and modify any job. By default, the Enable script security for Job DSL scripts option (Manage Jenkins → Security) is enabled, and then:

  • Scripts processed by a seed run in the sandbox only if the seed runs with the identity of a specific user (with a plugin such as Authorize Project); otherwise, every new version of the script needs approval from an administrator in In-process Script Approval (05-02).
  • With the scripts in Git, every merged PR would mean one more manual approval.

TecnoShop disables the check (useScriptSecurity: false in the security block) and moves the control to where it already is: only the platform team can merge into jenkins-config (protected branch, mandatory review, CODEOWNERS). It is the same logic as with tecnoshop-lib in 04-06: whoever can change that repository effectively has administrator powers over Jenkins, and that is why the repository is protected as such. If other teams in your organization could write Job DSL scripts, keep script security enabled and use the sandbox with a dedicated identity.

Rebuilding Jenkins from Git

flowchart TD
    G1["tecnoshop/jenkins-config"] --> I["Image tecnoshop/jenkins-controller<br/>(Jenkins + plugins.txt + casc/)"]
    S["Secrets (outside Git)<br/>/run/secrets/*"] --> A
    I --> A["Startup: no wizard<br/>JCasC applies casc/jenkins.yaml"]
    A --> C["Security, roles, agent, cloud,<br/>credentials, library, Sonar, Slack, files"]
    A --> SJ["jobs: creates seed-jobs and queues it"]
    SJ --> DSL["seed-jobs processes jobs/*.groovy"]
    DSL --> T["orders-delivery folder, multibranch<br/>orders-api, catalog-web, jenkins-config, view"]
    T --> SC["Repository scans"]
    G2["Jenkinsfile of each repository<br/>+ tecnoshop-lib"] --> SC
    SC --> B["Builds"]
    BK["Backups from 05-03"] -.->|"history, folder credentials,<br/>API tokens, fingerprints"| B

With an empty volume, the image and the secrets, in a few minutes you have a Jenkins with the same security, the same agents and clouds, the same system credentials and the same jobs. What is not rebuilt from Git:

What is missing Why How it is covered
Build history, logs, archived artifacts, test results It is state, not configuration Backups from 05-03
Folder credentials TecnoShop's decision (section 6) The README.md procedure + backups
Users' API tokens (metrics, automation) They are generated in Jenkins and cannot be exported in clear text Regenerate them and update whoever uses them (08-04)
The linux-agent-01 connection secret It depends on the controller's internal key Update the agent's .env
Fingerprints, build numbers State Backups

That is why JCasC complements backups rather than replacing them: the code answers "what Jenkins looks like"; the backups, "what has happened in Jenkins". The 4-hour RTO from 05-03 gets much shorter when the configuration does not need to be restored or redone.

CI for the jenkins-config Repository

A change to the Jenkins configuration is as delicate as a change to the code: a YAML error can leave the controller unable to start. ci/Jenkinsfile:

@Library('[email protected]') _

pipeline {
    agent {
        label 'docker'
    }

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

    environment {
        IMAGE     = 'registry.tecnoshop.local/tecnoshop/jenkins-controller'
        IMAGE_TAG = "candidate-${BUILD_NUMBER}"
    }

    stages {
        stage('Validate YAML') {
            agent {
                docker {
                    image 'python:3.13-slim'
                    reuseNode true
                    args '--network host'
                }
            }
            steps {
                sh '''
                    python -m venv .venv
                    .venv/bin/pip install --quiet --no-cache-dir "yamllint==<version>"
                    .venv/bin/yamllint --strict casc/
                '''
            }
        }

        stage('Secrets') {
            steps {
                scanSecrets()
            }
        }

        stage('Build image') {
            steps {
                script {
                    docker.build("${env.IMAGE}:${env.IMAGE_TAG}", '--pull .')
                }
            }
        }

        stage('Test startup') {
            options {
                timeout(time: 10, unit: 'MINUTES')
            }
            steps {
                script {
                    docker.image("${env.IMAGE}:${env.IMAGE_TAG}").withRun(
                        "-P --env-file ${env.WORKSPACE}/test-secrets/environment.env " +
                        "-v ${env.WORKSPACE}/test-secrets:/run/secrets:ro") { c ->
                        withEnv(["CONTAINER=${c.id}"]) {
                            sh label: 'Wait for Jenkins and check the configuration', script: '''
                                for i in $(seq 1 90); do
                                    docker logs "$CONTAINER" 2>&1 | grep -q "Jenkins is fully up and running" && break
                                    sleep 2
                                done
                                docker logs "$CONTAINER" > startup.log 2>&1
                                if grep -E "ConfiguratorException|Unknown property|SEVERE" startup.log; then
                                    echo "ERROR: the configuration was not applied cleanly"; exit 1
                                fi
                                URL="http://docker-dind:$(docker port "$CONTAINER" 8080/tcp | head -n 1 | sed 's/.*://')"
                                test "$(curl -s -o /dev/null -w '%{http_code}' "$URL/api/json")" = "403"
                                curl -fsS -u "laura:$(cat test-secrets/LAURA_PASSWORD)" "$URL/whoAmI/api/json" | grep -q '"authenticated":true'
                                echo "==> Jenkins starts with the configuration, with no anonymous access and with local login"
                            '''
                        }
                    }
                }
            }
            post {
                always {
                    archiveArtifacts artifacts: 'startup.log', allowEmptyArchive: true
                }
            }
        }

        stage('Publish candidate') {
            when {
                branch 'main'
            }
            steps {
                script {
                    docker.withRegistry('https://registry.tecnoshop.local', 'registry-tecnoshop') {
                        docker.image("${env.IMAGE}:${env.IMAGE_TAG}").push()
                    }
                }
            }
        }
    }

    post {
        always {
            notifyTeam channel: '#ci-platform', email: '[email protected]'
        }
        cleanup {
            cleanWs()
        }
    }
}
  • Validate YAML: yamllint --strict catches syntax and indentation errors (the most common JCasC mistake) in seconds, in a Python container, without installing anything on the agent.
  • Test startup: the most reliable validation of JCasC is to apply it. The candidate image is started with the fake secrets from test-secrets/ (mounted at /run/secrets, as in production; the mount works because the workspace is on the volume shared with docker-dind), and the stage checks that Jenkins finishes starting, that the log has no configuration errors, that an anonymous user gets a 403 and that laura can authenticate with the test password.
  • test-secrets/: throwaway values, different from the real ones and marked as fake (including a private key generated just for this); .gitleaks.toml excludes that directory with a comment that justifies it. environment.env contains the non-secret variables pointing to nonexistent addresses, so that the test Jenkins does not talk to anything real.
  • Publish candidate: only from main, the candidate-N image is pushed to the registry. Laura then tests it on jenkins-test (05-04) with CANDIDATE_IMAGE=localhost:5000/tecnoshop/jenkins-controller:candidate-N docker compose --profile test up -d jenkins-test, and promotes it to the final 2.xxx.y-N tag once she has validated it.
  • Until this job exists, the seed cannot create it: the first startup with JCasC creates it (it is in jobs/multibranch.groovy), and from then on every jenkins-config PR goes through here.

Adopting It Without Surprises

A Jenkins that has been configured by hand for months does not move to code overnight:

  1. Inventory: export the configuration and list every piece (security, nodes, clouds, credentials, libraries, integrations, jobs).
  2. Write the YAML and the scripts piece by piece, starting with the most stable parts (security, library, tools).
  3. Test it on jenkins-test with an empty volume: this checks that the code describes all of Jenkins and does not depend on anything that only exists in the volume.
  4. Test it on jenkins-test with a restored backup: this checks that applying the configuration on top of the real Jenkins does not break anything. Job DSL adopts existing jobs with the same name (they keep their history) and updates their configuration; review the differences in the seed's log.
  5. Maintenance window and rollout to production, with the cold backup from 05-04 as the rollback plan.
  6. From that day on, the interface is read-only for everything that is managed.

Common Mistakes and Tips

  • Copying the complete export into the repository: noise, encrypted secrets from another installation and keys that cannot be applied again. Use it to discover keys, not as a file.
  • Unknown property or No configurator for the following root elements: a mistyped key, one from another version of the plugin, or one from a plugin that is not installed. Check the JCasC documentation of your installation and plugins.txt.
  • A secret in the YAML "just to test": it ends up in the Git history forever. Always use ${...} and files outside the repository; gitleaks in the CI will catch it.
  • Forgetting to escape ${...} in a Maven settings file or in a Job DSL script inside the YAML: JCasC tries to resolve it and fails or leaves it empty. Write ^${...}.
  • Changes in the interface that "disappear": that is JCasC doing its job on reload. Carry the change over to the YAML.
  • Every branch is rebuilt after each seed run: the fixed id(...) is missing from the multibranch source.
  • "Build with Parameters" disappears after running the seed: the Job DSL script does not declare the parameters that the Jenkinsfile declares.
  • removedJobAction('DELETE') for convenience: the day someone deletes a line by mistake, you will lose the job's history. Disable, and delete by hand.
  • Tip: git log -p casc/jenkins.yaml answers "who changed the security, and when?" better than any after-the-fact audit. Write commit messages that explain the why.

Exercises

Exercise 1. Export your Jenkins configuration with View Configuration, find the roleBased, sonarGlobalConfiguration and globalLibraries sections and compare them with the ones in the lesson. Note three differences and explain which ones you would copy and which ones you would not.

Exercise 2. Write the Job DSL block for a new multibranch job, shipments-api (the fictitious service from 04-07), with tags and the Jenkinsfile in the root, and explain what else would have to change in jenkins-config and in the roles for the shipments team to see it.

Exercise 3. Full rebuild: start jenkins-test with the jenkins-config image and an empty volume. List, in order, what happens until orders-api/main runs its first build, and what you have to do by hand for it to really work.

Solutions

Solution 1. Typical differences: (1) the export includes default values (cachingConfiguration, includeInChangesets with its default value, empty lists): they are not copied, unless they are an explicit decision, like implicit: false, which is kept with its comment; (2) in sonarGlobalConfiguration, empty fields such as additionalAnalysisProperties, triggers or mojoVersion: noise; (3) secrets, if they appear, come out encrypted ({AQAAAB...}) or as references to credentials: only credential IDs and ${...} should appear in the versioned YAML. The format of the role assignments may also differ (entries vs. assignments): what your version of the plugin exports is what counts, since that is what it knows how to apply.

Solution 2. One more line in the list in jobs/multibranch.groovy: [name: 'shipments-api', tags: true, description: 'CI for shipments-api. Pipeline: the repository Jenkinsfile.']. In addition: the tecnoshop-jenkins GitHub App must be installed on the tecnoshop/shipments-api repository (or on the whole organization) and the webhook configured; in casc/jenkins.yaml, a shipments-developer item role with the pattern shipments-.* and the same permissions as the other developer roles, assigned to the shipments-developers group (or to specific users until there is SSO), and the qa pattern extended to (orders|catalog|shipments)-.* if Marta should see it; and, if it uses the TecnoShop view, extending its regular expression. All in the same PR, reviewed by the platform team.

Solution 3. (1) The container starts without the wizard; (2) JCasC applies the configuration: users, roles, global properties, the linux-agent-01 node (disconnected), the kubernetes cloud, system credentials, the library, SonarQube, Slack, managed files and tools; (3) the jobs root creates seed-jobs and queues it; (4) the seed waits for a linux agent; (5) by hand: copy the new linux-agent-01 secret into the test agent's .env (it has changed because the internal key is new) and start it; (6) the seed processes jobs/ and creates the orders-delivery folder, the CD and rollback jobs, the three multibranch jobs and the view; (7) each multibranch job scans its repository and triggers the build of main (and of any open PRs); (8) the orders-api/main build requests a pod from the cloud and starts. Also by hand: create the folder credentials (kubeconfig-tecnoshop, ssh-staging, ssh-production) following the README.md, regenerate the API tokens of metrics (and of automation, from the next lesson) and update Prometheus; and accept that there is no history. On a test Jenkins, make sure it cannot deploy to real environments: the test secrets must not be the production ones.

Conclusion

TecnoShop can now answer "what does our Jenkins look like?" with a repository. tecnoshop/jenkins-config contains the controller image (Jenkins and plugins.txt, now with Configuration as Code and Job DSL); casc/jenkins.yaml with the security and roles from 05-02, the agent, the kubernetes cloud, the system credentials with all their secrets outside Git (${...} resolved from /run/secrets/), the tecnoshop-lib library, SonarQube, Slack, the managed files with the mirror in a single variable and the remaining tools; and jobs/ with the multibranch jobs, the orders-delivery folder with its two pipelines and the view, generated by seed-jobs, which JCasC itself creates. You know why the export is for discovering and not for copying, how to reload, why TecnoShop disables Job DSL script security and protects the repository instead, what the code does not cover (history, folder credentials, tokens) and why the backups from 05-03 are still essential. The repository's own CI validates the YAML and starts a test Jenkins with every change. There is one last way of "talking" to Jenkins that goes through neither the interface nor Git: that of the scripts and tools that query its state or trigger builds. You will see it in Automating Jenkins with the REST API and CLI.

© Copyright 2026. All rights reserved