如何从Jenkins管道Groovy脚本调用资源文件中定义的bash函数? [英] How to invoke bash functions defined in a resource file from a Jenkins pipeline Groovy script?
问题描述
我们使用管道共享库插件来分解代码共同对我们不同的Jenkins管道。
从它的文档中,它为非Groovy文件提供了一个资源
顶级文件夹。由于我们依赖于不同的bash函数,因此我们希望将它们放在一个单独的 .sh
文件中(因此它们也可以被其他进程使用,而不是Jenkins)。
相同的文档告诉我们使用 libraryResource
步骤来加载这些资源文件。我们可以在Groovy脚本中成功调用此方法,并将其资源文件名称作为参数( function.sh
)。但是从这里开始,我们无法找到一种方法来调用 function.sh
中定义的 foofoo
函数。相同的Groovy脚本。
shfoofoo#error:foofoo未定义
我们也尝试先将它的来源如下所示:
shsource function.sh&& foofoo
但它在
source
step,说明没有找到function.sh
。
什么是调用
中定义的bash函数的正确过程function.sh
解决方案 div>根据文档
p>
外部库可能会使用libraryResource步骤从资源/目录
加载附件文件。参数是一个相对路径名,
类似于Java资源加载:
def请求= libraryResource'com / mycorp / pipeline / somelib / request.json'
文件作为字符串加载,适合传递给某些API
或使用writeFile保存到工作区。
建议使用独特的包结构,所以你不会
不小心与另一个库冲突。
我假设以下方法可行
def functions = libraryResource'com / mycorp / pipeline / somelib / functions.sh'
writeFile file:'functions.sh',text :函数
shsource function.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 usinglibraryResource
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 thefoofoo
function defined infunction.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 thatfunction.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屋!
查看全文