Common wrapper in Jenkinsfile

核能气质少年 提交于 2019-12-13 00:26:01

问题


I want to add timestamps() and colorizeOutput() features to our pipeline libraries. I find the wrappers {} in Jenkins documentation:

job('example') {
    wrappers {
        colorizeOutput()
        timestamps()
    }
}

I don`t get how to add wrappers to out library which looks like that:

// file ..src/helpers/Builder.groovy

package helpers.sw_main

def doSomething() {
    // some Groovy stuff here
}

def doSomethingElse() {
    // do something else
}

Our job pipeline looks like that:

#!/usr/bin/env groovy

// this is our library with custom methods
@Library('ext-lib')
def builder = new helpers.Builder()

node {
    try {

        stage('Some Stage') {
            builder.doSomething()
        }
    }

    catch (err) {
        throw err
    }
}

So, I want to add timestamps and ansi-colors to every function from library. Of course, I can do it with wrapping every function with

timestamps() {
    colorizeOutput() {
        // function body
    }
}

But its a little stupid.

So can I easily wrap pipeline or library?


回答1:


One solution to your problem is to use Global Variables (/vars/xxxxx.groovy).

To create an own build step, add a Global Variable like /vars/myOwnStep.groovy:

def call(STAGE_NAME, Closure closure) {
    // do something

    // return something if you like to
}

whcih you can call like this

myOwnStep("Step-name") {
    // what ever you want to do
}

in your pipeline script.

Another possibility is to "overwrite" the sh step. Therefore create a file called /vars/sh.groovy with this code:

def call(String script, String encoding=null, String label=null, boolean returnStatus=null, boolean returnStdout=null) {
    timestamps {
        return steps.sh(script: script, endoding: encoding, label: label, returnStatus: returnStatus, returnStdout: returnStdout)
    }
}

def call(Map params = [:]) {
    return call(params.script, params.get('encoding', null), params.get('label', null), params.get('returnStatus', false), params.get('returnStdout', false)) 
}

(This can be done for other steps too, but he parameters have to match.)

I just added a GitHub repository with some examples: https://github.com/datze/jenkins_shared_library (untested!)



来源:https://stackoverflow.com/questions/53409168/common-wrapper-in-jenkinsfile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!