本文介绍了Jenkinsfile中的通用包装器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我们的管道库中添加timestamps()colorizeOutput()功能.我在詹金斯wrappers {} >文档:

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
}

我们的工作流程如下:

#!/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
    }
}

因此,我想将时间戳和ansi-colors添加到库中的每个函数中.当然,我可以使用

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
    }
}

但是有点愚蠢.

那么我可以轻松地包装管道或库吗?

So can I easily wrap pipeline or library?

推荐答案

您的问题的一种解决方案是使用全局变量(/vars/xxxxx.groovy).

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

要创建自己的构建步骤,请添加诸如/vars/myOwnStep.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
}

您可以这样打电话给

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

在管道脚本中.

另一种可能性是覆盖" sh 步骤.因此,使用以下代码创建一个名为/vars/sh.groovy的文件:

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.)

我刚刚添加了一些示例的GitHub存储库: https://github.com/datze/jenkins_shared_library(未经测试!)

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

这篇关于Jenkinsfile中的通用包装器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 05:55