Jenkins:在 Shell 脚本/CURL 请求中使用变量

Jenkins: Using variable in Shell Script / CURL Request

我将来自早期 HTTP 请求的响应中的一个数字保存到一个变量中。在 CURL 请求中,我需要将这个数字插入到 URL 中,但不知何故它没有被识别为变量。它刚刚被整理出来,这就是为什么 URL 错误并且我收到 400 错误。

script{

// first httpRequest where I get the number from
def response = httpRequest httpMode: 'POST', url:"https://myServer.com", contentType: 'APPLICATION_JSON_UTF8', requestBody: 'myBody'

def props = readJSON text: response.content

def num = props.id[0]       //num stores the number now

sh(Script: curl "https://myServer.com/$num/files" -i -X POST -H Content-Type:multipart/form-data -F file=@JenkinsDemo.txt
}

控制台输出显示 sh 试图达到 https://myServer.com//files ,所以它遗漏了变量。

我也尝试将整个 URL 放入一个变量中并在 curl 中引用,但它也没有被识别。 当然,我尝试了多种输入选项,例如 ${num}、'$num' 等...

有什么想法吗?

编辑

我还收到消息“消息”:“给定的 url 包含恶意字符”,可能是因为 '$'

另一个奇怪的事情:如果我键入 ${props.id[0]} 而不是 ${num} (这没有任何区别,因为它们包含相同的数字)消息变为 “/var/jenkins_home/workspace/Pipeline Test@tmp/durable-153a0829/script.sh: 1: /var/jenkins_home/workspace/Pipeline Test@tmp/durable-153a0829/script.sh: 替换错误”

我解决了这个问题。 curl请求需要用双引号括起来。

sh("curl https....")

双引号可以使用groovy脚本中定义的变量。没有它们,它只会被解释为 java String.