Jenkins 在 sh 中使用脚本变量

Jenkins using script variable inside sh

我试图在 Jenkins 文件的 script 部分声明一个名为 output 的变量,并尝试像这样使用它

stages {
  stage('Deploy') {
    steps {
      script {
 
        output = 'output.log' 
        sh 'cd invoker && mvn clean install && mvn exec:java -Dexec.mainClass="com.company.Deployer" -Dexec.args="qal ${GIT_COMMIT_HASH}" > ../${output}'
        echo readFile(output)
       }
     }        
   }
}

但我收到此错误:script.sh: cannot create ../: Is a directory。这意味着变量没有被填充。我尝试了 ${output}$output 但得到了同样的错误。

我做错了什么?

在groovy单引号('')字符串不支持String Interpolation只有双引号("")字符串(GStrings)支持,因此你的参数没有得到评估。
要解决此问题,只需在 sh 步骤中使用双引号:

 sh "cd invoker && mvn clean install && mvn exec:java -Dexec.mainClass=\"com.company.Deployer\" -Dexec.args=\"qal ${GIT_COMMIT_HASH}\" > ../${output}"

另一种选择是使用声明性管道 environment directive,它是声明性管道语法的一部分,它设置将作为环境变量加载到 shell 执行环境。 所以你可以在 environment 块中定义参数,然后在脚本中使用它与环境变量的 shell 语法:$PARAM.
类似于:

pipeline {
   agent any
   environment {
       OUTPUT_FILE= 'output.log'
   }
   stages {
       stage('Use Global Parameter') {
           steps {
               sh 'cd invoker && mvn clean install && mvn exec:java -Dexec.mainClass="com.company.Deployer" -Dexec.args="qal $GIT_COMMIT_HASH" > ../$OUTPUT_FILE'
               echo readFile(output)
           }
       }
   }
}