In the previous lesson TecnoShop's builds learned to use containers, but they still depend on a permanent agent: linux-agent-01 has two executors, a shared workspace and a privileged Docker daemon by its side. Kubernetes changes the model: each build gets a new pod, with exactly the containers its Jenkinsfile asks for, created when it starts and destroyed when it finishes, and the capacity comes from the cluster, not from a specific machine. In this lesson you will set up a local cluster with kind, connect Jenkins to it with the Kubernetes plugin (the kubernetes cloud, plus a minimal ServiceAccount and RBAC), write pod templates in the Jenkinsfile, build the orders-api image without a daemon using Kaniko, get to know how the controller is installed with the official Helm chart, and deploy orders-api as a pilot to the tecnoshop-dev namespace, with a rolling update, health probes and kubectl rollout undo as the rollback. By the end you will have the orders-api Jenkinsfile in its end-of-module-8 state.

Kubernetes in Six Concepts

If you are coming from Docker, these are the essential concepts for this lesson:

Concept What it is In this lesson
Pod The smallest unit: one or more containers that share networking (localhost) and volumes, and are scheduled together on a node Each orders-api build is a pod with the jnlp, maven and kaniko containers
Namespace A space that separates resources, permissions and quotas jenkins-agents (the build pods) and tecnoshop-dev (the application)
Deployment Declares "I want N replicas of this pod" and manages updates (rolling update) and their history orders-api in tecnoshop-dev
Service A stable name and IP that spread traffic across the healthy pods orders-api (port 80 → 8081)
ConfigMap / Secret Configuration and secrets injected into pods as files or variables orders-api-config with application-dev.properties
ServiceAccount + RBAC A process's identity before the Kubernetes API and what it is allowed to do (Role + RoleBinding) jenkins creates pods; deploy-orders updates the Deployment

And one tool: kubectl, the command-line client, which reads from a kubeconfig file which cluster to talk to and with which credential.

What Jenkins Gains with Kubernetes and What TecnoShop Decides

Aspect Permanent agent + Docker (08-01) Agents in pods
Isolation between builds Shared workspace and caches; a common daemon A new pod per build; nothing survives except what you deliberately mount
Tools Agent image + stage images The pod's containers, declared in the repository
Capacity The agent's fixed executors The cluster's; with node autoscaling, it grows and shrinks (08-05)
Privileged Docker Required for docker build No: Kaniko builds without a daemon
Startup Immediate (the agent is already there) Tens of seconds (scheduling the pod, pulling images)
Caches The agent's volume They have to be designed (persistent volumes, Nexus)

TecnoShop's decisions for this module:

  • The orders-api CI moves to pods. It is the pilot project; catalog-web and orders-api-cd stay on linux-agent-01.
  • The controller stays where it is, for now (Docker in the lab; a VM at TecnoShop) and connects to the Kubernetes cloud "from outside". Migrating it to the cluster with Helm is planned (section 10), but these are two independent changes and TecnoShop does not want to make them at the same time.
  • The Kubernetes deployment pilot is dev only: staging and production stay on the module 7 VMs, with the jar and the rolling deployment from 07-04.

The Lab: A Local Cluster with kind

There are three common options for running Kubernetes on a laptop:

Tool How it works Pros Cons
kind (Kubernetes in Docker) Each node is a Docker container Lightweight, starts in a minute, attaches to Docker networks: fits the Compose lab Designed for testing; volumes are local to the node
k3d k3s (lightweight Kubernetes) in Docker containers Very lightweight; comes with a built-in ingress and registry The k3s distribution, with some differences from standard Kubernetes
minikube A VM or container with a full cluster Many addons; very well documented Heavier; its network is more separated from Compose

TecnoShop chooses kind: its nodes are containers on a Docker network called kind, which the Compose services (Jenkins, Nexus, the registry) can join. Install it following its official documentation, along with kubectl.

Resources: a kind node takes up little, but each orders-api build will request about 3.5 GB of memory (section 8) and the pilot two replicas of 384 MB. With Jenkins, Nexus and SonarQube running, you will need at least 16 GB of RAM. While you practice, stop what you are not using: docker compose stop grafana prometheus alertmanager staging-01 prod-01 prod-02 lb.

~/tecnoshop-jenkins/lab/kind/cluster.yaml:

kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
name: tecnoshop
nodes:
  - role: control-plane
containerdConfigPatches:
  - |-
    [plugins."io.containerd.grpc.v1.cri".registry]
      config_path = "/etc/containerd/certs.d"
  • name: tecnoshop: the cluster will be called tecnoshop, its node tecnoshop-control-plane and the kubectl context kind-tecnoshop.
  • A single node: enough for the lab.
  • containerdConfigPatches: kind uses containerd to run containers. This line tells it to look for each registry's configuration in /etc/containerd/certs.d/<registry>/hosts.toml, which you will use for the lab's HTTP registry. It is the method from kind's Local Registry guide; if your version uses a different configuration key, follow that guide.
cd ~/tecnoshop-jenkins
kind create cluster --config lab/kind/cluster.yaml
kubectl cluster-info --context kind-tecnoshop
kubectl get nodes

Connecting the Cluster to the Lab

Compose Services on the kind Network

The build pods will need to talk to jenkins-controller (to connect as agents), nexus (dependencies), registry.tecnoshop.local (images), sonarqube (analysis) and dev-01.tecnoshop.local (the deployment to the dev VM). And Jenkins needs to reach the cluster API. The cleanest way is to declare the kind network in docker-compose.yml and attach those services to it:

networks:
  kind:
    external: true       # created by kind; Compose only uses it

services:
  jenkins-controller:
    # ... unchanged ...
    networks:
      - default
      - kind

  nexus:
    # ... unchanged ...
    networks:
      - default
      - kind

  sonarqube:
    # ... unchanged ...
    networks:
      - default
      - kind

  registry:
    # ... unchanged ...
    networks:
      default:
        aliases:
          - registry.tecnoshop.local
      kind:
        aliases:
          - registry.tecnoshop.local

  dev-01:
    # ... unchanged ...
    networks:
      default:
        aliases:
          - dev-01.tecnoshop.local
      kind:
        aliases:
          - dev-01.tecnoshop.local
  • external: true: the network must exist before docker compose up (create the cluster first).
  • When a service declares networks, it no longer joins only the default network: that is why default is listed explicitly.
  • Aliases are declared per network: registry.tecnoshop.local must also resolve on kind.
docker compose up -d jenkins-controller nexus sonarqube registry dev-01
kubectl run dns-test --rm -it --restart=Never --image=busybox:1.36 -- \
  sh -c 'nslookup jenkins-controller; nslookup registry.tecnoshop.local'

The test pod must resolve both names: kind configures the pods' DNS to forward to the Docker DNS of the kind network. If that were not the case in your version, the alternative is hostAliases in the pod with the IPs of those containers (docker inspect), which is less convenient because the IPs change.

The Registry, as Seen from containerd

The kind nodes will pull images from registry.tecnoshop.local over HTTP. Configure it on the node:

docker exec tecnoshop-control-plane mkdir -p /etc/containerd/certs.d/registry.tecnoshop.local
docker exec -i tecnoshop-control-plane sh -c \
  'cat > /etc/containerd/certs.d/registry.tecnoshop.local/hosts.toml' <<'EOF'
server = "http://registry.tecnoshop.local"

[host."http://registry.tecnoshop.local"]
  capabilities = ["pull", "resolve"]
EOF
  • capabilities = ["pull", "resolve"]: the node only pulls; it never pushes images.
  • For the nodes to pull without credentials, check Allow anonymous docker pull on docker-tecnoshop in Nexus (it requires the Docker Bearer Token Realm to be active, as in 06-05). At TecnoShop there is no anonymous access: pods use an imagePullSecret with a read-only user.
  • This configuration lives inside the node container: if you delete and recreate the cluster, repeat it.

