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:

SGVsbG8gd29ybGQ=

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

apiVersion: v1
kind: Secret
type: Opaque
metadata:
  name: jenkins-conf-secrets
  namespace: <jenkins-namespace>
data:
  SYSTEM_MESSAGE: SGVsbG8gd29ybGQ=

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 spec.data 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.

apiVersion: carthago.cloud/v1beta1
kind: JenkinsGroovyScript
metadata:
  name: groovy-script
  namespace: <jenkins-namespace>
  labels:
    carthago.cloud/jenkins: <jenkins-cr-name>
spec:
  secretRef:
    namespace: <jenkins-namespace>
    name: jenkins-conf-secrets
  data: |
    import jenkins.model.Jenkins

    def systemMessage = "Hello " + secrets

    Jenkins jenkins = Jenkins.getInstance()
    jenkins.setSystemMessage(systemMessage)
    jenkins.save()    

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.