Jenkins Pipeline中CURL命令如何传入环境变量token?
解决Jenkins Pipeline中CURL请求体替换环境变量的问题
错误原因
你遇到的语法错误来自两个点:
- Groovy中单引号包裹的字符串不会执行变量插值,所以
${env.authtoken}会被当作字面量传递给shell,而非实际的环境变量值。 - 请求体内部的单引号与外层包裹script的单引号冲突,导致shell解析时出现语法错误。
正确写法示例
写法一:Groovy字符串插值(最直接)
用双引号包裹整个script参数,内部HTTP头的双引号转义,Groovy会自动替换${env.authtoken}为实际值:
sh(script: "curl -H \"Content-Type: application/json\" -d '{ \"token\":\"${env.authtoken}\",\"duration\":10, \"platform\":\"android\", \"available_now\":\"true\"}' https://device.pcloudy.com/api/devices", returnStdout: true)
写法二:单独定义请求体(更易维护)
把JSON请求体提取为Groovy变量,用三重双引号避免转义内部引号,再插入到shell命令中:
def requestBody = """{"token":"${env.authtoken}","duration":10,"platform":"android","available_now":"true"}""" sh(script: "curl -H \"Content-Type: application/json\" -d '${requestBody}' https://device.pcloudy.com/api/devices", returnStdout: true)
写法三:利用shell环境变量
Jenkins会自动将env.authtoken暴露为shell的环境变量$authtoken,直接在shell命令中使用即可:
sh(script: 'curl -H "Content-Type: application/json" -d \'{ "token":"$authtoken","duration":10, "platform":"android", "available_now":"true"}\' https://device.pcloudy.com/api/devices', returnStdout: true)
说明
- 写法一和二依赖Groovy的变量插值,确保
env.authtoken在传递给shell前已经被替换为实际值。 - 写法三直接让shell读取环境变量,适合更复杂的shell场景,无需Groovy提前插值。
内容的提问来源于stack exchange,提问作者JsLearner
相关产品推荐
相关产品推荐

