Customize Jenkins with Groovy Scripts

This document shows how to customize Jenkins with Groovy scripts.

Creating a Secret with data to use in the script

If you need to use confidential data in the script, you have to start by creating a Secret resource to wrap it in.

Kubernetes stores secrets in base64 format, so we have to encode it. Running:

$ echo -n "Hello World" | base64

will produce the following output:


which we can place in a Secret config file as the value of SYSTEM_MESSAGE key.

apiVersion: v1
kind: Secret
type: Opaque
  name: jenkins-conf-secrets
  namespace: <jenkins-namespace>

Now we can apply the secret:

$ kubectl apply -f secret.yaml

Creating JenkinsGroovyScript

We need to create a JenkinsGroovyScript config file containing the configuration we want to apply.

In section we can use Groovy scripts to write configuration code.

Since the secret is already present in the Cluster before we create the JenkinsGroovyScript, we can safely reference its value.

kind: JenkinsGroovyScript
  name: groovy-script
  namespace: <jenkins-namespace>
  labels: <jenkins-cr-name>
    namespace: <jenkins-namespace>
    name: jenkins-conf-secrets
  data: |
    import jenkins.model.Jenkins

    def systemMessage = "Hello " + secrets

    Jenkins jenkins = Jenkins.getInstance()

Now we can safely create this JenkinsGroovyScript.

$ kubectl apply -f jenkins-groovy-script.yaml 

Our Jenkins instance will see it and bind it to previously created Secret, thanks to the reference we provided.

This event will trigger Jenkins Groovy script reconcile loop and our configuration will be applied automatically.

You will see a tiny “Hello World” on the main page.