Jenkins: Deployment under Kubernetes

In short
  • Jenkins, a pioneer of CI/CD, remains widely adopted thanks to its plugins.
  • Creating custom images (server and agent).
  • Deployment with Helm under Kubernetes.
  • Validation: Jenkins manipulates cluster objects internally.

Introduction

Jenkins logo

Click the image to enlarge.

Jenkins is one of the foundational applications of CI/CD. Some even consider it a dinosaur in the DevOps market, advocating for its replacement with more modern and optimized tools.

However, Jenkins continues to be widely adopted and used. Its strength lies precisely in its longevity. Over the years, it has been enriched with numerous plugins, allowing integration into many ecosystems.

Generations of administrators have been able to train and develop their skills on this product, resulting in a large community of experts today.

The goal of this tutorial is to provide an introduction to installing Jenkins under Kubernetes. I do not intend to detail the use of Jenkins. I don't have sufficient expertise for that, and Jenkins is so powerful in terms of feasibility that there are many ways to do things and possible uses.

I simply want to offer some suggestions for deploying Jenkins under K8S, with the ultimate goal of including this article in a series of tutorials aimed at illustrating a complete CI/CD use case.

Unlike ArgoCD, which I presented here, and which is focused on continuous deployment (CD) via a GitOPS logic, Jenkins can be used for both CI (Continuous Integration) and CD.

Recap of the fundamentals

By the way, I'm taking this opportunity to remind you of this distinction, which is often forgotten:

  • CI, which stands for "Continuous Integration," encompasses all tasks related to compilation, code verification, image creation, etc. These processes are performed automatically and continuously.
  • CD, on the other hand, refers to "Continuous Delivery," which includes all aspects related to installation, deployment, and upgrades of applications, up to production environments. All of this is also done automatically and without interruption.

The ultimate goal is to build the famous CI/CD pipeline, enabling complete and continuous automation from code creation to application delivery… all the way to production!

Marketing often tends to mix things up. It's not uncommon for an application to have only CI or only CD, or even automation in a DEV environment only… without ever truly achieving full industrialization.

Some tools are sometimes oriented solely towards CI or CD. Jenkins was initially designed as a CI tool. Thanks to its extensibility through plugins, it has since expanded to include CD, making it today a platform capable of managing an entire CI/CD pipeline.

The downside is that Jenkins can sometimes perform certain tasks in a more complex and/or less efficient way than specialized tools when dealing with a specific part of the CI/CD pipeline.

History

For a bit of history, Jenkins is derived from Hudson, a software developed by Kohsuke Kawaguchi, an engineer at Sun Microsystems in 2004. Following Oracle's acquisition of Sun in 2010, tensions arose around Hudson, leading to a split in the community in January 2011 and the creation of Jenkins.

Since then, Hudson has been abandoned… Jenkins is still here!

Today, Jenkins is a project maintained by the Jenkins community, under the auspices of the Jenkins project, hosted by the CD Foundation (Continuous Delivery Foundation).

The CDF is to CI/CD what the CNCF is to cloud-native.

It structures the open source DevOps ecosystem, promoting key projects like Jenkins and Tekton, and bringing together a global community around software delivery.

Jenkins X

Before we start, it's worth clarifying Jenkins X. Although with a very similar name, Jenkins X is different from Jenkins.

Jenkins X logo

Click the image to enlarge.

Jenkins X dates back to 2018 and doesn't have the same philosophy as Jenkins. Its fundamental principle is to be a native CI/CD automation tool for Kubernetes, leveraging ready-to-use pipelines based on Tekton. Tekton is an open source pipeline framework designed for k8s.

Here's a table comparing the two products:

Feature Jenkins Jenkins X
Architecture Extensible monolithic Based on Kubernetes and Tekton
CI/CD CI-centric, CD as a plugin Complete CI/CD with integrated GitOps
Deployment VM, Docker, etc. Native Kubernetes
Pipelines Jenkinsfile (Groovy) YAML + Tekton
Usage General-purpose Cloud-native, microservices, GitOps

