Mass-editing Jenkins Jobs in Views

1 minute read

We might all know, Jenkins arguably is not the nicest piece of software to run in the cloud. Nevertheless, I still need to deal with it sometimes at work.

This time I’m tasked to add Slack notifications to all individual Jenkins Jobs, overriding the global default. It’s pretty trivial if you think of it as just a matter of some clicks and typing in the GUI. Unfortunately, there are too many Jobs to change (more than 20, IIRC) and I’m too lazy to do that manually.

The good news is the specific Jobs that I need to change are already grouped into several Jenkins Views with certain naming patterns. Now let’s leverage Jenkins’ built-in Groovy console with the elegance of language’s functional-ish methods.

import jenkins.plugins.slack.SlackNotifier
import jenkins.plugins.slack.CommitInfoChoice 

def viewRegex = /^\d+\. Running on .*$/
def targetChannel = '#my-notification-channel'

SlackNotifier createNotifier(String room) {
    // the constructor has been deprecated
    // you might need to adjust it on newer version of Slack plugin
    return new SlackNotifier(room: room,
            baseUrl: null,
            teamDomain: null,
            authToken: null,
            botUser: false,
            sendAs: null,
            startNotification: true,
            notifyAborted: true,
            notifyFailure: true,
            notifyNotBuilt: true,
            notifySuccess: true,
            notifyUnstable: true,
            notifyRegression: true,
            notifyBackToNormal: true,
            notifyRepeatedFailure: true,
            includeTestSummary: false,
            includeFailedTests: false,
            commitInfoChoice: CommitInfoChoice.NONE,
            includeCustomMessage: false,
            customMessage: null)
}

Jenkins.instance
    .getViews()
    .findAll { it.name ==~ viewRegex }
    .collectMany {it.getItems()}  
    .each { job ->
        println(job.name)
        def notifier = job.publishersList.find{it instanceof SlackNotifier}
        if (notifier == null) {
            println('> no slack notifier, create new')
            job.publishersList.add(createNotifier(targetChannel))
            job.save()
        } else {
            println('> slack notifier exists, setting target channel')
            notifier.setRoom(targetChannel)
            job.save()
        }
    }

You can change the variable values as needed, and run it on your Jenkins instance on http(s)://jenkins.domain.tld/script.

Cheers!

Mentions

Comments