0

我正在寻找一种方法来合并来自两个独立 YAML 的数组(将一个附加到另一个)。然而,YAML 有一个用运行时值替换的字段(不在数组中){}。IE

# 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", "watch", "list"]

# desired
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  namespace: default
  name: {clusterRoleName}
rules:
  - apiGroups: [""]
    resources: ["pods"]
    verbs: ["get", "watch", "list"]
  - apiGroups: ["apps"]
    resources: ["deployments"]
    verbs: ["get", "watch", "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 。

4

1 回答 1

1

虽然使用 yq 之类的专用 yaml 解析器是理想的,但使用 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

 
于 2021-01-08T12:41:32.887 回答