In reality, the adoption of Jenkins X is rather modest. It is often preferred to keep Jenkins and extend it with other tools that are more natively compatible with Kubernetes, such as ArgoCD, to handle certain parts of the pipeline.

The Jenkins X project is much less active today. That's why I prefer to use Jenkins and "adapt" it to make it usable on K8S... moreover, the community already offers many things for this, as we will see.

Creating images

Jenkins operates on the principle of a controller and agents. The controller serves as an administration center and entry point for configurations, while the agents execute the jobs contained in the pipelines. I won't go into detail, considering that you are already familiar with the tool.

Having an internal certificate authority (Certificate Authority (CA)) in the form of the Microsoft solution, I use certificates validated only internally within my lab.

Since Jenkins needs to communicate with other components of my network, it must recognize this CA. This is a common case in companies.

By default, Jenkins container images only recognize public CAs. If I don't anticipate this point, I will have errors as soon as the controller or agents try to communicate via SSL with other tools present in my lab.

It is very common to have to customize the base images of Jenkins. Adding support for custom CAs is a possible reason, but other needs may arise. For example, in my case, adding the kubectl binary for the agents.

Other ways of doing things are possible, but this is the choice I made and that you might find in some organizations.

Controller image

So, we will start by building the image for the Jenkins controller.

Here is the Dockerfile Dockerfile.server used:

  
FROM jenkins/jenkins:2.492.2-lts

USER root

# Copie du CA
COPY ca-coolcorp.crt /usr/local/share/ca-certificates/ca-coolcorp.crt

# Ajout du CA au système et au keystore Java
RUN apt-get update && apt-get install -y ca-certificates openjdk-17-jre-headless \
    #partie systeme
    && update-ca-certificates \
    #partie keystore
    && keytool -importcert -noprompt \
       -trustcacerts \
       -alias my-ca \
       -file /usr/local/share/ca-certificates/ca-coolcorp.crt \
       -keystore "$JAVA_HOME/lib/security/cacerts" \
       -storepass changeit

USER jenkins

  

At the time of writing this article, I am using version 2.492.2-lts as a base.

The modifications will be to add the public certificate from my CA (ca-coolcorp.crt) to both the Linux subsystem of the container (Debian) and the Jenkins keystore.

Indeed, Jenkins is developed in Java. It does not necessarily use the operating system's underlying trusted certificate recognition. Therefore, you need to add the CA to a Java keystore.

Now, all that remains is to compile the image and send it to my registry (GitLab).

docker build -t registry.gitlab.com/apps.coolcorp.priv/jenkins-custom:2.492.2-lts-v1 -f Dockerfile.server . docker push registry.gitlab.com/apps.coolcorp.priv/jenkins-custom:2.492.2-lts-v1
Creating the image for the controller

Click the image to enlarge.

Sending the controller image to the registry

Click the image to enlarge.

Agent image

We can now move on to the agent, via the Dockerfile Dockerfile.agent:

FROM jenkins/inbound-agent:3301.v4363ddcca_4e7-2

USER root

# Copie du CA
COPY ca-coolcorp.crt /usr/local/share/ca-certificates/ca-coolcorp.crt

# Ajout du CA au système et au keystore Java
RUN apt-get update && apt-get install -y ca-certificates openjdk-17-jre-headless \
    #partie systeme
    && update-ca-certificates \
    #partie keystore
    && keytool -importcert -noprompt \
       -trustcacerts \
       -alias my-ca \
       -file /usr/local/share/ca-certificates/ca-coolcorp.crt \
       -keystore "$JAVA_HOME/lib/security/cacerts" \
       -storepass changeit
#ajout du binaire kubectl
RUN curl -LO "https://dl.k8s.io/release/v1.32.0/bin/linux/amd64/kubectl" && \
    install -o root -g root -m 0755 kubectl /usr/local/bin/kubectl && \
    rm kubectl       

USER jenkins

The principle is the same as for the server; we add one extra step by including the kubectl binary (in version 1.32 here).

Indeed, it is the agent that will be responsible for executing kubectl commands, so we need to integrate the binary into it. Other approaches are possible. This one has the disadvantage of requiring new images with each new version of kubectl, and having a dependency between the agent used and the version of the cluster on which it operates, but it remains simple and quick to implement.

