如何用yq依据已有布尔键值生成新的role键值对
YAML角色转换命令修正
输入YAML数据
- hostname: rk089-s11 compute: false control: true master: false - hostname: rk090-s11 compute: false control: true master: true
期望输出
- hostname: rk089-s11 role: control - hostname: rk090-s11 role: control,master
尝试的错误命令
yq -r '.[] | [ { "hostname": .hostname, "role": ( ( ( .compute == true ) | "compute," ) + ( ( .control == true ) | "control," ) + ( ( .master == true ) | "master," ) ) } ]'|sed 's/,$//'
错误输出
- hostname: rk089-s11 role: compute,control,master - hostname: rk090-s11 role: compute,control,master
修正后的命令及说明
正确命令
yq -r '.[] | { hostname: .hostname, role: ( (if .compute then "compute," else "" end) + (if .control then "control," else "" end) + (if .master then "master," else "" end) ) | sub(",$", "") }'
修正说明
之前的命令错误在于:( .compute == true ) | "compute,"这种写法不会根据布尔值过滤内容——yq中布尔值通过管道传递到字符串时,无论真假都会返回该字符串,导致即使字段为false也会拼接角色名。
改用if...then...else...end条件判断后,只有当对应字段为true时才拼接带逗号的角色名,否则拼接空字符串。最后通过yq内置的sub(",$", "")直接移除末尾的多余逗号,无需再调用sed处理。
内容的提问来源于stack exchange,提问作者aqn
相关产品推荐
相关产品推荐