Namespaces, ServiceAccounts and Minimal RBAC

~/tecnoshop-jenkins/lab/kind/jenkins-agents.yaml:

apiVersion: v1
kind: Namespace
metadata:
  name: jenkins-agents
  labels:
    pod-security.kubernetes.io/enforce: baseline
    pod-security.kubernetes.io/warn: restricted
---
# Identity that Jenkins (from outside the cluster) uses to create and manage the build pods
apiVersion: v1
kind: ServiceAccount
metadata:
  name: jenkins
  namespace: jenkins-agents
---
# Identity of the build pods: no permissions at all on the API
apiVersion: v1
kind: ServiceAccount
metadata:
  name: jenkins-agent
  namespace: jenkins-agents
automountServiceAccountToken: false
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: jenkins-agents
  namespace: jenkins-agents
rules:
  - apiGroups: [""]
    resources: ["pods"]
    verbs: ["create", "delete", "get", "list", "patch", "update", "watch"]
  - apiGroups: [""]
    resources: ["pods/exec"]
    verbs: ["create", "delete", "get", "list", "patch", "update", "watch"]
  - apiGroups: [""]
    resources: ["pods/log"]
    verbs: ["get", "list", "watch"]
  - apiGroups: [""]
    resources: ["events"]
    verbs: ["watch"]
  - apiGroups: [""]
    resources: ["secrets"]
    verbs: ["get"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: jenkins-agents
  namespace: jenkins-agents
subjects:
  - kind: ServiceAccount
    name: jenkins
    namespace: jenkins-agents
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: jenkins-agents
---
# Long-lived token for the Jenkins credential (rotate it periodically)
apiVersion: v1
kind: Secret
metadata:
  name: jenkins-token
  namespace: jenkins-agents
  annotations:
    kubernetes.io/service-account.name: jenkins
type: kubernetes.io/service-account-token
---
# Shared build cache (Maven repository, Trivy database)
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: cache-ci
  namespace: jenkins-agents
spec:
  accessModes: ["ReadWriteOnce"]
  resources:
    requests:
      storage: 10Gi

Piece by piece:

  • Pod Security Admission: the enforce: baseline label makes the API reject privileged pods, pods with hostPath, hostNetwork or added capabilities, even if a Jenkinsfile asks for them. It is the safety net against a PR that tries to abuse the pod template. warn: restricted warns (without blocking) about what would violate the strictest level. restricted is not enforced because Kaniko needs to run as root inside its container (without privileges or extra capabilities).
  • Two ServiceAccounts: jenkins is the controller's identity before the API; jenkins-agent is that of the build pods, with no permissions and no mounted token. A compromised build cannot even list pods.
  • The Role: exactly what the Kubernetes plugin documents that it needs, and only in jenkins-agents: create, watch and delete pods, run commands in them (pods/exec, which is how sh and container work), read their logs and events, and read secrets (for the imagePullSecrets a pod template may reference). Nothing outside that namespace.
  • The service-account-token Secret: Kubernetes fills it with a long-lived token. It is the simplest approach for a controller outside the cluster; the alternative is short-lived tokens (kubectl create token) renewed by an external process. Rotate the token like any other credential.
  • cache-ci: a 10 GiB persistent volume (in kind, a directory on the node, with the default StorageClass).
kubectl apply -f lab/kind/jenkins-agents.yaml
kubectl -n jenkins-agents get secret jenkins-token -o jsonpath='{.data.token}' | base64 -d; echo
kind get kubeconfig --name tecnoshop --internal | grep server
kubectl config view --raw --minify --context kind-tecnoshop \
  -o jsonpath='{.clusters[0].cluster.certificate-authority-data}' | base64 -d > ca-tecnoshop.crt
  • The first command prints the token: copy it for the credential and do not leave it in your history or in files.
  • --internal: the API address from the kind network: https://tecnoshop-control-plane:6443.
  • ca-tecnoshop.crt: the cluster's certificate authority certificate, so that Jenkins can verify it is talking to the right API.

In Jenkins, Manage Jenkins → Credentials → Global → Add Credentials: Secret text, ID k8s-jenkins-agents, the token and the description Token of the jenkins ServiceAccount (namespace jenkins-agents) in the tecnoshop cluster. Only creates build pods. Owner: Laura.

The Kubernetes Plugin and the kubernetes Cloud

Install the Kubernetes plugin (ID kubernetes) using the procedure from 05-04. Then go to Manage Jenkins → Clouds → New cloud, name kubernetes, type Kubernetes:

Field Lab TecnoShop What for
Kubernetes URL https://tecnoshop-control-plane:6443 The API URL of the CI cluster Where to create the pods
Kubernetes server certificate key Contents of ca-tecnoshop.crt The cluster CA Verify the API (never check Disable https certificate check)
Kubernetes Namespace jenkins-agents jenkins-agents Where the pods are created
Credentials k8s-jenkins-agents Same The identity of the jenkins ServiceAccount
WebSocket Checked Checked Agents connect over the HTTP port, like linux-agent-01; port 50000 has been closed since 05-02
Jenkins URL http://jenkins-controller:8080/ https://jenkins.tecnoshop.local/ The controller URL as seen from the pods
Pod Labels jenkins=agent Same Kubernetes label on every build pod (useful for network policies and for finding them)
Concurrency Limit (in some versions, Container Cap) 4 Based on the cluster's capacity Maximum number of pods from this cloud at once
Pod Retention Never Never Delete the pod when it finishes, even if it fails (for debugging, temporarily On Failure)
Seconds to wait for pod to be running 600 300 Maximum time for the pod to start (the first image pull is slow)

Click Test Connection: it should respond with the Kubernetes version. Do not define pod templates in the interface: TecnoShop declares them in each repository.

An interesting security option in the cloud's advanced configuration is Restrict pipeline support to authorized folders: only the folders that explicitly allow it (in their configuration) can use this cloud. Use it if teams with different levels of trust share the same Jenkins.

Pod Templates in the Jenkinsfile

A practice Pipeline job, lab-k8s:

pipeline {
    agent {
        kubernetes {
            cloud 'kubernetes'
            defaultContainer 'maven'
            yaml '''
apiVersion: v1
kind: Pod
spec:
  serviceAccountName: jenkins-agent
  automountServiceAccountToken: false
  containers:
    - name: maven
      image: maven:3.9-eclipse-temurin-21
      command: ["sleep"]
      args: ["9999999"]
      resources:
        requests:
          cpu: 500m
          memory: 1Gi
        limits:
          memory: 1536Mi
'''
        }
    }
    stages {
        stage('Where am I?') {
            steps {
                sh 'echo "maven container in pod $(hostname)"; java -version 2>&1 | head -n 1'
                container('jnlp') {
                    sh 'echo "Agent: $NODE_NAME"; ls /home/jenkins/agent'
                }
            }
        }
    }
}
  • agent { kubernetes { ... } }: for this build, Jenkins asks the cloud for a pod with this specification. It shows up in Nodes as an agent with a generated name (lab-k8s-1-abcde-xyz) while the build lasts, and disappears afterwards.
  • yaml '''...''': the pod specification in Kubernetes YAML. Watch the indentation: it is YAML inside a Groovy string.
  • The jnlp container: the plugin adds it on its own if you do not declare it, with the jenkins/inbound-agent image. It is the agent: the process that connects to the controller over WebSocket and runs the steps. The other containers just "wait" (sleep) for the agent to run commands in them.
  • command: ["sleep"], args: ["9999999"]: without a process that never ends, the maven container would exit right after starting (the Maven image has no service to run). Another common approach is command: ["cat"] with tty: true.
  • defaultContainer 'maven': sh steps run in maven unless told otherwise. Without this line, they would run in jnlp.
  • container('jnlp') { ... }: runs the steps in the block in another container of the same pod. They all share the workspace (an emptyDir volume at /home/jenkins/agent) and the network: a process started in one container is reachable on localhost from the others.
  • serviceAccountName: jenkins-agent and automountServiceAccountToken: false: the pod runs with the identity that has no permissions.

Other options of the directive: yamlFile 'ci/pod-ci.yaml' (the specification in a file in the repository, easier to read), inheritFrom (inherit from a pod template defined in the cloud), namespace, nodeSelector, podRetention, idleMinutes (reuse the pod for a few minutes for consecutive builds, at the cost of losing strict isolation).

orders-api will use yamlFile: the pod is part of the code and is reviewed in PRs. This means a PR can change the pod; the Trust policy from 04-05 decides for which PRs the branch's file is used, and Pod Security Admission blocks the dangerous things (privileges, hostPath) in any case.

Resources, Caches and Pod Security

requests and limits

Field What it means TecnoShop's criterion
requests.cpu / requests.memory What the scheduler reserves on the node for the container What the container uses on a sustained basis
limits.memory Maximum: if exceeded, the container is killed (OOMKilled) Equal to or slightly higher than requests.memory
limits.cpu CPU maximum: if exceeded, the container is throttled Not set for builds: a throttled compilation takes much longer and bothers no one beyond what it reserved

Modern JVMs read the container's memory limit: an -XX:MaxRAMPercentage=50 in Maven leaves the other half for the test JVMs, which Surefire starts separately.

Caches in Ephemeral Pods

As 07-02 anticipated, with ephemeral agents the local Maven repository disappears with each pod and the main cache becomes the Nexus proxy. But there are two downloads that are not worth repeating in every build: the Dependency-Check vulnerability database (it is stored inside the local Maven repository and takes minutes to update) and the Trivy one (hundreds of MB). That is why cache-ci exists:

  • In the lab, a ReadWriteOnce volume works because all the pods go to the same node.
  • In a cluster with several nodes, ReadWriteOnce can only be mounted on one node at a time; the alternatives are ReadWriteMany volumes (NFS, cloud file systems), one cache per node, or centralizing: a shared Dependency-Check database updated by a nightly job, with the builds in no-update mode, and a mirror of the Trivy database. This is part of the optimization in 09-03.
  • Two simultaneous builds writing to the same Maven repository work almost always, but it is not guaranteed; it already happened with two executors on linux-agent-01.

The orders-api ci/pod-ci.yaml File

# CI pod for orders-api: used by the agent directive of the Jenkinsfile (Kubernetes plugin).
apiVersion: v1
kind: Pod
metadata:
  labels:
    tecnoshop/project: orders-api
spec:
  serviceAccountName: jenkins-agent
  automountServiceAccountToken: false
  securityContext:
    runAsUser: 1000
    runAsGroup: 1000
    fsGroup: 1000
  containers:
    # Agent: tecnoshop/linux-agent:3 (gitleaks, Trivy, kubectl, crane, ssh and Java 21)
    - name: jnlp
      image: registry.tecnoshop.local/tecnoshop/linux-agent:3
      env:
        - name: TRIVY_CACHE_DIR
          value: /cache/trivy
      resources:
        requests:
          cpu: 250m
          memory: 512Mi
        limits:
          memory: 1Gi
      volumeMounts:
        - name: cache-ci
          mountPath: /cache
    # Build and tests with the project's Maven Wrapper
    - name: maven
      image: maven:3.9-eclipse-temurin-21
      command: ["sleep"]
      args: ["9999999"]
      env:
        - name: HOME
          value: /home/jenkins/agent
        - name: MAVEN_USER_HOME
          value: /cache/m2
        - name: MAVEN_OPTS
          value: "-Dmaven.repo.local=/cache/m2/repository -XX:MaxRAMPercentage=50"
      resources:
        requests:
          cpu: "1"
          memory: 2Gi
        limits:
          memory: 2Gi
      volumeMounts:
        - name: cache-ci
          mountPath: /cache
    # Image build without a Docker daemon
    - name: kaniko
      image: gcr.io/kaniko-project/executor:<version>-debug
      command: ["sleep"]
      args: ["9999999"]
      securityContext:
        runAsUser: 0
        runAsGroup: 0
      resources:
        requests:
          cpu: 500m
          memory: 1Gi
        limits:
          memory: 2Gi
  volumes:
    - name: cache-ci
      persistentVolumeClaim:
        claimName: cache-ci
  • The pod's securityContext: every container runs with UID 1000 (that of the jenkins user in the agent image), and fsGroup: 1000 makes the volumes writable by that group. Kaniko overrides it with runAsUser: 0: it needs to be root inside its container to rebuild the image's file system; it is not privileged and has no extra capabilities.
  • jnlp with our image: instead of the default image, the agent is tecnoshop/linux-agent:3, the same one you know with two more tools (next section). This way gitleaks, Trivy, kubectl and ssh are available in container('jnlp') without additional third-party containers.
  • maven: HOME in the workspace (UID 1000 has no home directory in this image) and the Maven cache in /cache/m2. These variables replace the MAVEN_OPTS node variable of linux-agent-01: pods do not have node properties.
  • Total requested per build: 1.75 CPUs and 3.5 GiB. That is what the scheduler needs to find free on a node to start the pod.

Building Images Without a Daemon: Kaniko and tecnoshop-lib v1.7.0

There is no Docker daemon in a pod (and we do not want one: it would need privileges). Kaniko builds an image from a Dockerfile by running each instruction inside its own container, without a daemon. A timely warning: Google archived the original Kaniko repository in 2025; there are community-maintained forks (such as Chainguard's) and alternatives such as BuildKit in rootless mode or Buildah. Before adopting it in production, check which variant is maintained and use its image. The -debug variant includes a shell (busybox), which is essential for container('kaniko') { sh ... } to work.

The flow is the same as with Docker (build → scan → publish only when appropriate), with different tools:

flowchart LR
    J["target/orders-api-X.jar<br/>Dockerfile"] --> K["kaniko<br/>--no-push --tar-path image.tar"]
    K --> T["jnlp: trivy image --input image.tar<br/>+ SBOM image-bom.json"]
    T -->|"main or tag, after Quality Gate"| C["jnlp: crane push image.tar<br/>registry.tecnoshop.local/orders-api:IMAGE_TAG"]
    C --> D["digest → IMAGE_DIGEST<br/>build-info.txt"]

Kaniko can push the image itself, but then it would be pushed before the scan. With --no-push --tar-path, the image is left in a file; Trivy scans it, and only afterwards does crane (from go-containerregistry, a small tool for working with registries) push it. No unscanned image reaches the registry.

tecnoshop/linux-agent:3

A block with kubectl and crane is added to the agent Dockerfile, verified the same way as gitleaks and Trivy:

ARG KUBECTL_VERSION=vX.Y.Z
ARG KUBECTL_SHA256=replace-with-the-contents-of-kubectl.sha256
ARG CRANE_VERSION=X.Y.Z
ARG CRANE_SHA256=replace-with-the-sha256-of-go-containerregistry_Linux_x86_64.tar.gz

RUN set -eu; \
    cd /tmp; \
    curl -fsSLo kubectl "https://dl.k8s.io/release/${KUBECTL_VERSION}/bin/linux/amd64/kubectl"; \
    echo "${KUBECTL_SHA256}  kubectl" | sha256sum -c -; \
    install -m 0755 kubectl /usr/local/bin/kubectl; \
    curl -fsSLo crane.tar.gz \
      "https://github.com/google/go-containerregistry/releases/download/v${CRANE_VERSION}/go-containerregistry_Linux_x86_64.tar.gz"; \
    echo "${CRANE_SHA256}  crane.tar.gz" | sha256sum -c -; \
    tar -xzf crane.tar.gz crane; install -m 0755 crane /usr/local/bin/crane; \
    rm -f /tmp/kubectl /tmp/crane*; \
    kubectl version --client; crane version
  • The Kubernetes project publishes each binary's checksum alongside it (kubectl.sha256); go-containerregistry publishes a checksums.txt with each release.
  • Keep the kubectl version within the cluster's minor version, or one minor version away, which is the supported compatibility range.

Build it, tag it :3 and publish it as in 08-01: docker compose build linux-agent-01, docker tag tecnoshop/linux-agent:3 localhost:5000/tecnoshop/linux-agent:3 and docker push. linux-agent-01 can move to :3 as well: it is the same image with more tools.

What Is New in the Library

buildImage and publishImage accept an engine parameter. With engine: 'docker' (the default) they behave exactly as in v1.6.0. With engine: 'kaniko', the core fragment of vars/buildImage.groovy is:

    if ((config.engine ?: 'docker') == 'kaniko') {
        // Convention: the pod has a 'kaniko' container (executor -debug) and a 'jnlp' one with Trivy and crane
        container(config.kanikoContainer ?: 'kaniko') {
            withEnv(["REFERENCE=${reference}", "VERSION=${config.version}",
                     "COMMIT=${env.GIT_COMMIT ?: 'unknown'}", "BUILD_DATE=${date}",
                     "CONTEXT=${config.context ?: '.'}"]) {
                sh label: 'Build the image (Kaniko, no push)', script: '''
                    /kaniko/executor --context "dir://$WORKSPACE/$CONTEXT" --dockerfile Dockerfile \
                        --destination "$REFERENCE" --no-push --tar-path image.tar \
                        --build-arg VERSION="$VERSION" --build-arg COMMIT="$COMMIT" --build-arg BUILD_DATE="$BUILD_DATE"
                '''
            }
        }
        container(config.toolsContainer ?: 'jnlp') {
            scanWithTrivy('image.tar')          // the three Trivy calls from v1.6.0, extracted into a method
        }
        echo 'buildImage: without a daemon the image is not started; the real smoke test is the rollout in tecnoshop-dev'
        return reference
    }

And that of vars/publishImage.groovy:

    if ((config.engine ?: 'docker') == 'kaniko') {
        String host = (config.registry ?: 'https://registry.tecnoshop.local').replaceFirst(/^https?:\/\//, '')
        container(config.toolsContainer ?: 'jnlp') {
            withCredentials([usernamePassword(credentialsId: config.credential ?: 'registry-tecnoshop',
                                              usernameVariable: 'REGISTRY_USER', passwordVariable: 'REGISTRY_PASSWORD')]) {
                withEnv(["REFERENCE=${reference}", "REGISTRY_HOST=${host}",
                         "EXTRA_TAGS=${(config.extraTags ?: []).join(' ')}",
                         "INSECURE=${env.TECNOSHOP_INSECURE_REGISTRY == 'true' ? '--insecure' : ''}"]) {
                    sh label: 'Publish the image (crane)', script: '''
                        echo "$REGISTRY_PASSWORD" | crane auth login "$REGISTRY_HOST" -u "$REGISTRY_USER" --password-stdin
                        crane push $INSECURE image.tar "$REFERENCE" > image-digest.txt
                        for extraTag in $EXTRA_TAGS; do crane tag $INSECURE "$REFERENCE" "$extraTag"; done
                        crane auth logout "$REGISTRY_HOST" || true
                    '''
                }
            }
        }
        digest = readFile('image-digest.txt').trim()
        // ... from here on, the same as with Docker: build-info.txt, archiving, env.IMAGE_DIGEST
    }
  • crane push image.tar <reference> pushes the file and prints the digest reference; it is saved straight into image-digest.txt.
  • crane tag adds the version tag for releases without pushing anything again.
  • TECNOSHOP_INSECURE_REGISTRY: with the lab registry (HTTP), crane needs --insecure. Instead of writing it in the Jenkinsfile, Laura defines the global property TECNOSHOP_INSECURE_REGISTRY=true in the lab Jenkins (Manage Jenkins → System → Global properties, like TECNOSHOP_REGISTRY in 04-03). The Jenkinsfile is the same in the lab and at TecnoShop.
  • The library assumes a container naming convention (kaniko, jnlp), documented in vars/buildImage.txt, with parameters to change it.

Together with deployToKubernetes (section 12), it is released as v1.7.0.

The Controller on Kubernetes: The Official Helm Chart

The Jenkins project maintains a Helm chart (Helm being the Kubernetes package manager) to install the controller: jenkinsci/jenkins, published at https://charts.jenkins.io. It creates a single-replica StatefulSet, a persistent volume for JENKINS_HOME, the Service, the optional Ingress, the JCasC configuration and, by default, a Kubernetes cloud inside the cluster itself.

A minimal values.yaml for TecnoShop:

# values-jenkins.yaml: TecnoShop controller with the jenkinsci/jenkins chart.
# Check the names with `helm show values jenkins/jenkins`: the chart changes between versions.
controller:
  image:
    registry: registry.tecnoshop.local
    repository: tecnoshop/jenkins-controller     # the image from 05-04: Jenkins + pinned plugins
    tag: "2.xxx.y-1"
  installPlugins: false          # the plugins come in the image; nothing is installed at startup
  numExecutors: 0                # the controller does not build
  javaOpts: "-Xms2g -Xmx2g"
  resources:
    requests:
      cpu: "1"
      memory: 3Gi
    limits:
      memory: 3Gi
  admin:
    existingSecret: jenkins-admin    # Secret created separately, never in this file
    userKey: username
    passwordKey: password
  JCasC:
    defaultConfig: false
    configScripts: {}            # casc/jenkins.yaml will go here (08-03)
  ingress:
    enabled: true
    ingressClassName: nginx
    hostName: jenkins.tecnoshop.local
    tls:
      - secretName: jenkins-tecnoshop-tls
        hosts:
          - jenkins.tecnoshop.local

persistence:
  enabled: true                  # JENKINS_HOME on a persistent volume
  size: 50Gi
  storageClass: ssd-retain       # SSD and Retain policy: deleting the chart does not delete the volume

agent:
  enabled: true                  # "in-cluster" Kubernetes cloud
  namespace: jenkins-agents
helm repo add jenkins https://charts.jenkins.io
helm repo update
helm show values jenkins/jenkins > default-values.yaml     # the complete reference
helm upgrade --install jenkins jenkins/jenkins --namespace jenkins --create-namespace \
  --version <chart-version> -f values-jenkins.yaml
  • controller.image: the same image the lab uses in Compose. Installing with Helm does not change which Jenkins runs, only where.
  • installPlugins: false: the chart can install plugins at startup, but that would break the reproducibility from 05-04.
  • admin.existingSecret: the platform team creates the admin password with kubectl create secret, outside Git. With JCasC (08-03) the admin user will be described differently.
  • persistence: JENKINS_HOME on a fast disk; the Retain policy avoids losing the history if someone uninstalls the chart. The backups from 05-03 are still needed (volume snapshots).
  • agent.enabled: the chart configures a cloud that uses the API from inside the cluster, with no exported tokens. It is one of the advantages of having the controller in the cluster.
  • --version: pins the chart version, just as you pin the image version.

The option chosen for the lab: the controller stays in Docker Compose, connected to kind from outside. Installing a second Jenkins in kind would double memory consumption and mix the controller migration with the agent migration. At TecnoShop, Laura will rehearse the migration by restoring a copy of JENKINS_HOME into the chart's volume, just as she restored into jenkins-restored in 05-03; exercise 3 sets it up on a small scale.

The Pilot: orders-api in tecnoshop-dev

The Namespace and the Deployment Identity

lab/kind/tecnoshop-dev.yaml (at TecnoShop, the platform team applies it, not the pipeline):

apiVersion: v1
kind: Namespace
metadata:
  name: tecnoshop-dev
  labels:
    pod-security.kubernetes.io/enforce: restricted
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: deploy-orders
  namespace: tecnoshop-dev
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: deploy-orders
  namespace: tecnoshop-dev
rules:
  - apiGroups: ["apps"]
    resources: ["deployments"]
    resourceNames: ["orders-api"]
    verbs: ["get", "patch", "update"]
  - apiGroups: ["apps"]
    resources: ["deployments"]
    verbs: ["create", "list", "watch"]
  - apiGroups: ["apps"]
    resources: ["replicasets"]
    verbs: ["get", "list", "watch"]
  - apiGroups: [""]
    resources: ["configmaps", "services"]
    verbs: ["get", "list", "create", "patch", "update"]
  - apiGroups: [""]
    resources: ["pods", "pods/log", "events"]
    verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: deploy-orders
  namespace: tecnoshop-dev
subjects:
  - kind: ServiceAccount
    name: deploy-orders
    namespace: tecnoshop-dev
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: deploy-orders
---
apiVersion: v1
kind: Secret
metadata:
  name: deploy-orders-token
  namespace: tecnoshop-dev
  annotations:
    kubernetes.io/service-account.name: deploy-orders
type: kubernetes.io/service-account-token
  • enforce: restricted: the application must comply with the strictest level (no root, no privilege escalation, no capabilities, a seccomp profile). The Deployment below complies.
  • resourceNames: ["orders-api"]: modify only that Deployment. create, list and watch do not support resourceNames, which is why they go in a separate rule (kubectl apply needs to create it the first time, and rollout status watches).
  • No deleting, no secrets, nothing outside tecnoshop-dev.

The Manifests, in the orders-api Repository

k8s/configmap.yaml:

apiVersion: v1
kind: ConfigMap
metadata:
  name: orders-api-config
  labels:
    app.kubernetes.io/name: orders-api
data:
  application-dev.properties: |
    info.environment=dev
    info.platform=kubernetes
    management.info.env.enabled=true
    logging.level.com.tecnoshop=DEBUG

k8s/deployment.yaml:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: orders-api
  labels:
    app.kubernetes.io/name: orders-api
    app.kubernetes.io/part-of: tecnoshop
spec:
  replicas: 2
  revisionHistoryLimit: 5
  selector:
    matchLabels:
      app.kubernetes.io/name: orders-api
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 0
  template:
    metadata:
      labels:
        app.kubernetes.io/name: orders-api
    spec:
      automountServiceAccountToken: false
      securityContext:
        runAsNonRoot: true
        runAsUser: 10001
        runAsGroup: 10001
        seccompProfile:
          type: RuntimeDefault
      containers:
        - name: orders-api
          image: __IMAGE__
          ports:
            - name: http
              containerPort: 8081
          env:
            - name: SPRING_PROFILES_ACTIVE
              value: dev
            - name: SPRING_CONFIG_ADDITIONAL_LOCATION
              value: optional:file:/etc/orders-api/
          resources:
            requests:
              cpu: 100m
              memory: 384Mi
            limits:
              memory: 512Mi
          startupProbe:
            httpGet:
              path: /actuator/health/liveness
              port: http
            periodSeconds: 3
            failureThreshold: 40
          readinessProbe:
            httpGet:
              path: /actuator/health/readiness
              port: http
            periodSeconds: 5
            failureThreshold: 3
          livenessProbe:
            httpGet:
              path: /actuator/health/liveness
              port: http
            periodSeconds: 10
            failureThreshold: 3
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities:
              drop: ["ALL"]
          volumeMounts:
            - name: config
              mountPath: /etc/orders-api
              readOnly: true
            - name: tmp
              mountPath: /tmp
      volumes:
        - name: config
          configMap:
            name: orders-api-config
        - name: tmp
          emptyDir: {}

k8s/service.yaml:

apiVersion: v1
kind: Service
metadata:
  name: orders-api
  labels:
    app.kubernetes.io/name: orders-api
spec:
  selector:
    app.kubernetes.io/name: orders-api
  ports:
    - name: http
      port: 80
      targetPort: http

The essentials of the Deployment:

  • RollingUpdate with maxSurge: 1 and maxUnavailable: 0: Kubernetes starts a new pod, waits for it to be ready, removes an old one and repeats. There are never fewer than two replicas serving: it is the rolling deployment from 07-04 (remove from the load balancer, update, put back), done by the platform.
  • readinessProbe on /actuator/health/readiness: while it fails, the Service sends no traffic to that pod and the rollout does not move forward. It is the equivalent of check-health.sh before putting a node back into the load balancer.
  • livenessProbe on /actuator/health/liveness: if it fails three times in a row, Kubernetes restarts the container. That is why it is kept separate from readiness: a dependency that is down should take the pod out of traffic, not restart it in a loop.
  • startupProbe: gives startup up to 120 seconds (40 × 3) before the other two start counting; it keeps a slow start from being mistaken for a hung pod.
  • image: __IMAGE__: a placeholder that the pipeline replaces with the digest reference of the published image.
  • Configuration: the same mechanism as on the VMs in 07-03. The ConfigMap shows up as /etc/orders-api/application-dev.properties and SPRING_CONFIG_ADDITIONAL_LOCATION tells Spring to read it. The image is identical in every environment.
  • Security: user 10001 (the one from the Dockerfile), a read-only file system with a writable /tmp (Tomcat needs it), no capabilities. revisionHistoryLimit: 5 keeps five previous versions for rollback.

Deploying from the Pipeline: kubeconfig-tecnoshop and deployToKubernetes

The Credential

With the deploy-orders token, Laura builds a single-purpose kubeconfig:

kubectl apply -f lab/kind/tecnoshop-dev.yaml
TOKEN=$(kubectl -n tecnoshop-dev get secret deploy-orders-token -o jsonpath='{.data.token}' | base64 -d)
K=./kubeconfig-tecnoshop
kubectl config --kubeconfig="$K" set-cluster tecnoshop \
  --server=https://tecnoshop-control-plane:6443 --certificate-authority=ca-tecnoshop.crt --embed-certs=true
kubectl config --kubeconfig="$K" set-credentials deploy-orders --token="$TOKEN"
kubectl config --kubeconfig="$K" set-context tecnoshop-dev \
  --cluster=tecnoshop --user=deploy-orders --namespace=tecnoshop-dev
kubectl config --kubeconfig="$K" use-context tecnoshop-dev
unset TOKEN

Before uploading it, check it (the API is reachable as tecnoshop-control-plane only from the kind network; from your machine, temporarily change the server to the one from kind get kubeconfig, or run the checks in a container attached to that network):

kubectl --kubeconfig="$K" auth can-i patch deployment/orders-api   # yes
kubectl --kubeconfig="$K" auth can-i delete deployment/orders-api  # no
kubectl --kubeconfig="$K" auth can-i get secrets                   # no
kubectl --kubeconfig="$K" auth can-i create pods -n jenkins-agents # no

In Jenkins, in the credentials store of the orders-api multibranch folder (orders-api → Credentials → Folder → Global credentials → Add Credentials): Secret file, ID kubeconfig-tecnoshop, the file, description Kubeconfig for deploy-orders (tecnoshop-dev only, orders-api Deployment only). Owner: Laura. Then run shred -u ./kubeconfig-tecnoshop. Because it lives in the folder, catalog-web and orders-delivery cannot use it; as you already saw in 04-04, withCredentials([file(...)]) puts the path of a temporary copy in the variable.

The deployToKubernetes Step (v1.7.0)

vars/deployToKubernetes.groovy:

/**
 * Deploys an image (by digest) to Kubernetes with the repository manifests and waits for the rollout.
 * If the rollout does not finish in time, it goes back to the previous revision (kubectl rollout undo) and fails.
 *
 *   deployToKubernetes credential: 'kubeconfig-tecnoshop', namespace: 'tecnoshop-dev',
 *                      deployment: 'orders-api', image: env.IMAGE_DIGEST, manifests: 'k8s'
 *
 * Requires kubectl (tecnoshop/linux-agent:3).
 */
def call(Map config = [:]) {
    for (String required : ['credential', 'namespace', 'deployment', 'image']) {
        if (!config[required]) {
            error "deployToKubernetes: missing parameter \"${required}\""
        }
    }
    if (!(config.image ==~ /.+@sha256:[0-9a-f]{64}/)) {
        error "deployToKubernetes: the image must be referenced by digest; received '${config.image}'"
    }
    withCredentials([file(credentialsId: config.credential, variable: 'KUBECONFIG')]) {
        withEnv(["NS=${config.namespace}", "DEPLOYMENT=${config.deployment}", "IMAGE_REF=${config.image}",
                 "DIR=${config.manifests ?: 'k8s'}", "ROLLOUT_TIMEOUT=${config.rolloutTimeout ?: '180s'}",
                 "CHANGE_CAUSE=${env.JOB_NAME} #${env.BUILD_NUMBER}"]) {
            sh label: "Apply manifests to ${config.namespace}", script: '''
                kubectl -n "$NS" apply -f "$DIR/configmap.yaml" -f "$DIR/service.yaml"
                sed "s|__IMAGE__|$IMAGE_REF|" "$DIR/deployment.yaml" | kubectl -n "$NS" apply -f -
                kubectl -n "$NS" annotate deployment "$DEPLOYMENT" kubernetes.io/change-cause="$CHANGE_CAUSE" --overwrite
            '''
            int status = sh(returnStatus: true, label: 'Wait for the rollout',
                            script: 'kubectl -n "$NS" rollout status deployment/"$DEPLOYMENT" --timeout="$ROLLOUT_TIMEOUT"')
            if (status != 0) {
                sh label: 'Diagnostics', script: '''
                    kubectl -n "$NS" get pods -l app.kubernetes.io/name="$DEPLOYMENT" -o wide || true
                    kubectl -n "$NS" get events --sort-by=.lastTimestamp | tail -n 20 || true
                '''
                sh label: 'Rollback: return to the previous revision', script: '''
                    kubectl -n "$NS" rollout undo deployment/"$DEPLOYMENT"
                    kubectl -n "$NS" rollout status deployment/"$DEPLOYMENT" --timeout="$ROLLOUT_TIMEOUT"
                '''
                error "deployToKubernetes: ${config.deployment} did not complete the rollout in ${config.namespace}; " +
                      'rolled back to the previous revision'
            }
            env.DEPLOYED_TO = "${env.DEPLOYED_TO ? env.DEPLOYED_TO + ', ' : ''}k8s/${config.namespace}"
        }
    }
}
  • Digest only: the step rejects orders-api:1.2.0-SNAPSHOT-57. What gets deployed is exactly what was scanned.
  • kubectl apply with the versioned manifests (and the placeholder replaced with sed): declares the desired state. If nothing changes, it does nothing; if the image changes, the rolling update begins.
  • change-cause: the annotation shown by kubectl rollout history: who (which build) made each revision.
  • rollout status --timeout: waits for all the new replicas to be ready (their probes green). It is the deployment verification.
  • If it fails: diagnostics (pod status and the latest events) and rollout undo.
  • A change only to the ConfigMap does not restart the pods (they read the file at startup); at TecnoShop every build changes the image, so it does not happen, but it is worth knowing (Helm solves it with an annotation containing the ConfigMap's checksum).

Why kubectl apply and not Helm for the application? Three manifests and a single environment do not justify a chart; kubectl apply is transparent and can be read in the PR. When orders-api reaches staging and production on Kubernetes, with different values per environment, a dedicated chart (or Kustomize, built into kubectl) will avoid duplicating manifests.

Rollback on Kubernetes: kubectl rollout undo

Rollback on the VMs (07-04) Kubernetes equivalent
The previous jar is still in each server's releases/ The ReplicaSet of the previous revision is kept (revisionHistoryLimit)
revert.sh node by node, in reverse order, out of the load balancer kubectl rollout undo: a rolling update back to the previous template
orders-api-rollback with TARGET_VERSION kubectl rollout undo --to-revision=N, after checking kubectl rollout history
Automatic if verification fails Automatic in deployToKubernetes if the rollout does not finish
kubectl -n tecnoshop-dev rollout history deployment/orders-api
kubectl -n tecnoshop-dev rollout undo deployment/orders-api --to-revision=3

Two caveats:

  • rollout undo reverts the pod template (image, variables...), not the ConfigMap or the Service. That is why configuration must be changed carefully, just like the database schema (expand/contract, 07-04).
  • With no previous revision (the first deployment), undo fails: the build goes red and the Deployment is left with no ready replicas, which is acceptable in dev.

For canary and blue/green on Kubernetes there are specialized controllers, such as Argo Rollouts or Flagger, that automate the metrics analysis that 07-04 left as the next step.

The orders-api Jenkinsfile at the End of Module 8

Compared with the module 7 version, these things change: the library (v1.7.0); the agent (the pod from ci/pod-ci.yaml, with maven as the default); the steps that need agent tools go in container('jnlp'); a new parallel branch scans the Dockerfile and the manifests with trivy config (as announced in 07-05); the Image and Deploy to Kubernetes (pilot) stages are new; Publish also publishes the image; and cleanWs() disappears, because the workspace dies with the pod.

@Library('[email protected]') _

pipeline {
    agent {
        kubernetes {
            cloud 'kubernetes'
            yamlFile 'ci/pod-ci.yaml'
            defaultContainer 'maven'
        }
    }

    options {
        timestamps()
        timeout(time: 30, unit: 'MINUTES')
        buildDiscarder(logRotator(numToKeepStr: '30', artifactNumToKeepStr: '5'))
        disableConcurrentBuilds(abortPrevious: env.CHANGE_ID != null)
        preserveStashes(buildCount: 5)
    }

    parameters {
        booleanParam(name: 'RUN_TESTS', defaultValue: true,
                     description: 'Uncheck only to quickly verify that the code compiles. Without tests nothing is analyzed, published or deployed, and the CD pipeline is not triggered. Security checks always run.')
    }

    triggers {
        cron(env.BRANCH_NAME == 'main' ? 'TZ=Europe/Madrid\nH 2 * * 1-5' : '')
    }

    environment {
        MAVEN_ARGS        = '-B -ntp'
        MAVEN_SETTINGS_ID = 'maven-settings-tecnoshop'
        IMAGE             = 'registry.tecnoshop.local/orders-api'
        APP_VERSION       = sh(script: './mvnw -q help:evaluate -Dexpression=project.version -DforceStdout',
                               returnStdout: true, label: 'Read the version from the pom').trim()
        IMAGE_TAG         = "${APP_VERSION}-${BUILD_NUMBER}"
    }

    stages {
        stage('PR info') {
            when {
                changeRequest()
            }
            steps {
                echo "PR #${env.CHANGE_ID} by ${env.CHANGE_AUTHOR}: ${env.CHANGE_BRANCH} → ${env.CHANGE_TARGET} (${env.CHANGE_URL})"
            }
        }

        stage('Build') {
            steps {
                echo "Build ${env.BUILD_NUMBER} of ${env.JOB_NAME} | branch ${env.BRANCH_NAME} | version ${env.APP_VERSION} | RUN_TESTS=${params.RUN_TESTS}"
                mavenTecnoShop 'clean compile'
            }
        }

        stage('Checks') {
            failFast true
            parallel {
                stage('Tests') {
                    when {
                        expression { params.RUN_TESTS }
                    }
                    options {
                        timeout(time: 10, unit: 'MINUTES')
                    }
                    steps {
                        mavenTecnoShop 'test'
                        recordCoverage(
                            tools: [[parser: 'JACOCO', pattern: 'target/site/jacoco/jacoco.xml']],
                            id: 'jacoco',
                            name: 'Coverage (JaCoCo)',
                            sourceCodeRetention: 'LAST_BUILD',
                            qualityGates: [
                                [metric: 'LINE',   baseline: 'PROJECT', threshold: 70.0, criticality: 'UNSTABLE'],
                                [metric: 'BRANCH', baseline: 'PROJECT', threshold: 60.0, criticality: 'UNSTABLE']
                            ]
                        )
                    }
                    post {
                        always {
                            junit testResults: 'target/surefire-reports/*.xml', allowEmptyResults: false
                        }
                        failure {
                            echo 'The tests failed: check the Test Result page of the build.'
                        }
                    }
                }
                stage('Dependency analysis') {
                    options {
                        timeout(time: 15, unit: 'MINUTES')
                    }
                    steps {
                        mavenTecnoShop goals: 'dependency:tree -DoutputFile=dependencies.txt', label: 'Dependency tree'
                        withCredentials([string(credentialsId: 'nvd-api-key', variable: 'NVD_API_KEY')]) {
                            mavenTecnoShop goals: 'dependency-check:check', label: 'Known vulnerabilities (OWASP Dependency-Check)'
                        }
                    }
                    post {
                        always {
                            archiveArtifacts artifacts: 'dependencies.txt,target/dependency-check-report.html', allowEmptyArchive: true
                            dependencyCheckPublisher pattern: 'target/dependency-check-report.xml', unstableTotalMedium: 1
                        }
                    }
                }
                stage('Secrets') {
                    steps {
                        container('jnlp') {
                            scanSecrets()
                        }
                    }
                }
                stage('Secrets in history') {
                    when {
                        allOf {
                            branch 'main'
                            triggeredBy 'TimerTrigger'
                        }
                    }
                    steps {
                        container('jnlp') {
                            scanSecrets history: true, report: 'gitleaks-history.json'
                        }
                    }
                }
                stage('Container configuration') {
                    steps {
                        container('jnlp') {
                            sh label: 'Dockerfile and Kubernetes manifests (trivy config)',
                               script: 'trivy config --severity HIGH,CRITICAL --exit-code 1 --quiet Dockerfile k8s/'
                        }
                    }
                }
            }
        }

        stage('Integration tests') {
            when {
                expression { params.RUN_TESTS }
            }
            options {
                timeout(time: 10, unit: 'MINUTES')
            }
            steps {
                mavenTecnoShop goals: 'failsafe:integration-test failsafe:verify', label: 'Integration tests'
            }
            post {
                always {
                    junit testResults: 'target/failsafe-reports/TEST-*.xml', allowEmptyResults: false
                }
            }
        }

        stage('Package') {
            steps {
                mavenTecnoShop '-DskipTests package'
                infoBuild application: 'orders-api', version: env.APP_VERSION, image: "${env.IMAGE}:${env.IMAGE_TAG}"
                archiveArtifacts artifacts: 'target/*.jar,target/bom.json,build-info.txt', fingerprint: true
                stash name: 'jar', includes: 'target/*.jar'
            }
        }

        stage('Smoke') {
            options {
                timeout(time: 3, unit: 'MINUTES')
            }
            steps {
                container('jnlp') {
                    smokeSpringBoot extraPath: '/api/orders', expectedText: 'SHIPPED'
                }
            }
        }

        stage('Image') {
            options {
                timeout(time: 15, unit: 'MINUTES')
            }
            steps {
                buildImage engine: 'kaniko', image: env.IMAGE, tag: env.IMAGE_TAG, version: env.APP_VERSION
            }
        }

        stage('Quality analysis') {
            when {
                allOf {
                    branch 'main'
                    expression { params.RUN_TESTS }
                }
            }
            options {
                timeout(time: 10, unit: 'MINUTES')
            }
            steps {
                withSonarQubeEnv('sonar-tecnoshop') {
                    mavenTecnoShop goals: 'sonar:sonar', label: 'SonarQube analysis'
                }
            }
        }

        stage('Quality Gate') {
            when {
                allOf {
                    branch 'main'
                    expression { params.RUN_TESTS }
                }
            }
            options {
                timeout(time: 5, unit: 'MINUTES')
            }
            steps {
                waitForQualityGate abortPipeline: true
            }
        }

        stage('Publish') {
            when {
                allOf {
                    expression { params.RUN_TESTS }
                    anyOf {
                        allOf {
                            branch 'main'
                            expression { env.APP_VERSION.endsWith('-SNAPSHOT') }
                        }
                        tag pattern: 'v\\d+\\.\\d+\\.\\d+', comparator: 'REGEXP'
                    }
                }
            }
            options {
                timeout(time: 10, unit: 'MINUTES')
            }
            steps {
                milestone(label: 'Publish')
                sh label: 'Check that the tag matches the version', script: '''
                    if [ -n "${TAG_NAME:-}" ] && [ "$TAG_NAME" != "v$APP_VERSION" ]; then
                        echo "ERROR: the tag $TAG_NAME does not match the pom version ($APP_VERSION)"
                        exit 1
                    fi
                '''
                mavenTecnoShop goals: '-DskipTests -Dmaven.install.skip=true deploy',
                               settings: 'maven-settings-tecnoshop-publish',
                               label: 'Publish to Nexus (jar and SBOM)'
                publishImage engine: 'kaniko', image: env.IMAGE, tag: env.IMAGE_TAG,
                             extraTags: env.TAG_NAME ? [env.APP_VERSION] : []
            }
        }

        stage('Deploy to dev') {
            when {
                allOf {
                    branch 'main'
                    expression { params.RUN_TESTS }
                }
            }
            options {
                timeout(time: 5, unit: 'MINUTES')
            }
            environment {
                DEV_SERVER = 'dev-01.tecnoshop.local'
            }
            steps {
                container('jnlp') {
                    unstash 'jar'
                    sshagent(credentials: ['ssh-dev']) {
                        sh label: 'Deploy to dev-01 over SSH', script: 'sh deploy/deploy.sh "$DEV_SERVER"'
                    }
                }
            }
        }

        stage('Deploy to Kubernetes (pilot)') {
            when {
                allOf {
                    branch 'main'
                    expression { params.RUN_TESTS }
                }
            }
            options {
                timeout(time: 5, unit: 'MINUTES')
            }
            steps {
                container('jnlp') {
                    deployToKubernetes credential: 'kubeconfig-tecnoshop', namespace: 'tecnoshop-dev',
                                       deployment: 'orders-api', image: env.IMAGE_DIGEST, manifests: 'k8s'
                }
            }
        }

        stage('Trigger CD') {
            when {
                allOf {
                    tag pattern: 'v\\d+\\.\\d+\\.\\d+', comparator: 'REGEXP'
                    expression { params.RUN_TESTS }
                }
            }
            steps {
                script {
                    def sha256 = sh(script: 'sha256sum target/orders-api-*.jar | cut -d " " -f 1',
                                    returnStdout: true, label: 'SHA-256 of the published jar').trim()
                    build job: '/orders-delivery/orders-api-cd',
                          wait: false,
                          parameters: [
                              string(name: 'VERSION', value: env.APP_VERSION),
                              string(name: 'SHA256', value: sha256)
                          ]
                    currentBuild.description = "${currentBuild.description} → orders-api-cd"
                }
            }
        }
    }

    post {
        always {
            notifyTeam channel: '#ci-orders', email: '[email protected]'
        }
    }
}

Notes on this version:

  • APP_VERSION in environment still works: it is evaluated in the pod's default container (maven), after the checkout.
  • The parallel branches run in the same pod, at the same time, in different containers (maven for Maven, jnlp for gitleaks and Trivy). The pod's resource requests must cover that peak.
  • Smoke in jnlp: the agent image is guaranteed to have Java 21 and curl. Since all the containers share the network, the jar started there is reachable on localhost.
  • Image runs in every build, PRs included: Kaniko builds and Trivy scans; nothing is pushed until Publish.
  • Deploy to dev (the dev-01 VM) and Deploy to Kubernetes (pilot) coexist: for a few weeks the team compares both dev environments (Marta's acceptance criteria can be run against both) before deciding.
  • orders-api-cd does not change: it still deploys the Nexus jar to the staging and production VMs from linux-agent-01.
  • cleanWs() disappears: the workspace emptyDir is deleted along with the pod. If you ever use idleMinutes to reuse pods, you will have to bring it back.

The Next Step on the Roadmap

Step What it involves When
Evaluate the pilot Compare build times, deployment stability and cost against the dev-01 VM Coming weeks
catalog-web and orders-api-cd to pods Their own pod templates; the CD will need to reach the VMs or the target clusters After the pilot
staging and production on Kubernetes Target clusters, a chart or Kustomize per environment, imagePullSecrets, network policies, approval as in 07-03 Next quarter
Controller on Kubernetes with Helm Migrate JENKINS_HOME to the chart's volume, configuration with JCasC (08-03) Before decommissioning the controller VM
GitOps (Argo CD, Flux) Jenkins builds and updates a configuration repository; another system syncs the cluster To be considered once there are several environments on Kubernetes
Image signing and admission policies cosign in publishImage and rejection of unsigned images in the cluster (07-05) Together with production on Kubernetes

Common Mistakes and Tips

  • The pod stays Pending: no node has the requested resources free. kubectl -n jenkins-agents describe pod <name> tells you in the events (Insufficient memory). Reduce the requests or free up memory in the lab.
  • ErrImagePull or ImagePullBackOff with registry.tecnoshop.local: the hosts.toml is missing on the node (it is lost when the cluster is recreated), Nexus does not allow anonymous pulls, or the image has not been published with that tag.
  • The agent does not connect and the pod dies after a few minutes: the cloud's Jenkins URL is not reachable from the pods, or WebSocket is not checked. Look at the jnlp container's log with Pod Retention temporarily set to On Failure and kubectl logs <pod> -c jnlp.
  • sh in a container gives exec: "sh": executable file not found: the image has no shell (for example, Kaniko without -debug, or distroless images). The container step needs sh.
  • Forbidden: pods ... violates PodSecurity "baseline": the pod template asks for something forbidden (privileged, hostPath). That is the protection working: do not loosen it for a build.
  • OOMKilled in the maven container: Maven's JVM plus the test JVMs exceed the limit. Adjust MaxRAMPercentage, the Surefire argLine or the limit, but measure before raising it.
  • Deploying by tag (orders-api:1.2.0-SNAPSHOT-57): if the tag moved, two replicas could be running different images. deployToKubernetes prevents this by requiring the digest.
  • Mixing up liveness and readiness: a liveness probe that checks external dependencies restarts every pod when a dependency goes down. Liveness answers "is the process alive?"; readiness, "can it serve traffic?".
  • Granting cluster-admin "to make it work": the Jenkins credential would control the whole cluster. The two Role objects in this lesson are the most TecnoShop needs.
  • Tip: when a pod fails in a strange way, reproduce the specification by hand: kubectl -n jenkins-agents apply -f ci/pod-ci.yaml (adding a metadata.name) shows you the API errors without going through Jenkins.

Exercises

Exercise 1. Set up the lab (kind, the kind network in Compose, hosts.toml, jenkins-agents.yaml, the credential and the cloud) and run lab-k8s. While it runs, watch what happens in a terminal with kubectl -n jenkins-agents get pods -w. How many containers does the pod have, and why? What happens to the pod when it finishes?

Exercise 2. After deploying the pilot, publish from a PR a version of orders-api whose readiness never becomes ready (for example, a HealthIndicator that always returns DOWN in the dev profile). Merge it into main in your lab. Describe what you will see in the build, in kubectl rollout history and in the Service's traffic during the process.

Exercise 3. Practice installing the controller with Helm on kind, in the jenkins-helm-test namespace, with a reduced values.yaml (no Ingress, a 1 GiB heap, a 5 GiB volume, and the registry.tecnoshop.local/tecnoshop/jenkins-controller image that you publish). How do you access the interface? What differences do you notice in Manage Jenkins → Clouds compared with your Compose Jenkins?

Solutions

Solution 1. The pod goes through Pending (scheduling and image pulling, longer the first time), Running for the duration of the build and, when it finishes, Terminating until it disappears (Pod Retention: Never). It has two containers: maven, declared in the YAML, and jnlp, which the plugin adds on its own because you did not declare it; jnlp is the agent that connects to the controller and runs the steps, and maven is just waiting with sleep. kubectl -n jenkins-agents get pod <name> -o jsonpath='{.spec.containers[*].name}' confirms it. While it exists, the pod shows up in Manage Jenkins → Nodes like any other agent.

Solution 2. The CI passes all its stages (the tests do not run the dev profile), publishes the image and reaches Deploy to Kubernetes (pilot). kubectl apply creates a new revision; Kubernetes starts one new pod (maxSurge: 1) that never passes readiness, so it receives no traffic and no old pod is removed (maxUnavailable: 0): the Service keeps serving with the two previous replicas, with no outage. After 180 seconds, rollout status fails, the step shows the diagnostics (the new pod with 0/1 under READY), runs rollout undo (which removes the new pod and leaves the previous template as the most recent revision) and the build ends in red, with a notification in #ci-orders. rollout history shows the failed revision and the restored one, with their change-cause. The fix is to revert the change on main (roll forward with the correction, as in 07-04).

Solution 3. A values.yaml like the one in the lesson with controller.ingress.enabled: false, controller.javaOpts: "-Xms1g -Xmx1g", 1.5 GiB of resources, persistence.size: 5Gi with no storageClass (kind's default one) and a jenkins-admin Secret created beforehand with kubectl -n jenkins-helm-test create secret generic jenkins-admin --from-literal=username=laura --from-literal=password=<random>. You access it with kubectl -n jenkins-helm-test port-forward svc/jenkins 8095:8080 and http://localhost:8095. Clouds shows a Kubernetes cloud created by the chart that has no URL or credential: it uses the controller's own ServiceAccount inside the cluster, and its Jenkins URL is the name of the internal Service. Uninstall it when you are done with helm uninstall and delete the namespace (and its volume) to free up memory.

Conclusion

orders-api is now built on Kubernetes. Each build gets an ephemeral pod in jenkins-agents, described in ci/pod-ci.yaml, with a maven container, a kaniko one and the jnlp agent on tecnoshop/linux-agent:3 (which adds kubectl and crane), which connects over WebSocket to the kubernetes cloud with the k8s-jenkins-agents credential. You have applied least privilege at two levels: RBAC (one ServiceAccount that only manages build pods, another with no permissions for the builds themselves, and deploy-orders, which can only update one Deployment) and Pod Security Admission. The image is built without a daemon with Kaniko, scanned with Trivy before being pushed and published with crane thanks to tecnoshop-lib v1.7.0, which also adds deployToKubernetes: the tecnoshop-dev pilot receives every main build by digest with a rolling update governed by readiness and liveness probes, and rolls back with kubectl rollout undo if it does not finish. You know the official Helm chart for the controller and why TecnoShop will migrate the controller separately. In this module you have added many pieces of configuration (clouds, credentials, plugins, jobs) by clicking through the interface, exactly the opposite of what you do with pipelines. In Jenkins as Code: Jenkinsfile, JCasC and Job DSL you will describe all of Jenkins in Git.

© Copyright 2026. All rights reserved