我有以下 JSON:
{
"defaultOptions" : {
"environmentVariableEntries" : [
{
"key" : "OS_VERSION",
"value" : "13"
}
]
}
}
在 Jenkins 上,我有一个步骤写入一些环境变量,在另一个步骤中我需要将这些变量插入到上面 json 中的
environmentVariableEntries
,
这是我的代码:
sh(script: "echo \$(jq --arg url \"$URL\" '.defaultOptions.environmentVariableEntries += [{\"key\": \"URL\", \"value\": \$url}]' json.xctestplan) > json.xctestplan", returnStdout: true)
这种方法可行,但有两个问题:
++ jq --arg url 'https://redacted
' '.defaultOptions.environmentVariableEntries += [{"key": "URL", "value": [$url]}]' json.xctestplan
jq: parse error: Invalid string: control characters from U+0000 through U+001F must be escaped at line 2, column 1
+ echo
我尝试将变量包装在 [] 中,但没有成功。
我们首先确定
jq
命令是否有效。
#!/bin/bash
URL=https://www.google.com
jq --arg url "$URL" '.defaultOptions.environmentVariableEntries += [{"key": "URL", "value": $url}]' json.xctestplan
输出为:
{
"defaultOptions": {
"environmentVariableEntries": [
{
"key": "OS_VERSION",
"value": "13"
},
{
"key": "URL",
"value": "https://www.google.com"
}
]
}
}
所以这似乎正在做你想做的事情。
我想我明白为什么你将
jq
命令包装在 echo
命令中。这是否允许您重定向到您正在读取的同一文件?如果没有 echo
,输入文件将在读取开始之前被截断。
如何将 Jenkins 命令更新为类似这样的命令(未经测试):
pipeline {
agent any
environment {
URL = 'https://www.google.com'
}
stages {
stage('Update XCTestPlan') {
steps {
script {
sh "jq --arg url \"$URL\" '.defaultOptions.environmentVariableEntries += [{\"key\": \"URL\", \"value\": \$url}]' json.xctestplan > json.xctestplan.tmp"
sh "mv json.xctestplan.tmp json.xctestplan"
}
}
}
}
}
这使您能够避免使用
echo
,从而简化了引用。
作为可能的改进,您可以使用
sh
运算符组合两个 &&
命令。