如何在jenkins管道groovy脚本中使用json发出curl请求 [英] How to make a curl request with json in jenkins pipeline groovy script

查看:530
本文介绍了如何在jenkins管道groovy脚本中使用json发出curl请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Groovy管道作为Jenkins构建步骤进行New Relic部署API调用.我很麻烦,因为在groovy脚本的shell('sh')命令中同时使用了单引号和双引号.每当执行以下命令时:

I am trying to make a New Relic deployment API call as a Jenkins build step using the Groovy pipeline. I'm having trouble because of the use of both single and double quotes within the shell ('sh') command on the groovy script. Whenever I execute the following:

node {

    //...

    def json = '''\
    {"deployment": {"revision": "v1","user": "me"}}'
    '''

    sh "curl -o /dev/null -s -X POST 'https://api.newrelic.com/v2/applications/[redacted]/deployments.json' \
    -H 'X-Api-Key:[redacted]' \
    -H 'Content-Type: application/json' \
    -d '${json}'"

    // ...
}

我在詹金斯(Jenkins)中收到一条错误消息:

I get an error in Jenkins that says:

/var/lib/jenkins/jobs/[redacted]/workspace@tmp/durable-0f6c52ef/script.sh:第2行:寻找匹配''时出现意外的EOF

/var/lib/jenkins/jobs/[redacted]/workspace@tmp/durable-0f6c52ef/script.sh: line 2: unexpected EOF while looking for matching `''

推荐答案

'json'变量包含一个字符串,该字符串带有一个额外的尾随单引号(').

The 'json' variable contains a string that has an extra trailing single quote (').

在 -d'$ {json}' 我怀疑这会导致数据块中出现额外的(').数据块要求将JSON括在单引号中,因此请确保其中包括了这些引号.

When this is used in -d '${json}'" I suspect it will result in an extra (') in the data block. The data block will require the JSON be enclosed in single quotes so make certain those are included.

您可能不是必须要使用转义字符,否则您可能不是玩过Groovy的人(双关语意味十足的),它可以确保将正确的字符串传递给cURL命令.

Not being a Groovy person (pun intended) you may have to play with escaping characters it ensure that the correct string is passed to the cURL command.

这篇关于如何在jenkins管道groovy脚本中使用json发出curl请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