如何解决合并 YAML 数组,忽略 YAML 中的其他字段
我正在寻找一种方法来合并来自两个单独 YAML 的数组(将一个附加到另一个)。然而,YAML 有一个字段(不在数组中)用 {}
包裹,以替换为运行时值。即
# yaml a
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
namespace: default
name: {clusterRoleName}
rules:
- apiGroups: [""]
resources: ["pods"]
verbs: ["get","watch","list"]
# yaml b
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
namespace: default
name: {clusterRoleName}
rules:
- apiGroups: ["apps"]
resources: ["deployments"]
verbs: ["get","list"]
# desired
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
namespace: default
name: {clusterRoleName}
rules:
- apiGroups: [""]
resources: ["pods"]
verbs: ["get","list"]
- apiGroups: ["apps"]
resources: ["deployments"]
verbs: ["get","list"]
为此,我使用的是 yq 2.14 版。我试过 yq merge -a=append a.yaml b.yaml
,它按照我的意愿处理规则数组,但将 name: {clusterRoleName}
视为 JSON 并输出:
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
namespace: default
name: {ClusterRoleName: ''}
...
有没有办法只合并一个字段,或者忽略特定的键或值类型?如果有人能够提出替代方法,我也不会为此使用 yq。
解决方法
虽然使用专用的 yaml 解析器(例如 yq)是理想的,但使用 awk 可能是另一种选择:
awk 'NR==FNR && !/^[[:space:]]/ { tag=$1;next } tag=="rules:" && FNR==NR { map[idx++]=$0 } END { tag="" } NR!=FNR && !/^[[:space:]]/ { if (tag=="rules:") { for (i in map) { print map[i]}} tag=$1 } NR!=FNR { print }' yamlb yamla
说明:
awk 'NR==FNR && !/^[[:space:]]/ { # Processing yamlb (NR==FNR) and there there are spaces at the beginning of the line
tag=$1; # Set the variable tag to the first space delimited field
next # Skip to the next file
}
tag=="rules:" && FNR==NR { # Process where tag is "rules:" and we are processing yamlb
map[idx++]=$0 # Put the line in an array map with in incrementing index
}
END {
tag="" # At the end of the file reset the variable tag
}
NR!=FNR && !/^[[:space:]]/ { # Process yamla where there are no spaces at the start of the line
if (tag=="rules:") {
for (i in map) {
print map[i] # If tag is equal to rules: print the array map
}
}
tag=$1 # Set the variable tag to the first space delimited field.
}
NR!=FNR {
print # Print lines when we are processing yamla
}' yamlb yamla
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。