Back to Charts

⚠️ DEPRECATED

stable/jenkins/README.md

latest52.1 KB
Original Source

⚠️ DEPRECATED

This chart was moved to https://github.com/jenkinsci/helm-charts

Jenkins Helm Chart

Jenkins master and agent cluster utilizing the Jenkins Kubernetes plugin

Inspired by the awesome work of Carlos Sanchez mailto:[email protected]

Chart Details

This chart will do the following:

  • 1 x Jenkins Master with port 8080 exposed on an external LoadBalancer
  • All using Kubernetes Deployments

Installing the Chart

To install the chart with the release name my-release:

bash
$ helm install my-release stable/jenkins

Upgrading an existing Release to a new major version

A major chart version change (like v0.40.0 -> v1.0.0) indicates that there is an incompatible breaking change needing manual actions.

2.0.0 Configuration as Code now default + container does not run as root anymore

Configuration as Code new default

Configuration is done via Jenkins Configuration as Code Plugin by default. That means that changes in values which result in a configuration change are always applied. In contrast the XML configuration was only applied during the first start and never altered.

:exclamation::exclamation::exclamation: Attention: This also means if you manually altered configuration then this will most likely be reset to what was configured by default. It also applies to securityRealm and authorizationStrategy as they are also configured using configuration as code. :exclamation::exclamation::exclamation:

Image does not run as root anymore

It's not recommended to run containers in Kubernetes as root.

:exclamation: Attention: If you had not configured a different user before then you need to ensure that your image supports the user and group id configured and also manually change permissions of all files so that Jenkins is still able to use them.

Summary of updated values

As version 2.0.0 only updates default values and nothing else it's still possible to migrate to this version and opt out of some or all new defaults. All you have to do is ensure the old values are set in your installation.

Here we show which values have changed and the previous default values:

yaml
master:
  enableXmlConfig: false  # was true
  runAsUser: 1000         # was unset before
  fsGroup: 1000           # was unset before
  JCasC:
    enabled: true         # was false
    defaultConfig: true   # was false
  sidecars:
    configAutoReload:
      enabled: true       # was false

Migration steps

Migration instructions heavily depend on your current setup. So think of the list below more as a general guideline of what should be done.

  • Ensure that the Jenkins image you are using contains a user with id 1000 and a group with the same id. That's the case for jenkins/jenkins:lts image, which the chart uses by default

  • Make a backup of your existing installation especially the persistent volume

  • Ensure that you have the configuration as code plugin installed

  • Export your current settings via the plugin: Manage Jenkins -> Configuration as Code -> Download Configuration

  • prepare your values file for the update e.g. add additional configuration as code setting that you need. The export taken from above might be a good starting point for this. In addition the demos from the plugin itself are quite useful.

  • test drive those setting on a separate installation

  • Put Jenkins to Quiet Down mode so that it does not accept new jobs <JENKINS_URL>/quietDown

  • change permissions of all files and folders to the new user and group id

    shell
    kubectl exec -it <jenkins_pod> -c jenkins /bin/bash
    chown -R 1000:1000 /var/jenkins_home
    
  • Update Jenkins

1.0.0

Breaking changes:

As a result of the label changes also the selectors of the deployment have been updated. Those are immutable so trying an updated will cause an error like:

Error: Deployment.apps "jenkins" is invalid: spec.selector: Invalid value: v1.LabelSelector{MatchLabels:map[string]string{"app.kubernetes.io/component":"jenkins-master", "app.kubernetes.io/instance":"jenkins"}, MatchExpressions:[]v1.LabelSelectorRequirement(nil)}: field is immutable

In order to upgrade, delete the Jenkins Deployment before upgrading:

kubectl delete deploy jenkins

Configuration

The following tables list the configurable parameters of the Jenkins chart and their default values.

Jenkins Master

