繁体   English   中英

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

[英]How to invoke bash functions defined in a resource file from a Jenkins pipeline Groovy script?

我们正在使用管道共享库插件来分解我们不同 Jenkins 管道的通用代码。

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

sh "foofoo"  #error: foofoo is not defined

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

sh "source function.sh && foofoo"

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

什么是调用中定义的bash函数的正确步骤function.sh

根据文档

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

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

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

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

我认为以下将起作用

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

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

def scriptContent = libraryResource "com/corp/pipeline/scripts/${scriptName}"
writeFile file: "${scriptName}", text: scriptContent
sh "chmod +x ${scriptName}"

希望这有帮助!!

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

报价等被搞砸了,它试图替换变量。

它需要逐字转移。

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

sh """
    wget http://some server/path../yourscript.sh
    chmod a+x yourscript.sh
   """

...或直接从 repo 签出脚本并在本地使用它,如下所示:

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 ./
    """
}

...然后稍后运行您的脚本:

sh "./yourscript.sh ...."

在 sh 步骤开始时使用 bash shebang (#!/bin/bash) 告诉 Jenkins 使用 bash,然后像在 bash 中一样加载你的库,例如:

sh '''#!/bin/bash
      . path/to/shared_lib.bash
       myfunc $myarg
    '''

请注意, path/to/shared_lib.bash已在您的 repo 中检查以使其正常工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM