如何从Jenkins管道Groovy脚本调用资源文件中定义的bash函数?

Ad *_*d N 6 bash groovy jenkins jenkins-pipeline

我们使用Pipeline Shared Libraries插件来分解我们不同的Jenkins 管道共有的代码.

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

sh "foofoo"  #error: foofoo is not defined
Run Code Online (Sandbox Code Playgroud)

我们也试图像这样首先采购它:

sh "source function.sh && foofoo"
Run Code Online (Sandbox Code Playgroud)

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

调用中定义的bash函数的正确过程是什么? function.sh

Yur*_* G. 11

根据文件

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

def request = libraryResource 'com/mycorp/pipeline/somelib/request.json'
Run Code Online (Sandbox Code Playgroud)

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

建议使用独特的包结构,以免意外与其他库冲突.

我假设以下内容可行

def functions = libraryResource 'com/mycorp/pipeline/somelib/functions.sh'
writeFile file: 'functions.sh', text: functions
sh "source function.sh && foofoo"
Run Code Online (Sandbox Code Playgroud)

  • 可笑的是,您不能直接使用该文件,而是需要创建该文件的副本。 (4认同)
  • 当您有要加载的脚本列表但不知道文件数量和文件名时该怎么办(人们可能会添加资源并且在管道内部我必须加载所有这些脚本) (2认同)

anu*_*901 6

由于您使用的是 Jenkins Pipelines V2,因此最好为此创建一个共享库。下面的代码将起作用。在写入文件的同时,您还需要为该文件提供执行权限:

def scriptContent = libraryResource "com/corp/pipeline/scripts/${scriptName}"
writeFile file: "${scriptName}", text: scriptContent
sh "chmod +x ${scriptName}"
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!!


Tur*_*Ltd 5

前面的所有答案都是糟糕的解决方案,因为脚本在传输时被解析为文本文件,这会损坏它。

引号等被搞乱了,它试图替换变量。

它需要逐字转移。

唯一的解决方案是将脚本存储在文件服务器上,下载并运行它,例如:

sh """
    wget http://some server/path../yourscript.sh
    chmod a+x yourscript.sh
   """
Run Code Online (Sandbox Code Playgroud)

...或者直接从存储库中签出脚本并在本地使用它,如下所示:

withCredentials([usernamePassword(
    credentialsId: <git access credentials>,
    usernameVariable: 'username',
    passwordVariable: 'password'
)])
{
    sh  """
        git clone http://$username:$password@<your git server>/<shared library repo>.git gittemp
        cd gittemp
        git checkout <the branch in the shared library>
        cd ..
        mv -vf gittemp/<path to file>/yourscript.sh ./
    """
}
Run Code Online (Sandbox Code Playgroud)

...然后运行你的脚本:

sh "./yourscript.sh ...."
Run Code Online (Sandbox Code Playgroud)