如何在windows slave上从groovy文件运行复杂的curl命令(带json)



我有下面的CURL(用于bitbucket标记(命令,其中包括json内容(--data(。它在Windows上从我的CMD工作(当然我用伪字符串替换了敏感信息(:

curl -L -k --location-trusted -X POST --user "TEST58:123@456!" https://git.devops.test/rest/api/1.0/projects/M800/repos/test/tags
--data "{"name": "test","startPoint": "1234ca34f3624fea0e0a2134f123da11ae01","message": "test"}"
-H "X-Atlassian-Token: no-check" -H "Content-Type: application/json"

现在,我正试图在windows从机上运行的jenkinsfile.groovy文件上运行此命令。这是经过一些尝试后的当前命令和最新的异常:

def body = "{name: ${testTag}, startPoint: ${commitHash}, message: ${message}}"
withCredentials([usernamePassword(usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD', credentialsId: "TEST")]) {
bat(returnStdout: true, script: "curl -L -k --location-trusted -X POST --user "${USERNAME}:${PASSWORD}" "https://git.devops.test/rest/api/1.0/projects/${projectKey}/repos/${repoName}/tags" -d "${body}" -H "X-Atlassian-Token: no-check" -H "Content-Type: application/json"")
} 

错误:

{"errors":[{"context":null,"message":"Unexpected character ('n' (code 110)): was expecting double-quote to start field namen at [Source: com.atlassian.stash.internal.web.util.web.CountingServletInputStream@447c81dc; line: 1, column: 3]","exceptionName":"org.codehaus.jackson.JsonParseException"}]}

你能指出哪里出了问题吗?它是由jsongroovywindows混合而成,令人困惑

更新

根据以下建议和工作解决方案,这是jenkisfile.groovy:的最终结构

import groovy.json.JsonOutput
node ("win") {    
stage("tag") {     
def testTag = "testTag"
def message = "test"
def stdout = bat(returnStdout: true, script: "git rev-parse HEAD").trim()
def commitHash = stdout.readLines().drop(1).join(" ")

def body = [
name: "${testTag}",
startPoint: "${commitHash}",
message: "${message}",
]

body = JsonOutput.toJson(body) // normal json
body = JsonOutput.toJson(body) // escaped json - escape all doublequotes

def url = "https://git.devops.test/rest/api/1.0/projects/${projectKey}/repos/${repoName}/tags"
withCredentials([usernamePassword(usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD', credentialsId: "TEST")]) {
def cmd = """curl -L -k --location-trusted -X POST --user "${USERNAME}:${PASSWORD}" "${url}" -H "accept: application/json" --data ${body} -H "Content-Type: application/json" -H "X-Atlassian-Token: no-check" """
bat(script:cmd, returnStdout:true)    
}
}
}

def body = [
name: 'aaa',
startPoint: 123,
message: "test",
]
body = JsonOutput.toJson(body) // normal json
body = JsonOutput.toJson(body) // escaped json - escape all doublequotes
def url = "https://httpbin.org/post"
def cmd = """curl -L -k --location-trusted -X POST --user "TEST58:123@456!" "$url" -H "accept: application/json" --data $body  -H "Content-Type: application/json" -H "X-Atlassian-Token: no-check" """
println cmd
bat(script:cmd, returnStdout:true)

最新更新