【问题标题】:Why cannot embed env vars into curl in Jenkins?为什么不能将 env vars 嵌入到 Jenkins 的 curl 中?
【发布时间】:2018-02-15 08:37:30
【问题描述】:

在 Jenkins 管道中,我无法嵌入环境变量:

sh 'curl -d '{"color":"green","message":"${BUILD_NUMBER}","notify":false,"message_format":"text"}' -H 'Content-Type: application/json' http:blahbah.com'

问题是即使我尝试在每个 ' 和 " 前面使用转义字符 \ 时,目标机器上的输出总是 ${BUILD_NUMBER}

这里应该如何看待正确的 curl 语法?

【问题讨论】:

    标签: curl jenkins environment-variables jenkins-pipeline


    【解决方案1】:

    您的 curl -d 参数命令用单引号括起来。

    curl -d '{"color":"green","message":"${BUILD_NUMBER}","notify":false,"message_format":"text"}' -H 'Content-Type: application/json' http:blahbah.com'
    

    一般情况下(至少在bash"Single quotes won't interpolate anything, but double quotes will (for example variables, backticks, certain \ escapes, etc...)"

    使用 Jenkins Pipelines,您需要小心提供的引号转义。您可以看到记录在 here 的一些奇怪行为。

    处理这种情况的一种方法是在 Groovy 中替换 env.BUILD_NUMBER 值,而不是在 shell 评估中。 Groovy 的triple-quoted strings 也可以帮助进行字符串引用:

    sh """curl -d '{"color":"green","message":"${env.BUILD_NUMBER}","notify":false,"message_format":"text"}' -H 'Content-Type: application/json' http:blahbah.com'"""
    

    我在这里:

    1. """ 包围整个命令。双引号用于 string interpolation,三引号用于简化 curl 命令 JSON 内部的引用。
    2. ${env.BUILD_NUMBER} 被 Groovy 插入到 JSON 正文中

    【讨论】:

    • 它对我不起作用,是否需要任何特定的插件?
    • /tmp/jenkins8342961224735107425.sh: line 26: ${env.BUILD_NUMBER}","description":"Hello: bad substitution Build step 'Execute shell' marked build as failure
    【解决方案2】:

    不要使用${BUILD_NUMBER},而是使用$BUILD_NUMBER。它会成功的。以下是一些示例代码。

    环境变量可以从 Groovy 代码中作为 env.VARNAME 访问 或简单地作为 VARNAME。您也可以写入此类属性(仅 使用环境。前缀):

    env.MYTOOL_VERSION = '1.33'
    node {
      sh '/usr/local/mytool-$MYTOOL_VERSION/bin/start'
    }
    

    pipeline { 
      agent any 
      stages {
        stage('Build') { 
            steps { 
                sh 'echo "Hello World $BUILD_ID"' 
            }
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-08
      • 2021-11-20
      • 1970-01-01
      • 2021-05-23
      • 2022-06-17
      • 2015-09-03
      • 1970-01-01
      相关资源
      最近更新 更多