jenkins

by book-k8sinfra

Helm chartv2.7.1App lts

Open source continuous integration server. It supports multiple SCM tools including CVS, Subversion and Git. It can execute Apache Ant and Apache Maven-based projects as well as arbitrary scripts.

About this chart

Jenkins

Jenkins is the leading open source automation server, Jenkins provides hundreds of plugins to support building, deploying and automating any project.

This chart installs a Jenkins server which spawns agents on Kubernetes utilizing the Jenkins Kubernetes plugin.

Inspired by the awesome work of Carlos Sanchez.

TL;DR

$ helm repo add edu https://iac-source.github.io/helm-charts
$ helm repo update

Get Repo Info

helm repo add jenkins https://charts.jenkins.io
helm repo update

See helm repo for command documentation.

Install Chart

# Helm 3
$ helm install [RELEASE_NAME] jenkins/jenkins [flags]

# Helm 2
$ helm install --name [RELEASE_NAME] jenkins/jenkins [flags]

See configuration below.

See helm install for command documentation.

Uninstall Chart

# Helm 3
$ helm uninstall [RELEASE_NAME]

# Helm 2
# helm delete --purge [RELEASE_NAME]

This removes all the Kubernetes components associated with the chart and deletes the release.

See helm uninstall for command documentation.

Upgrade Chart

# Helm 3 or 2
$ helm upgrade [RELEASE_NAME] jenkins/jenkins [flags]

See helm upgrade for command documentation.

Visit the chart's CHANGELOG to view the chart's release history. For migration between major version check migration guide.

Configuration

See Customizing the Chart Before Installing. To see all configurable options with detailed comments, visit the chart's values.yaml, or run these configuration commands:

# Helm 3
$ helm show values jenkins/jenkins

# Helm 2
$ helm inspect values jenkins/jenkins

For a summary of all configurable options, see VALUES_SUMMARY.md

Configuration as Code

Jenkins Configuration as Code is now a standard component in the Jenkins project. Add a key under configScripts for each configuration area, where each corresponds to a plugin or section of the UI. The keys (prior to | character) are just labels, and can be any value. They are only used to give the section a meaningful name. The only restriction is they must conform to RFC 1123 definition of a DNS label, so they may only contain lowercase letters, numbers, and hyphens. Each key will become the name of a configuration yaml file on the master in /var/jenkins_home/casc_configs (by default) and will be processed by the Configuration as Code Plugin during Jenkins startup. The lines after each | become the content of the configuration yaml file. The first line after this is a JCasC root element, e.g. jenkins, credentials, etc. Best reference is the Documentation link here: https://<jenkins_url>/configuration-as-code.

The example below sets custom systemMessage:

master:
  JCasC:
    configScripts:
      welcome-message: |
        jenkins:
          systemMessage: Welcome to our CI\CD server.

More complex example that creates ldap settings:

master:
  JCasC:
    configScripts:
      ldap-settings: |
        jenkins:
          securityRealm:
            ldap:
              configurations:
                - server: ldap.acme.com
                  rootDN: dc=acme,dc=uk
                  managerPasswordSecret: ${LDAP_PASSWORD}
                  groupMembershipStrategy:
                    fromUserRecord:
                      attributeName: "memberOf"

Keep in mind that default configuration file already contains some values that you won't be able to override under configScripts section.

For example, you can not configure Jenkins URL and System Admin e-mail address like this because of conflictig configuration error.

Incorrect:

master:
  JCasC:
    configScripts:
      jenkins-url: |
        unclassified:
          location:
            url: https://example.com/jenkins
            adminAddress: [email protected]

Correct:

master:
  jenkinsUrl: https://example.com/jenkins
  jenkinsAdminEmail: [email protected]

Further JCasC examples can be found here.

Config as Code With or Without Auto-Reload