ParameterDescriptionDefault
checkDeprecationChecks for deprecated values usedtrue
clusterZoneOverride the cluster name for FQDN resolvingcluster.local
nameOverrideOverride the resource name prefixjenkins
fullnameOverrideOverride the full resource namesjenkins-{release-name} (or jenkins if release-name is jenkins)
namespaceOverrideOverride the deployment namespaceNot set (Release.Namespace)
master.componentNameJenkins master namejenkins-master
master.enableXmlConfigenables configuration done via XML filesfalse
master.testEnabledCan be used to disable rendering test resources when using helm templatetrue

Jenkins Configuration as Code (JCasC)

ParameterDescriptionDefault
master.JCasC.enabledWhether Jenkins Configuration as Code is enabled or nottrue
master.JCasC.defaultConfigEnables default Jenkins configuration via configuration as code plugintrue
master.JCasC.configScriptsList of Jenkins Config as Code scripts{}
master.JCasC.securityRealmJenkins Config as Code for Security Realmlegacy
master.JCasC.authorizationStrategyJenkins Config as Code for Authorization StrategyloggedInUsersCanDoAnything
master.sidecars.configAutoReloadJenkins Config as Code auto-reload settings
master.sidecars.configAutoReload.enabledJenkins Config as Code auto-reload settings (Attention: rbac needs to be enabled otherwise the sidecar can't read the config map)true
master.sidecars.configAutoReload.imageImage which triggers the reloadkiwigrid/k8s-sidecar:0.1.144
master.sidecars.configAutoReload.reqRetryConnectHow many connection-related errors to retry on10
master.sidecars.configAutoReload.envEnvironment variables for the Jenkins Config as Code auto-reload containerNot set

Jenkins Configuration Files & Scripts

ParameterDescriptionDefault
master.initScriptsList of Jenkins init scripts[]
master.overwriteConfigReplace init scripts and config w/ ConfigMap on bootfalse
master.credentialsXmlSecretKubernetes secret that contains a 'credentials.xml' fileNot set
master.secretsFilesSecretKubernetes secret that contains 'secrets' filesNot set
master.jobsJenkins XML job configs{}
master.overwriteJobsReplace jobs w/ ConfigMap on bootfalse

Jenkins Global Security

ParameterDescriptionDefault
master.useSecurityUse basic securitytrue
master.disableRememberMeDisable use of remember mefalse
master.securityRealmJenkins XML for Security RealmXML for LegacySecurityRealm
master.authorizationStrategyJenkins XML for Authorization StrategyXML for FullControlOnceLoggedInAuthorizationStrategy
master.enableRawHtmlMarkupFormatterEnable HTML parsing using (see below)false
master.markupFormatterYaml of the markup formatter to useplainText
master.disabledAgentProtocolsDisabled agent protocolsJNLP-connect JNLP2-connect
master.csrf.defaultCrumbIssuer.enabledEnable the default CSRF Crumb issuertrue
master.csrf.defaultCrumbIssuer.proxyCompatabilityEnable proxy compatibilitytrue
master.cliEnable CLI over remotingfalse

Jenkins Global Settings

ParameterDescriptionDefault
master.numExecutorsSet Number of executors0
master.executorModeSet executor mode of the Jenkins node. Possible values are: NORMAL or EXCLUSIVENORMAL
master.customJenkinsLabelsAppend Jenkins labels to the master{}
master.jenkinsHomeCustom Jenkins home path/var/jenkins_home
master.jenkinsRefCustom Jenkins reference path/usr/share/jenkins/ref
master.jenkinsAdminEmailEmail address for the administrator of the Jenkins instanceNot set
master.jenkinsUrlProtocolSet protocol for JenkinsLocationConfiguration.xmlSet to https if Master.ingress.tls, http otherwise
master.jenkinsUriPrefixRoot Uri Jenkins will be served onNot set

Jenkins In-Process Script Approval

ParameterDescriptionDefault
master.scriptApprovalList of groovy functions to approve[]

Jenkins Plugins

ParameterDescriptionDefault
master.installPluginsList of Jenkins plugins to install. If you don't want to install plugins set it to []kubernetes:1.18.2 workflow-aggregator:2.6 credentials-binding:1.19 git:3.11.0 workflow-job:2.33
master.additionalPluginsList of Jenkins plugins to install in addition to those listed in master.installPlugins[]
master.initializeOnceInitialize only on first install. Ensures plugins do not get updated inadvertently. Requires persistence.enabled to be set to true.false
master.overwritePluginsOverwrite installed plugins on start.false
master.overwritePluginsFromImageKeep plugins that are already installed in the master image.true

Jenkins Kubernetes Plugin

ParameterDescriptionDefault
master.slaveListenerPortListening port for agents50000
master.slaveHostPortHost port to listen for agentsNot set
master.slaveKubernetesNamespaceNamespace in which the Kubernetes agents should be launchedNot set
master.slaveDefaultsProviderTemplateThe name of the pod template to use for providing default valuesNot set
master.slaveJenkinsUrlOverrides the Kubernetes Jenkins URLNot set
master.slaveJenkinsTunnelOverrides the Kubernetes Jenkins tunnelNot set
master.slaveConnectTimeoutThe connection timeout in seconds for connections to Kubernetes API. Minimum value is 5.5
master.slaveReadTimeoutThe read timeout in seconds for connections to Kubernetes API. Minimum value is 15.15
master.slaveListenerServiceTypeDefines how to expose the slaveListener serviceClusterIP
master.slaveListenerLoadBalancerIPStatic IP for the slaveListener LoadBalancerNot set

Kubernetes Deployment & Service

ParameterDescriptionDefault
master.imageMaster image namejenkins/jenkins
master.tagMaster image taglts
master.imagePullPolicyMaster image pull policyAlways
master.imagePullSecretNameMaster image pull secretNot set
master.resourcesResources allocation (Requests and Limits){requests: {cpu: 50m, memory: 256Mi}, limits: {cpu: 2000m, memory: 4096Mi}}
master.initContainerEnvEnvironment variables for Init ContainerNot set
master.containerEnvEnvironment variables for Jenkins ContainerNot set
master.usePodSecurityContextEnable pod security context (must be true if runAsUser or fsGroup are set)true
master.runAsUseruid that jenkins runs with1000
master.fsGroupuid that will be used for persistent volume1000
master.hostAliasesAliases for IPs in /etc/hosts[]
master.serviceAnnotationsService annotations{}
master.serviceTypek8s service typeClusterIP
master.clusterIPk8s service clusterIPNot set
master.servicePortk8s service port8080
master.targetPortk8s target port8080
master.nodePortk8s node portNot set
master.jmxPortOpen a port, for JMX statsNot set
master.extraPortsOpen extra ports, for other uses[]
master.loadBalancerSourceRangesAllowed inbound IP addresses0.0.0.0/0
master.loadBalancerIPOptional fixed external IPNot set
master.deploymentLabelsCustom Deployment labelsNot set
master.serviceLabelsCustom Service labelsNot set
master.podLabelsCustom Pod labelsNot set
master.nodeSelectorNode labels for pod assignment{}
master.affinityAffinity settings{}
master.schedulerNameKubernetes scheduler nameNot set
master.terminationGracePeriodSecondsSet TerminationGracePeriodSecondsNot set
master.tolerationsToleration labels for pod assignment[]
master.podAnnotationsAnnotations for master pod{}
master.deploymentAnnotationsAnnotations for master deployment{}
master.lifecycleLifecycle specification for master-containerNot set
master.priorityClassNameThe name of a priorityClass to apply to the master podNot set
master.admin.existingSecretThe name of an existing secret containing the admin credentials.""
master.admin.userKeyThe key in the existing admin secret containing the username.jenkins-admin-user
master.admin.passwordKeyThe key in the existing admin secret containing the password.jenkins-admin-password
master.customInitContainersCustom init-container specification in raw-yaml formatNot set
master.sidecars.otherConfigures additional sidecar container(s) for Jenkins master[]

Kubernetes Health Probes

ParameterDescriptionDefault
master.healthProbesEnable k8s liveness and readiness probestrue
master.healthProbesLivenessTimeoutSet the timeout for the liveness probe5
master.healthProbesReadinessTimeoutSet the timeout for the readiness probe5
master.healthProbeLivenessPeriodSecondsSet how often (in seconds) to perform the liveness probe10
master.healthProbeReadinessPeriodSecondsSet how often (in seconds) to perform the readiness probe10
master.healthProbeLivenessFailureThresholdSet the failure threshold for the liveness probe5
master.healthProbeReadinessFailureThresholdSet the failure threshold for the readiness probe3
master.healthProbeLivenessInitialDelaySet the initial delay for the liveness probe90
master.healthProbeReadinessInitialDelaySet the initial delay for the readiness probe60

Kubernetes Ingress

ParameterDescriptionDefault
master.ingress.enabledEnables ingressfalse
master.ingress.apiVersionIngress API versionextensions/v1beta1
master.ingress.hostNameIngress host nameNot set
master.ingress.resourceRootUrlHostname to serve assets fromNot set
master.ingress.annotationsIngress annotations{}
master.ingress.labelsIngress labels{}
master.ingress.pathIngress pathNot set
master.ingress.pathsOverride for the default Ingress paths[]
master.ingress.tlsIngress TLS configuration[]

GKE BackendConfig

ParameterDescriptionDefault
master.backendconfig.enabledEnables backendconfigfalse
master.backendconfig.apiVersionbackendconfig API versionextensions/v1beta1
master.backendconfig.namebackendconfig nameNot set
master.backendconfig.annotationsbackendconfig annotations{}
master.backendconfig.labelsbackendconfig labels{}
master.backendconfig.specbackendconfig spec{}

OpenShift Route

ParameterDescriptionDefault
master.route.enabledEnables openshift routefalse
master.route.annotationsRoute annotations{}
master.route.labelsRoute labels{}
master.route.pathRoute pathNot set

Prometheus

ParameterDescriptionDefault
master.prometheus.enabledEnables prometheus service monitorfalse
master.prometheus.serviceMonitorAdditionalLabelsAdditional labels to add to the service monitor object{}
master.prometheus.serviceMonitorNamespaceCustom namespace for serviceMonitorNot set (same ns where is Jenkins being deployed)
master.prometheus.scrapeIntervalHow often prometheus should scrape metrics60s
master.prometheus.scrapeEndpointThe endpoint prometheus should get metrics from/prometheus
master.prometheus.alertingrulesArray of prometheus alerting rules[]
master.prometheus.alertingRulesAdditionalLabelsAdditional labels to add to the prometheus rule object{}

HTTPS Keystore

ParameterDescriptionDefault
master.httpsKeyStore.enableEnables https keystore on jenkins masterfalse
master.httpsKeyStore.jenkinsHttpsJksSecretNameName of the secret that already has ssl keystore``
master.httpsKeyStore.httpPortHttp Port that Jenkins should listen on along with https, it also serves liveness and readiness probs port. When https keystore is enabled servicePort and targetPort will be used as https port8081
master.httpsKeyStore.pathPath of https keystore file/var/jenkins_keystore
master.httpsKeyStore.fileNameJenkins keystore filename which will apear under master.httpsKeyStore.pathkeystore.jks
master.httpsKeyStore.passwordJenkins keystore passwordpassword
master.httpsKeyStore.jenkinsKeyStoreBase64EncodedBase64 ecoded Keystore content. Keystore must be converted to base64 then being pasted herea self signed cert

Kubernetes Secret

ParameterDescriptionDefault
master.adminUserAdmin username (and password) created as a secret if useSecurity is trueadmin
master.adminPasswordAdmin password (and user) created as a secret if useSecurity is trueRandom value

Kubernetes NetworkPolicy

ParameterDescriptionDefault
networkPolicy.enabledEnable creation of NetworkPolicy resources.false
networkPolicy.apiVersionNetworkPolicy ApiVersionnetworking.k8s.io/v1
networkPolicy.internalAgents.allowedAllow internal agents (from the same cluster) to connect to master. Agent pods would be filtered based on PodLabels.false
networkPolicy.internalAgents.podLabelsA map of labels (keys/values) that agents pods must have to be able to connect to master.{}
networkPolicy.internalAgents.namespaceLabelsA map of labels (keys/values) that agents namespaces must have to be able to connect to master.{}
networkPolicy.externalAgents.ipCIDRThe IP range from which external agents are allowed to connect to master.``
networkPolicy.externalAgents.exceptA list of IP sub-ranges to be excluded from the whitelisted IP range.[]

Kubernetes RBAC

ParameterDescriptionDefault
rbac.createWhether RBAC resources are createdtrue
rbac.readSecretsWhether the Jenkins service account should be able to read Kubernetes secretsfalse

Kubernetes ServiceAccount - Master

ParameterDescriptionDefault
serviceAccount.namename of the ServiceAccount to be used by access-controlled resourcesautogenerated
serviceAccount.createConfigures if a ServiceAccount with this name should be createdtrue
serviceAccount.annotationsConfigures annotation for the ServiceAccount{}

Kubernetes ServiceAccount - Agent

ParameterDescriptionDefault
serviceAccountAgent.namename of the agent ServiceAccount to be used by access-controlled resourcesautogenerated
serviceAccountAgent.createConfigures if an agent ServiceAccount with this name should be createdfalse
serviceAccountAgent.annotationsConfigures annotation for the agent ServiceAccount{}

Deprecated

ParameterDescriptionDefault
master.customConfigMapDeprecated: Use a custom ConfigMapfalse
master.additionalConfigDeprecated: Add additional config files{}

Some third-party systems, e.g. GitHub, use HTML-formatted data in their payload sent to a Jenkins webhooks, 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 OWASP Markup Formatter Plugin (antisamy-markup-formatter). The plugin is not installed by default, please update master.installPlugins.

Jenkins Agent(s)

ParameterDescriptionDefault
agent.enabledEnable Kubernetes plugin jnlp-agent podTemplatetrue
agent.containerCapMaximum number of agent10

Pod Configuration

ParameterDescriptionDefault
agent.podNameAgent Pod base nameNot set
agent.customJenkinsLabelsAppend Jenkins labels to the agent{}
agent.envVarsEnvironment variables for the agent Pod[]
agent.idleMinutesAllows the Pod to remain active for reuse0
agent.imagePullSecretNameAgent image pull secretNot set
agent.nodeSelectorNode labels for pod assignment{}
agent.slaveConnectTimeoutTimeout in seconds for an agent to be online100
agent.volumesAdditional volumes[]
agent.yamlTemplateThe raw yaml of a Pod API Object to merge into the agent specNot set
agent.yamlMergeStrategyDefines how the raw yaml field gets merged with yaml definitions from inherited pod templatesoverride

Side Container Configuration

ParameterDescriptionDefault
agent.sideContainerNameSide container name in agentjnlp
agent.imageAgent image namejenkins/inbound-agent
agent.tagAgent image tag4.3-4
agent.alwaysPullImageAlways pull agent container image before buildfalse
agent.privilegedAgent privileged containerfalse
agent.resourcesResources allocation (Requests and Limits){requests: {cpu: 512m, memory: 512Mi}, limits: {cpu: 512m, memory: 512Mi}}
agent.runAsUserConfigure container userNot set
agent.runAsGroupConfigure container groupNot set
agent.commandExecuted command when side container startsNot set
agent.argsArguments passed to executed command${computer.jnlpmac} ${computer.name}
agent.TTYEnabledAllocate pseudo tty to the side containerfalse
agent.workingDirConfigure working directory for default agent/home/jenkins

Other

ParameterDescriptionDefault
agent.podTemplatesConfigures extra pod templates for the default kubernetes cloud{}
additionalAgentsConfigure additional agents which inherit values from agent{}

Specify each parameter using the --set key=value[,key=value] argument to helm install.

Alternatively, a YAML file that specifies the values for the parameters can be provided while installing the chart. For example,

bash
$ helm install my-release -f values.yaml stable/jenkins

Tip: You can use the default values.yaml

Mounting volumes into your Agent pods

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

yaml
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.

For Kubernetes v1.5 & v1.6, you must also turn on NetworkPolicy by setting the DefaultDeny namespace annotation. Note: this will enforce policy for all pods in the namespace:

kubectl annotate namespace default "net.beta.kubernetes.io/network-policy={\"ingress\":{\"isolation\":\"DefaultDeny\"}}"

Install helm chart with network policy enabled:

$ helm install stable/jenkins --set networkPolicy.enabled=true

You can use master.networkPolicy.internalAgents and master.networkPolicy.externalAgents stanzas to 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.

Adding customized securityRealm

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.

yaml
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>

Adding 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.

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

Adding customized labels

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

yaml
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.

Persistence Values

ParameterDescriptionDefault
persistence.enabledEnable the use of a Jenkins PVCtrue
persistence.existingClaimProvide the name of a PVCnil
persistence.storageClassStorage class for the PVCnil
persistence.annotationsAnnotations for the PVC{}
persistence.accessModeThe PVC access modeReadWriteOnce
persistence.sizeThe size of the PVC8Gi
persistence.subPathSubPath for jenkins-home mountnil
persistence.volumesAdditional volumesnil
persistence.mountsAdditional mountsnil

Existing PersistentVolumeClaim

  1. Create the PersistentVolume
  2. Create the PersistentVolumeClaim
  3. Install the chart
bash
$ helm install my-release --set persistence.existingClaim=PVC_NAME stable/jenkins

Storage Class

It is possible to define which storage class to use:

bash
$ helm install my-release --set persistence.storageClass=customStorageClass stable/jenkins

If set to a dash (-, as in persistence.storageClass=-), the dynamic provision is disabled.

If the storage class is set to null or left undefined (persistence.storageClass=), the default provisioner is used (gp2 on AWS, standard on GKE, AWS & OpenStack).

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 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, eg jenkins, credentials, etc. Best reference is the Documentation link here: https://<jenkins_url>/configuration-as-code. The example below creates ldap settings:

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

Further JCasC examples can be found here.

Config as Code with and 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 choose master.sidecars.autoConfigReload.enabled: 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.

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

RBAC

RBAC is enabled by default if you want to disable it you will need to do the following:

  • helm install stable/jenkins --set rbac.create=false

Backup

Adds a backup CronJob for jenkins, along with required RBAC resources.

Backup Values

ParameterDescriptionDefault
backup.enabledEnable the use of a backup CronJobfalse
backup.scheduleSchedule to run jobs0 2 * * *
backup.labelsBackup pod labels{}
backup.annotationsBackup pod annotations{}
backup.image.repoBackup image repositorymaorfr/kube-tasks
backup.image.tagBackup image tag0.2.0
backup.extraArgsAdditional arguments for kube-tasks[]
backup.existingSecretEnvironment variables to add to the cronjob container{}
backup.existingSecret.*Specify the secret name containing the AWS or GCP credentialsjenkinsaws
backup.existingSecret.*.awsaccesskeysecretKeyRef.key used for AWS_ACCESS_KEY_IDjenkins_aws_access_key
backup.existingSecret.*.awssecretkeysecretKeyRef.key used for AWS_SECRET_ACCESS_KEYjenkins_aws_secret_key
backup.existingSecret.*.gcpcredentialsMounts secret as volume and sets GOOGLE_APPLICATION_CREDENTIALScredentials.json
backup.envBackup environment variables[]
backup.resourcesBackup CPU/Memory resource requests/limitsMemory: 1Gi, CPU: 1
backup.destinationDestination to store backup artifactss3://jenkins-data/backup

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.

Run Jenkins as non root user

The default settings of this helm chart let Jenkins run as root user with uid 0. Due to security reasons you may want to run Jenkins as a non root user. Fortunately the default jenkins docker image jenkins/jenkins contains a user jenkins with uid 1000 that can be used for this purpose.

Simply use the following settings to run Jenkins as jenkins user with uid 1000.

yaml
master:
  runAsUser: 1000
  fsGroup: 1000

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:

values.yaml

yaml
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/>

Directory structure of jobs directory

.
├── _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.

yaml
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,

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

additionalAgents:
  maven:
    podName: maven
    customJenkinsLabels: maven
    # An example of overriding the jnlp container
    # sideContainerName: jnlp
    image: jenkins/jnlp-agent-maven
    tag: latest
  python:
    podName: python
    customJenkinsLabels: python
    sideContainerName: python
    image: python
    tag: "3"
    command: "/bin/sh -c"
    args: "cat"
    TTYEnabled: true

Running behind a forward proxy

The master pod uses an Init Container to install plugins etc. If you are behind a corporate proxy it may be useful to set master.initContainerEnv to add environment variables such as http_proxy, so that these can be downloaded.

Additionally, you may want to add env vars for the Jenkins container, and the JVM (master.javaOpts).

yaml
master:
  initContainerEnv:
    - name: http_proxy
      value: "http://192.168.64.1:3128"
    - name: https_proxy
      value: "http://192.168.64.1:3128"
    - name: no_proxy
      value: ""
  containerEnv:
    - name: http_proxy
      value: "http://192.168.64.1:3128"
    - name: https_proxy
      value: "http://192.168.64.1:3128"
  javaOpts: >-
    -Dhttp.proxyHost=192.168.64.1
    -Dhttp.proxyPort=3128
    -Dhttps.proxyHost=192.168.64.1
    -Dhttps.proxyPort=3128

Custom ConfigMap

The following configuration method is deprecated and will be removed in an upcoming version of this chart. We recommend you use Jenkins Configuration as Code to configure instead. When creating a new parent chart with this chart as a dependency, the customConfigMap parameter can be used to override the default config.xml provided. It also allows for providing additional xml configuration files that will be copied into /var/jenkins_home. In the parent chart's values.yaml, set the jenkins.master.customConfigMap value to true like so

yaml
jenkins:
  master:
    customConfigMap: true

and provide the file templates/config.tpl in your parent chart for your use case. You can start by copying the contents of config.yaml from this chart into your parent charts templates/config.tpl as a basis for customization. Finally, you'll need to wrap the contents of templates/config.tpl like so:

yaml
{{- define "override_config_map" }}
    <CONTENTS_HERE>
{{ end }}

Https keystore configuration

This configuration enable jenkins to use keystore inorder to serve https: https://wiki.jenkins.io/pages/viewpage.action?pageId=135468777

Here is the value file section related to keystore configuration.

Keystore itself should be placed in front of jenkinsKeyStoreBase64Encoded key and in base64 encoded format. To achive that after having keystore.jks file simply do this: cat keystore.jks | base64 and paste the output in front of jenkinsKeyStoreBase64Encoded .

After enabling httpsKeyStore.enable make sure that httpPort and targetPort are not the same as targetPort will serve https.

Do not set master.httpsKeyStore.httpPort to -1 because it will cause readiness and liveliness prob to fail.

If you already have a kubernetes secret that has keystore and its password you can specify its' name in front of jenkinsHttpsJksSecretName, You need to remember that your secret should have proper data key names jenkins-jks-file and https-jks-password.

yaml
master:
   httpsKeyStore:
       enable: true
       jenkinsHttpsJksSecretName: ''
       httpPort: 8081
       path: "/var/jenkins_keystore"
       fileName: "keystore.jks"
       password: "changeit"
       jenkinsKeyStoreBase64Encoded: ''