我有一个逗号分隔的IP地址字符串(一个或多个)
nodes=192.168.56.111,192.168.56.112,192.168.56.113
使用jq
,我想创建一个JSON文档,看起来像这样:
{
"clusters": [
{
"nodes": [
{
"node": {
"hostnames": {
"manage": [
"192.168.56.111"
],
"storage": [
"192.168.56.111"
]
},
"zone": 1
},
"devices": [
{
"name": "/dev/sdb",
"destroydata": false
}
]
},
{
"node": {
"hostnames": {
"manage": [
"192.168.56.112"
],
"storage": [
"192.168.56.112"
]
},
"zone": 1
},
"devices": [
{
"name": "/dev/sdb",
"destroydata": false
}
]
},
{
"node": {
"hostnames": {
"manage": [
"192.168.56.113"
],
"storage": [
"192.168.56.113"
]
},
"zone": 1
},
"devices": [
{
"name": "/dev/sdb",
"destroydata": false
}
]
}
]
}
]
}
目前为止我有什么:
nodes=192.168.56.111,192.168.56.112,192.168.56.113
jq --arg ip "$nodes" '.clusters[].nodes[].node.hostnames.manage |= ($ip | split(","))' <<<'{"clusters":[{"nodes":[{"node":{"hostnames":{"manage":[],"storage":[]},"zone":1},"devices":[{"name":"/dev/sdb","destroydata":false}]}]}]}'
这个有两个问题:
.clusters[].nodes[].node
未被复制.clusters[].nodes[].node.hostnames.storage
缺失
您可以使用map
的拆分结果来创建.clusters[0].nodes
下的数组:
nodes=192.168.56.111,192.168.56.112,192.168.56.113
jq -R '
{clusters: [{nodes: (./"," | map({
node: {hostnames: {manage: [.], storage: [.]}, zone: 1},
devices: [{name: "/dev/sdb", destroydata: false}]
}))}]}
' <<< "$nodes"
{
"clusters": [
{
"nodes": [
{
"node": {
"hostnames": {
"manage": [
"192.168.56.111"
],
"storage": [
"192.168.56.111"
]
},
"zone": 1
},
"devices": [
{
"name": "/dev/sdb",
"destroydata": false
}
]
},
{
"node": {
"hostnames": {
"manage": [
"192.168.56.112"
],
"storage": [
"192.168.56.112"
]
},
"zone": 1
},
"devices": [
{
"name": "/dev/sdb",
"destroydata": false
}
]
},
{
"node": {
"hostnames": {
"manage": [
"192.168.56.113"
],
"storage": [
"192.168.56.113"
]
},
"zone": 1
},
"devices": [
{
"name": "/dev/sdb",
"destroydata": false
}
]
}
]
}
]
}
演示