We compile the image and send it to the registry:

docker build -t registry.gitlab.com/apps.coolcorp.priv/jenkins-custom:agent-2.492.2-lts-v1 -f Dockerfile.agent . docker push registry.gitlab.com/apps.coolcorp.priv/jenkins-custom:agent-2.492.2-lts-v1
Creating the image for the agent

Click the image to enlarge.

Sending the agent image to the registry

Click the image to enlarge.

We now have two "custom" images. It is not uncommon for other adjustments to be needed in a company. This is not necessarily a blocker, even for an assisted deployment of Jenkins via Helm, as we will see later.

Deploying Jenkins

To run Jenkins, we will prefer to dedicate a namespace to it. This follows my naming convention, and can be created very easily using the following command:

kubectl create ns prd-jenkins-lan
Creating the namespace

Click the image to enlarge.

As usual, and for each deployment of an application under Kubernetes, here is a target diagram that summarizes the objects that will need to be manipulated:

Architecture diagram

Click the image to enlarge.

Storage

Before starting the Jenkins deployment, we will manage the persistent storage requirement. Since I have chosen Helm to install Jenkins, I could rely on it to provision the storage dynamically. But this is something I prefer to manage in advance for better control.

Jenkins can simply use a Network File System (NFS) share to host its data and configuration. In fact, this is a major strength of the product: easy to back up, easy to restore. You mount the NFS volume, and Jenkins automatically recovers.

In my case, I will simply provision a folder on my NAS that is intended to be accessible to my Kubernetes cluster.

Creating the folder on NFS

Click the image to enlarge.

We can then generate a PersistentVolume (pv) based on the CSI (Container Storage Interface) NFS. For those who are not familiar with the principle of storage under k8S, I invite you to read this article from my K8S cookbook as well as this article on the deployment of CSI NFS.

Here is the content of the file 01-pv-jenkins-default.yml:

---
apiVersion: v1
kind: PersistentVolume
metadata:
  annotations:
    pv.kubernetes.io/provisioned-by: nfs.csi.k8s.io
  name: pv-jenkins-default
  labels:
      environment: prd
      network: lan
      application: jenkins
      tier: default
spec:
  capacity:
    storage: 30Gi
  accessModes:
    - ReadWriteMany
  persistentVolumeReclaimPolicy: Retain
  csi:
    driver: nfs.csi.k8s.io
    volumeHandle: /Volume1/nfsshare/rubikub.coolcorp.priv/namespaces/prd-jenkins-lan/default
    volumeAttributes:
      server: 192.168.10.152
      share: /Volume1/nfsshare/rubikub.coolcorp.priv/namespaces/prd-jenkins-lan/default    
    

Nothing new under the sun; I'm directly mounting the volume to my NFS export /Volume1/nfsshare/rubikub.coolcorp.priv/namespaces/prd-jenkins-lan/default.

Here is the content of the PersistentVolumeClaim associated through the file 02-pvc-jenkins-default.yml:

---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: pvc-jenkins-default
  namespace: prd-jenkins-lan
  labels:
      environment: prd
      network: lan
      application: jenkins
      tier: default
spec:
  accessModes:
    - ReadWriteMany
  resources:
    requests:
      storage: 30Gi
  volumeName: pv-jenkins-default
  storageClassName: ""

The PVC explicitly references the PV without going through a StorageClass (sc).

I place both in a 'storage' folder and I can apply them directly using the command:

kubectl apply -f storage/
Applying the pv and pvc objects

Click the image to enlarge.

We can check the status of the PVC:

kubectl get pvc -n prd-jenkins-lan
Checking the pvc

Click the image to enlarge.

For now, it is not yet mounted, as no application is requesting it.

Using Helm

I assume you have basic knowledge of Helm and Kubernetes. If not, feel free to review all the steps in my cookbook on K8S. However, we will quickly recap Helm

Helm is a package manager for Kubernetes that simplifies application deployment. It avoids having to manipulate all the YAML files that might be associated with it and preconfigures the application for quick use.

