如何解决如何在 Jenkins Pipeline 中捕获和格式化 Json 响应
我正在 Jenkinsfile 中运行 curl 命令。
df = pd.read_csv(io.StringIO("""burgers double-double triple
condiments ketchup mustard relish ketchup mustard relish
Beep's Burgers 3 3 3 4 5 5
Roadhouse 3 5 2 3 3 2
"""),sep="\t",header=None)
# reconstruct multi-index columns DF...
df1 = df.iloc[2:].rename(columns={0:"burgers"}).set_index("burgers")
df1.columns = pd.MultiIndex.from_arrays([df.iloc[0,1:].fillna(method="ffill").values,df.iloc[1,1:].values],names=df.iloc[0:2,0])
# get required columns based on condiment
df1.loc[:,df1.columns.get_level_values("condiments").isin(["ketchup","mustard"])]
但是我得到了错误
post {
success {
script {
sh '''
|SCORE=+1
|GERRIT_COMMENT="$(cat <<-EOL
|Sonar result was: SUCCESS
|Report: ${Jenkins_URL}/job/${JOB_NAME}/${BUILD_NUMBER}/artifact/report1.txt
|EOL
|)"
|curl -s -u ${apiToken}: ${Sonar_URL}/api/measures/component_tree?ps=100&s=qualifier,name&component=sonarqube&metricKeys=ncloc,bugs,vulnerabilities,code_smells,security_hotspots,coverage,duplicated_lines_density&strategy=children | json_pp -json_opt pretty,canonical > report1.txt
|echo "Voting unsuccessful"
'''.stripMargin().stripIndent()
archiveArtifacts artifacts: 'report1.txt',fingerprint: true
echo 'I Succeeded'
}
}
我无法使用 jq,因为它没有安装并且安装它不是一个选项。
curl 命令在我的终端上运行良好,但在我的 Jenkins 管道中失败。
另外,当我这样做时,它会起作用。
malformed JSON string,neither array,object,number,string or atom,at character offset 0 (before "(end of string)") at /usr/bin/json_pp
但它会在控制台输出中引发警告。
post {
success {
script {
sh '''
|SCORE=+1
|GERRIT_COMMENT="$(cat <<-EOL
|Sonar result was: SUCCESS
|Report: ${Jenkins_URL}/job/${JOB_NAME}/${BUILD_NUMBER}/artifact/report1.txt
|EOL
|)"
|echo "Voting unsuccessful"
'''.stripMargin().stripIndent()
sh """
curl -s -u ${apiToken}: '${Sonar_URL}/api/measures/component_tree?ps=100&s=qualifier,duplicated_lines_density&strategy=children' | json_pp -json_opt pretty,canonical > report1.txt
"""
archiveArtifacts artifacts: 'report1.txt',fingerprint: true
echo 'I Succeeded'
}
}
请问我做错了什么?
在 Jenkins 管道中,您将如何使用 curl 将 JSON 响应正确传递到文件中?
解决方法
我建议尽可能不要使用 shell 脚本。 Shell 脚本不是跨平台的,需要安装额外的工具(例如 curl
)。
在您的情况下,curl
调用可以替换为 httpRequest 步骤。
首先让我们替换 curl
调用并将结果保存在 componentTree.json
文件中:
httpRequest(
url: "${Sonar_URL}/api/measures/component_tree?ps=100&s=qualifier,name&component=sonarqube&metricKeys=ncloc,bugs,vulnerabilities,code_smells,security_hotspots,coverage,duplicated_lines_density&strategy=children",authorization: 'id-of-credentials-which-was-used-to-create-the-apiToken-variable',outputFile: 'componentTree.json'
)
您希望将 JSON 数据格式化为人类可读的格式,因此让我们使用 readJSON 和 writeJSON 步骤:
def json = readJSON(file: 'componentTree.json')
writeJSON(json: json,file: 'report1.txt',pretty: 4)
现在 report1.txt
文件包含缩进 4 格式的 JSON。
componentTree.json
文件只写入和读取一次,所以让我们减少 IO 操作的次数:
def response = httpRequest(
url: "${Sonar_URL}/api/measures/component_tree?ps=100&s=qualifier,authorization: 'id-of-credentials-which-was-used-to-create-the-apiToken-variable'
)
def json = readJSON(text: response.content)
writeJSON(json: json,pretty: 4)
关于警告:
警告:使用 Groovy 字符串插值将机密传递给“sh”,这是不安全的。受影响的参数使用了以下变量:[apiToken]
秘密永远不应该被插入,因为它们可能包含可以解释的特殊字符。示例:
- 我的秘密:
My' https://example.org; cat /etc/passwd; echo \
- 命令:
curl -u '${password}' https://private.server/path/file.txt
插值后调用以下命令:
curl -u 'My' https://example.org; cat /etc/passwd; echo \' https://private.server/path/file.txt
有两种方法可以修复它:
- 如果
apiToken
是环境变量:sh "curl -s -u \$apiToken: '${Sonar_URL}/api/measures/component..."
- 如果
apiToken
是一个 Groovy 变量:withEnv(["CREDENTIALS=${apiToken}"]) { sh "curl -s -u \$CREDENTIALS: '${Sonar_URL}/api/measures/component..." }
在这两种情况下,美元符号 ($
) 在凭据之前被转义,这意味着 shell 脚本将解析它(它将从环境变量中获取)。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。