Bjorn Reppen
Bjorn Reppen

Reputation: 22769

How do I write a Jenkins pipeline function in order to be able to use it as an option?

I would like to add general functionality to my Jenkins pipeline script, similar to what you can do with built-in functions (timestamps, ansiColor):

options {
    timestamps()
    ansiColor 'xterm'
    // failureNotification() <- I want to add this
}

How do I write a function in the script so that it can be used as an option?

Upvotes: 1

Views: 3128

Answers (1)

Spencer Malone
Spencer Malone

Reputation: 1509

Currently I don't believe that's possible with the declarative syntax that you're using. You could write your own Jenkins plugin to do this, but that could get hairy.

If you're willing to use a slightly more complicated syntax, I would look at this blog post: https://jenkins.io/blog/2017/02/15/declarative-notifications/

Essentially, you'll need to create a shared groovy library and use the step from that to manage your notification step. There's a few steps to this:

  1. Create a repository for your shared library. This should have a folder called "vars", which is where your steps and step documentation goes.
  2. Create a step in your shared library. Using camelCase and a groovy extension, create a file name to describe your step. This is what you will call in your Jenkinsfile. Ex: sendFailureNotification.groovy
  3. Within that file, create a function with the name of call. You can use whatever parameters you want. Ex: def call() { }
  4. That call function is your "step logic". In your case, it sounds like you would want to look at the build result and use whatever notification steps you feel are necessary.
  5. Copying from the documentation... 'To setup a "Global Pipeline Library," I navigated to "Manage Jenkins" → "Configure System" in the Jenkins web UI. Once there, under "Global Pipeline Libraries", I added a new library.'
  6. Import your library into your Jenkinsfile like so: @Library('<library name you picked here>')
  7. Now you should be able to call sendFailureNotification() at the end of your Jenkinsfile. Maybe in a post stage like so?:

    post { failure { sendFailureNotification() } }

Upvotes: 2

Related Questions