Helm comes in the form of a simple binary that you deploy on your cluster or on your working environment, which is used to manage Kubernetes (where the access elements, such as the configuration file, to the cluster are located).

A Helm package is referred to as a Chart. It's actually a folder that contains all the manifests needed for the application, as well as a values.yaml file containing the application configuration and the variables to be passed to the various Kubernetes objects.

By default, all of this is "hidden" from the user, who can simply launch the installation of the desired application with a simple Helm command. These charts are available in repositories, similar to what you can find on Linux distributions.

So we start by adding these repositories.

helm repo add jenkins https://charts.jenkins.io helm repo update
Adding the Helm repository

Click the image to enlarge.

While I appreciate Helm a lot, it also frustrates me. Initially, if you simply deploy packaged applications, you don't know how they will be configured or what objects will be declared and with what configuration.

Therefore, it is always recommended to take a look at the default "values". They can be directly accessed on the GitHub repository associated with the project or can be extracted using the command helm show values nom_repo

Personally, I have gotten into the habit of exporting these values to a file default-value.yml within a subdirectory helm:

helm show values Jenkins/jenkins > helm/default-value.yml
Extracting default values

Click the image to enlarge.

Default values for the chart

Click the image to enlarge.

This allows me to draw inspiration from the suggested configuration to build my own custom-values.yml file.

Here is its content:

controller:
  namespaceOverride: prd-jenkins-lan
#Utilisation de l'image custom
  imagePullSecretName: sec-jenkins-registry
  image:
    registry: registry.gitlab.com
    repository: apps.coolcorp.priv/jenkins-custom
    tag: 2.492.2-lts-v1
    pullPolicy: Always
#Précision sur l'URL de jenkins 
  jenkinsUrlProtocol: https
  jenkinsUrl: https://jenkins.coolcorp.priv
#On ne créé par un ingress automatiquement
  ingress:
    enabled: false

  service:
    type: ClusterIP
    port: 8080

  resources:
    requests:
      cpu: "500m"
      memory: "1Gi"
    limits:
      cpu: "2000m"
      memory: "4Gi"
 
#Récupération du pvc existent
persistence:
  enabled: true
  existingClaim: pvc-jenkins-default

#Configuration de l'agent
agent:
  enabled: true
  #Usage d'un compte de service dédié
  useDefaultServiceAccount: false
  serviceAccount: sa-jenkins-agent
  #url du controleur
  jenkinsUrl: https://jenkins.coolcorp.priv
  #image de l'agent à utiliser 
  imagePullSecretName: sec-jenkins-registry
  image:
    repository: registry.gitlab.com/apps.coolcorp.priv/jenkins-custom
    tag: agent-2.492.2-lts-v2
  

As you can see, it is significantly smaller because I only include the options that I want to modify.

Overall, I will specify the images to be used. I indicate those that I have "customized" at the beginning of the article.

I am also adding a reference to the URL where the controller will be accessible (jenkins.coolcorp.priv).

Of course, I declare the recently created PVC, pvc-jenkins-default, so that it can be used without Helm having to create other storage objects.

Another important point is that, in the agent section, I specify a service account to use: sa-jenkins-agent. This part will be detailed in a dedicated section, but it is important to understand that the agent needs to perform actions on the cluster. Therefore, it must do so under the identity of an account authorized to manipulate objects on the cluster.

Finally, as we will see later, I do not want an object of type ingress to be created automatically. We will take care of that ourselves.

Before starting the installation, there is a prerequisite. Since I am using custom images from a private registry, I need to create the secret containing the access token for this registry.

This secret, which I will name sec-jenkins-registry, is also specified in the custom-values.yml file in the imagePullSecretName field.

Here is the content of the 01-sec-jenkins-registry.yml file (with fake values, of course… 😊):

apiVersion: v1
data:
  .dockerconfigjson: eyJhdXRocyI6eyJyZWdpc3RyeS5naXRsYWIuY29tIjp7
kind: Secret
metadata:
  name: sec-jenkins-registry
  namespace: prd-jenkins-lan
type: kubernetes.io/dockerconfigjson

We apply it immediately:

Kubectl apply -f 01-sec-jenkins-registry.yml
Creating the secret for the registry

Click the image to enlarge.

The Jenkins deployment can now be performed by specifying my custom values file:

helm install Jenkins Jenkins/jenkins -n prd-jenkins-lan -f helm/custom-values.yml
Starting the installation with Helm

Click the image to enlarge.

Note the output from Helm, which specifies that you should use this instruction: kubectl exec -namespace prd-jenkins-lan—it svc/Jenkins -c Jenkins -- /bin/cat /run/secrets/additional/chart-admin-password && echo to obtain the password for the default admin account.

Retrieve it and store it securely.

Retrieving the administrator password

Click the image to enlarge.

The finalization of the installation takes a few minutes. We can verify the success of the operation with the following command:

kubectl get pod -n prd-jenkins-lan
Checking the installation

Click the image to enlarge.

(For those who may not have noticed, based on the name of the pod, we can see that Helm has deployed Jenkins as StatefulSets).

Our pod Jenkins is there… Now we need to make it accessible.

Exposing via Ingress

This is where we talk about ingress. As a reminder, this object allows you to expose your application outside the K8S cluster. If you are a little lost, feel free to read this article.

My Jenkins instance will be accessible at the URL https://jenkins.coolcorp.priv. This is an HTTPS site with a certificate.

Therefore, I need to create this certificate beforehand and store it in a secret so that it can be used by the ingress.

It's possible to fully automate the creation and mapping of the certificate using Cert Manager. I actually have a dedicated article if you are interested in this topic.

Here, I will use a more traditional method. First, I will generate my key and the associated certificate request (CSR file).

openssl req -new -nodes -sha256 -keyout jenkins.coolcorp.priv.key -out jenkins.coolcorp.priv.csr -newkey rsa:4096 -subj "/C=FR/ST=Ile-de-France/L=Paris/O=COOLCORP/OU=Infrastructure/CN=jenkins.coolcorp.priv" -reqexts SAN -config <(printf "[req]\ndistinguished_name = req_distinguished_name\n[req_distinguished_name]\n[SAN]\nsubjectAltName=DNS:jenkins.coolcorp.priv")>
Creating the CSR and private key

Click the image to enlarge.

Next, I submit my CSR to my certification authority (in this case, under Windows): certreq -attrib "CertificateTemplate:TPL-SRV-WEB-DEFAULT" -submit .\jenkins.coolcorp.priv.csr

Retrieving the certificate

Click the image to enlarge.

And finally, I retrieve my certificate.

Therefore, in the end, I have a certificate and my key. Both will allow me to create the secret sec-jenkins-cert.

kubectl create secret tls sec-jenkins-cert --cert=jenkins.coolcorp.priv.cer --key=jenkins.coolcorp.priv.key -n prd-jenkins-lan
Creating the secret to host the certificate

Click the image to enlarge.

I won't go into detail here, as each organization often has its own internal method for managing certificates. You can either generate the secret using the key and certificate, or delegate this task to the Cert-Manager tool. For those of you who, like me, have a Windows CA, you can even follow this tutorial to take advantage of automation via the ACME protocol

We can now move on to the ingress itself, which is detailed in this file 02-ing-jenkins-default.yml:

---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: ing-jenkins-default
  namespace: prd-jenkins-lan
  labels:
    environment: prd
    network: lan
    application: jenkins
    tier: default
  annotations:
    traefik.ingress.kubernetes.io/router.entrypoints: web,websecure
    ingressClassName: traefik-lan
    traefik.ingress.kubernetes.io/router.tls: "true"
spec:
  ingressClassName: traefik-lan
  tls:
  - hosts:
    - jenkins.coolcorp.priv
    secretName: sec-jenkins-cert
  rules:
  - host: jenkins.coolcorp.priv
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: jenkins
            port:
              number: 8080

This includes the secret containing the certificate and a reference to the ingress class "traefik-lan" that should be used.

Again, I won't provide further explanations here. The use of Traefik is described here.

Regarding the name of the service jenkins and the port 8080 to which the request should be redirected, this refers to the service created directly by Helm. You can find it using the following command:

kubectl get service -n prd-jenkins-lan

