如何从 Jenkins 管道 Groovy 脚本调用资源文件中定义的 bash 函数? [英] How to invoke bash functions defined in a resource file from a Jenkins pipeline Groovy script?

查看:47
本文介绍了如何从 Jenkins 管道 Groovy 脚本调用资源文件中定义的 bash 函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在使用 Pipeline Shared Libraries 插件来分解代码我们不同的 Jenkins 流水线通用.

从它的文档,它提供了一个resources 非 Groovy 文件的顶级文件夹.由于我们依赖于不同的 bash 函数,我们希望将它们托管在一个单独的 .sh 文件中(因此它们也可以被 Jenkins 之外的其他进程使用).相同的文档告诉我们如何使用 libraryResource 步骤加载这些资源文件.我们可以在 Groovy 脚本中成功调用此方法,将我们的资源文件名作为参数 (function.sh).但是从这里开始,我们无法找到从同一个 Groovy 脚本调用 function.sh 中定义的 foofoo 函数的方法.

sh "foofoo" #error: foofoo 未定义

我们也尝试像这样首先获取它:

sh "源函数.sh && foofoo"

但它在 source 步骤失败,说明未找到 function.sh.

调用 function.sh

中定义的 bash 函数的正确过程是什么

解决方案

根据 文档

<块引用>

外部库可以从 resources/目录加载附属文件使用 libraryResource 步骤.参数是一个相对路径名,类似于 Java 资源加载:

def request = libraryResource 'com/mycorp/pipeline/somelib/request.json'

<块引用>

文件以字符串形式加载,适合传递给某些API或使用 writeFile 保存到工作区.

建议使用独特的包结构,这样您就不会意外与另一个库冲突.

我认为以下方法可行

def functions = libraryResource 'com/mycorp/pipeline/somelib/functions.sh'writeFile 文件:'functions.sh',文本:函数sh "源函数.sh && foofoo"

We are using the Pipeline Shared Libraries plugin to factorize the code common to our different Jenkins pipelines.

From its documentation, it offers a resources top-level folder for non-Groovy files. As we rely on different bash functions, we would like to host them in a separate .sh file (thus they could also be used by other processes than Jenkins). The same documentation tells us about using libraryResource step to load those resource files. We can successfully call this method within our Groovy script, giving it our resource file name as argument (function.sh). But from here, we were not able to find a way to invoke the foofoo function defined in function.sh from the same Groovy script.

sh "foofoo"  #error: foofoo is not defined

We also tried to first source it like this:

sh "source function.sh && foofoo"

But it fails at the source step, stating that function.sh is not found.

What would be the correct procedure to invoke a bash function defined in function.sh

解决方案

According to the documentation

External libraries may load adjunct files from a resources/ directory using the libraryResource step. The argument is a relative pathname, akin to Java resource loading:

def request = libraryResource 'com/mycorp/pipeline/somelib/request.json'

The file is loaded as a string, suitable for passing to certain APIs or saving to a workspace using writeFile.

It is advisable to use an unique package structure so you do not accidentally conflict with another library.

I assume the following will work

def functions = libraryResource 'com/mycorp/pipeline/somelib/functions.sh'
writeFile file: 'functions.sh', text: functions
sh "source function.sh && foofoo"

这篇关于如何从 Jenkins 管道 Groovy 脚本调用资源文件中定义的 bash 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