在 Jenkinsfile 中将参数传递给 shell 脚本时替换错误

Mol*_*pad 0 jenkins jenkins-groovy jenkins-pipeline

在 Jenkinsfile 中,我尝试通过设置 shell 脚本的 stdOut 来设置环境变量。该脚本包含一个返回 InstanceID 的 AWS 命令​​:

stage('Set InstanceID') {
         steps {
             script {
           env.IID = sh (script: 'scripts/get-node-id.sh "${params.ENVIRONMENT}" "${params.NODE}"', returnStdout: true).trim()
             }
          }
    }
Run Code Online (Sandbox Code Playgroud)

无论我做什么或使用多少个反斜杠来转义引号,都不起作用。我收到严重的替换错误。我也尝试过不加双引号。

如果我在 shell 脚本参数中进行硬编码,它就可以正常运行。

如果我想使用此处的参数值,如何使其工作?

Mic*_*ael 5

Groovy(Jenkinsfile 的语言)和 Bash 共享相同的替换语法。由于您在示例代码中使用单引号,Groovy 替换不起作用(请参阅https://groovy-lang.org/syntax.html#_single_quoted_string)。因此 Bash 将尝试进行替换,但不知道这些变量,因为它们是 Jenkins 参数值。

因此,解决这个问题您需要在脚本中使用双引号并转义其中的双引号(或使用单引号):

stage('Set InstanceID') {
    steps {
        script {
            env.IID = sh (script: "scripts/get-node-id.sh \"${params.ENVIRONMENT}\" \"${params.NODE}\"", returnStdout: true).trim()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)