Jenkins Groovy将变量传递给并行运行

时间:2018-08-08 11:45:42

标签: jenkins groovy jenkins-pipeline

我在弄清楚如何在下面的Jenkins groovy脚本中将一些变量传递到并行运行时遇到问题:

#!/usr/bin/env groovy

def call(version, project) {

    sh '''#!/bin/bash
    [[ ! -e ${WORKSPACE}/target/rpm/${project}/RPMS/ ]] && mkdir -p ${WORKSPACE}/target/rpm/${project}/RPMS/
    (( $(ls ${WORKSPACE}/target/rpm/${project}/RPMS/*.rpm | wc -l) != 0 )) && rm ${WORKSPACE}/target/rpm/${project}/RPMS/*.rpm
    cd ${WORKSPACE}/scripts/fpm_requirements && bundle install && bundle show fpm
    '''

    parallel (
        "package foo": {
            sh '''#!/bin/bash
            export PATH=$PATH:~/bin:~/.gem/ruby/gems
            cd ${WORKSPACE}/scripts/fpm_requirements
            echo Project is ${project}
            echo Version is ${version}
            echo Iteration is $(echo ${version} | cut -d . -f 3)
            '''
        },
        "package bar": {
            sh '''#!/bin/bash
            export PATH=$PATH:~/bin:~/.gem/ruby/gems
            cd ${WORKSPACE}/scripts/fpm_requirements
            echo Project is ${project}
            echo Version is ${version}
            echo Iteration is $(echo ${version} | cut -d . -f 3)
            '''
        }
    )
}

因此,版本和项目变量填充在第一个称为shell的外壳程序中,但是当它们两次并行运行时,它们不会被拉入。

我尝试了几种其他方法来传递它们,但没有一个起作用。

有人对您有帮助的相关想法吗?

1 个答案:

答案 0 :(得分:3)

您应将'''更改为"""。在Groovy中,单引号/三重引号内的字符串不会触发字符串插值,但是单引号/三重双引号内的字符串会触发插值。

因此,Shell脚本中的${version}${project}将被视为Shell上下文中的变量,但实际上它们存在于Groovy上下文中。

有关here中Groovy String的更多信息,选项2下面的内容更适合您的问题。

选项1),使用"""""

   "package foo": {
        sh """#!/bin/bash
        export PATH=\$PATH:~/bin:~/.gem/ruby/gems
        cd \${WORKSPACE}/scripts/fpm_requirements
        echo Project is ${project}
        echo Version is ${version}
        echo Iteration is \$(echo ${version} | cut -d . -f 3)
        """
    },
    "package bar": {
        sh """#!/bin/bash
        export PATH=\$PATH:~/bin:~/.gem/ruby/gems
        cd \${WORKSPACE}/scripts/fpm_requirements
        echo Project is ${project}
        echo Version is ${version}
        echo Iteration is \$(echo ${version} | cut -d . -f 3)
        """
    }

注意:需要在$${WORKSPACE}前面避开$(echo ..),因为我们希望在插值后保留$

选项2),使用''''并将versionproject注入Shell上下文的环境变量中。

def call(version, project) {
    env.version=version
    env.project=project
    // Groovy env api used to inject groovy value into environment variable
    // so that you can refer groovy value later in shell script

    // still use ''' in following code, no need to change
    ...