Config as Code changes (to master.JCasC.configScripts) can either force a new pod to be created and only be applied at next startup, or can be auto-reloaded on-the-fly. If you set master.sidecars.configAutoReload.enabled to true, a second, auxiliary container will be installed into the Jenkins master pod, known as a "sidecar". This watches for changes to configScripts, copies the content onto the Jenkins file-system and issues a POST to http://<jenkins_url>/reload-configuration-as-code with a pre-shared key. You can monitor this sidecar's logs using command kubectl logs <master_pod> -c jenkins-sc-config -f. If you want to enable auto-reload then you also need to configure rbac as the container which triggers the reload needs to watch the config maps:

master:
  JCasC:
    enabled: true
  sidecars:
    configAutoReload:
      enabled: true
rbac:
  create: true

Allow Limited HTML Markup in User-Submitted Text

Some third-party systems (e.g. GitHub) use HTML-formatted data in their payload sent to a Jenkins webhook (e.g. URL of a pull-request being built). To display such data as processed HTML instead of raw text set master.enableRawHtmlMarkupFormatter to true. This option requires installation of the OWASP Markup Formatter Plugin (antisamy-markup-formatter). This plugin is not installed by default but may be added to master.additionalPlugins.

Mounting Volumes into Agent Pods

Your Jenkins Agents will run as pods, and it's possible to inject volumes where needed:

agent:
  volumes:
  - type: Secret
    secretName: jenkins-mysecrets
    mountPath: /var/run/secrets/jenkins-mysecrets

The supported volume types are: ConfigMap, EmptyDir, HostPath, Nfs, PVC, Secret. Each type supports a different set of configurable attributes, defined by the corresponding Java class.

NetworkPolicy

To make use of the NetworkPolicy resources created by default, install a networking plugin that implements the Kubernetes NetworkPolicy spec.

Install helm chart with network policy enabled by setting networkPolicy.enabled to true.

You can use master.networkPolicy.internalAgents and master.networkPolicy.externalAgents stanzas for fine-grained controls over where internal/external agents can connect from. Internal ones are allowed based on pod labels and (optionally) namespaces, and external ones are allowed based on IP ranges.

Custom Security Realm

master.securityRealm in values can be used to support custom security realm instead of default LegacySecurityRealm. For example, you can add a security realm to authenticate via keycloak:

securityRealm: |-
  <securityRealm class="org.jenkinsci.plugins.oic.OicSecurityRealm" plugin="[email protected]">
    <clientId>testId</clientId>
    <clientSecret>testsecret</clientSecret>
    <tokenServerUrl>https:testurl</tokenServerUrl>
    <authorizationServerUrl>https:testAuthUrl</authorizationServerUrl>
    <userNameField>email</userNameField>
    <scopes>openid email</scopes>
  </securityRealm>

Additional Configs

master.additionalConfig can be used to add additional config files in config.yaml. For example, it can be used to add additional config files for keycloak authentication:

additionalConfig:
  testConfig.txt: |-
    - name: testName
      clientKey: testKey
      clientURL: testUrl

Custom Labels

master.serviceLabels can be used to add custom labels in jenkins-master-svc.yaml. For example:

ServiceLabels:
  expose: true

Persistence

The Jenkins image stores persistence under /var/jenkins_home path of the container. A dynamically managed Persistent Volume Claim is used to keep the data across deployments, by default. This is known to work in GCE, AWS, and minikube. Alternatively, a previously configured Persistent Volume Claim can be used.

It is possible to mount several volumes using persistence.volumes and persistence.mounts parameters. See additional persistence values using configuration commands.

Existing PersistentVolumeClaim

  1. Create the PersistentVolume
  2. Create the PersistentVolumeClaim
  3. Install the chart, setting persistence.existingClaim to PVC_NAME

Storage Class

It is possible to define which storage class to use, by setting persistence.storageClass to [customStorageClass]. If set to a dash (-), dynamic provisioning is disabled. If the storage class is set to null or left undefined (""), the default provisioner is used (gp2 on AWS, standard on GKE, AWS & OpenStack).

RBAC

RBAC is enabled by default. If you want to disable it you will need to set rbac.create to false.

Backup

Adds a backup CronJob for jenkins, along with required RBAC resources. See additional backup values using configuration commands.

Restore From Backup

To restore a backup, you can use the kube-tasks underlying tool called skbn, which copies files from cloud storage to Kubernetes. The best way to do it would be using a Job to copy files from the desired backup tag to the Jenkins pod. See the skbn in-cluster example for more details.

