【问题标题】:Handle string interpolation in shell command in jenkins在詹金斯的shell命令中处理字符串插值
【发布时间】:2021-08-20 18:58:07
【问题描述】:

我们有一个管道,我们需要在其中调用带有Authorization 标头的外部 API,其值来自已预先配置的 Jenkins 机密。

如下实现时,Jenkins 抱怨字符串插值。

withCredentials([string(credentialsId: '<SECRETNAME>', variable: 'Token')]) { 
  sh """curl --location --request POST 'https://abc.example.com/api/endpoint' \
  --header 'Authorization: Bearer ${Token}' \
  --header 'Content-Type: application/json' \
  --data-raw ${payload}""

我们尝试了将单引号 sh 和双引号,但没有任何效果。 这里怎么处理?

【问题讨论】:

    标签: jenkins string-interpolation cloudbees cicd


    【解决方案1】:

    Jenkins 不希望您在代码中插入密码,而是将它们作为环境变量传递给 shell 并让 shell 命令提取它们,这仅适用于加载到 shell 执行环境中的参数。
    在声明性管道中,可以使用 environment 指令将参数和秘密加载到 shell 环境中,对于脚本化管道,可以通过 withCredentials 关键字加载秘密,并且可以通过“withEnv”关键字加载常规参数。

    在您的情况下,您有 withCredentials 步骤加载到环境中的 Token 参数和可能不是的 payload 参数,因此您正在混合两种类型的参数上下文,有关此的更多信息是在Answer for this question 中可用。

    要解决它,您有两种选择。
    第一种选择是将有效负载加载到 shell 环境中并使用单引号 groovy 字符串:

    withEnv(["PAYLOAD=${payload}"]) {
       withCredentials([string(credentialsId: '<SECRETNAME>', variable: 'Token')]) {
           sh '''curl --location --request POST "https://abc.example.com/api/endpoint" \
         --header "Authorization: Bearer $Token" \
         --header "Content-Type: application/json" \
         --data-raw $PAYLOAD'''
       }
    }
    

    第二种选择是将字符串的构造分成两种类型,并用相关方法处理每个部分:

    withCredentials([string(credentialsId: '<SECRETNAME>', variable: 'Token')]) {
       sh '''curl --location --request POST "https://abc.example.com/api/endpoint" \
         --header "Authorization: Bearer $Token" \
         --header "Content-Type: application/json" \
         --data-raw ''' + payload
    }
    

    【讨论】:

    • 感谢您的回复,我忘了说。在这种情况下,我只需要解决Token。我会试一试的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-27
    • 2020-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多