We apply the ingress:

kubectl apply -f 02-ing-jenkins-default.yml
Creating the ingress

Click the image to enlarge.

You can verify access to the Jenkins interface via the desired URL (make sure you have properly configured your DNS record) and using the password of the admin account retrieved previously.

Accessing the interface

Click the image to enlarge.

Now, we have a Jenkins instance deployed on the Kubernetes cluster.

Service account permissions

Before moving further, let's revisit the service account sa-jenkins-agent used by the agent.

This service account currently does not exist in the cluster (we specified in the Helm values file that we did not want to use the default service account).

We need to create it using the file 01-sa-jenkins-agent.yml:

apiVersion: v1
kind: ServiceAccount
metadata:
  name: sa-jenkins-agent
  namespace: prd-jenkins-lan

We will assign a role to this account. This will allow us to precisely define what Jenkins can do on this cluster.

This role is defined in 02-clusterrole-jenkins-agent.yml:

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: clusterrole-jenkins-agent
rules:
- apiGroups: [""]
  resources: ["pods"]
  verbs: ["get", "list", "watch", "create", "delete", "update", "patch"]
- apiGroups: [""]
  resources: ["nodes"]
  verbs: ["get", "list", "watch"]

For the purposes of this tutorial, we are using a simple configuration. We only allow manipulation of pods.

Next, you need to associate this role with the account using the clusterrolebinding object described in the YAML file 03-clusterrolebinding-jenkins-agent.yaml:

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: clusterrolebinding-jenkins-agent
subjects:
- kind: ServiceAccount
  name: sa-jenkins-agent
  namespace: prd-jenkins-lan
roleRef:
  kind: ClusterRole
  name: clusterrole-jenkins-agent
  apiGroup: rbac.authorization.k8s.io
  

I will place these three files in a folder named right, and I can apply them in a single operation:

kubectl apply -f right/
Applying permissions

Click the image to enlarge.

If you wish, you can read this article, which discusses the management of permissions under K8S and the RBAC mechanism associated with it. This will help you better understand the logic behind these three objects.

Validation

Now that everything is ready, there's nothing left to do but validate it all.

To do this, we will use a very basic DEMO pipeline that only lists the pods in the cluster.

Here is the content of the pipeline:

pipeline {
  agent any

  stages {
      stage('Test Kubernetes Access') {
          steps {
              sh 'kubectl get pods -A'
          }
      }
  }
}
Creating the pipeline

Click the image to enlarge.

As mentioned at the beginning of this article, the purpose of this tutorial is not to explain how Jenkins works, but rather to make it capable of running within a Kubernetes cluster and orchestrating tasks there.

We can now run the pipeline.

You will observe that a new pod will be provisioned in the namespace prd-jenkins-lan.

Creating the agent pod

Click the image to enlarge.

This pod represents the agent controlled by the controller. It will load the image that we detailed in the Helm values file and built at the beginning of this article.

Because this image contains kubectl, the get pod command declared in the pipeline can be executed.

The agent will execute the command under the identity of the service account sa-jenkins-agent, which has the role clusterrole-jenkins-agent, allowing it to manipulate pods.

Therefore, we correctly obtain a list of the pods in the cluster as output.

Pipeline output

Click the image to enlarge.

Pipeline output

Click the image to enlarge.

Note that the agent's pod is deleted once the pipeline is finished

Please note that we did not need to specify which cluster to operate on. Since Jenkins is running on the cluster itself, it will use the cluster by default. This integration is possible thanks to the use of the Kubernetes plugin, which is included and configured by default when using Helm.

Conclusion

Jenkins is now deployed on the cluster and capable of performing actions there.

The DEMO pipeline doesn't have much practical value, but it demonstrates the feasibility of Jenkins manipulating objects within the cluster, and does so entirely internally.

It is now possible to leverage Jenkins' modularity and the power of its pipelines to design sequences of tasks that combine both components external to the cluster and the cluster itself. For example, retrieving source code from a Git repository and compiling it in a dedicated pod, executing actions within pods... It's up to each user to find their own use cases! All that remains is to let your imagination run wild!