Providing Jobs XML

Jobs can be created (and overwritten) by providing jenkins config xml within the values.yaml file. The keys of the map will become a directory within the jobs directory. The values of the map will become the config.xml file in the respective directory.

Below is an example of a values.yaml file and the directory structure created:

master:
  jobs:
    test-job: |-
      <?xml version='1.0' encoding='UTF-8'?>
      <project>
        <keepDependencies>false</keepDependencies>
        <properties/>
        <scm class="hudson.scm.NullSCM"/>
        <canRoam>false</canRoam>
        <disabled>false</disabled>
        <blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding>
        <blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
        <triggers/>
        <concurrentBuild>false</concurrentBuild>
        <builders/>
        <publishers/>
        <buildWrappers/>
      </project>
    test-job-2: |-
      <?xml version='1.0' encoding='UTF-8'?>
      <project>
        <keepDependencies>false</keepDependencies>
        <properties/>
        <scm class="hudson.scm.NullSCM"/>
        <canRoam>false</canRoam>
        <disabled>false</disabled>
        <blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding>
        <blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
        <triggers/>
        <concurrentBuild>false</concurrentBuild>
        <builders/>
        <publishers/>
        <buildWrappers/>

Jobs Directory Structure

.
├── _test-job-1
|   └── config.xml
├── _test-job-2
|   └── config.xml

Docs taken from https://github.com/jenkinsci/docker/blob/master/Dockerfile: Jenkins is run with user jenkins, uid = 1000. If you bind mount a volume from the host or a data container,ensure you use the same uid

Adding Custom Pod Templates

It is possible to add custom pod templates for the default configured kubernetes cloud. Add a key under agent.podTemplates for each pod template. Each key (prior to | character) is just a label, and can be any value. Keys are only used to give the pod template a meaningful name. The only restriction is they may only contain RFC 1123 \ DNS label characters: lowercase letters, numbers, and hyphens. Each pod template can contain multiple containers. There's no need to add the jnlp container since the kubernetes plugin will automatically inject it into the pod. For this pod templates configuration to be loaded the following values must be set:

master.JCasC.enabled: true
master.JCasC.defaultConfig: true

The example below creates a python pod template in the kubernetes cloud:

agent:
  podTemplates:
    python: |
      - name: python
        label: jenkins-python
        serviceAccount: jenkins
        containers:
          - name: python
            image: python:3
            command: "/bin/sh -c"
            args: "cat"
            ttyEnabled: true
            privileged: true
            resourceRequestCpu: "400m"
            resourceRequestMemory: "512Mi"
            resourceLimitCpu: "1"
            resourceLimitMemory: "1024Mi"

Best reference is https://<jenkins_url>/configuration-as-code/reference#Cloud-kubernetes.

Adding Pod Templates Using additionalAgents

additionalAgents may be used to configure additional kubernetes pod templates. Each additional agent corresponds to agent in terms of the configurable values and inherits all values from agent so you only need to specify values which differ. For example:

agent:
  podName: default
  customJenkinsLabels: default
  # set resources for additional agents to inherit
  resources:
    limits:
      cpu: "1"
      memory: "2048Mi"

additionalAgents:
  maven:
    podName: maven
    customJenkinsLabels: m

Deploy jenkins with OpenTenant

Each tenant gets its own release of this chart, with its own namespace, secrets and domain. The builder below already has jenkins on a Hetzner server. Change the host, add apps from the marketplace, then copy the generated files. Providers and prices are samples, and nothing here is sent anywhere.

  1. Pick a serverConnect Hetzner, OVHcloud or AWS. The builder starts on Hetzner, the cheapest sample rate.
  2. Place the chartjenkins is pinned at v2.7.1 in opentenant.yaml. Drag more apps from the marketplace onto a rack.
  3. ApplySave opentenant.yaml and main.tf from the console, then run the commands below.
# opentenant.yaml, main.tf and dns.tf come from the builder below
opentenant validate opentenant.yaml
terraform init && terraform apply