首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >合并YAML数组,忽略YAML中的其他字段

合并YAML数组,忽略YAML中的其他字段
EN

Stack Overflow用户
提问于 2021-01-07 19:04:27
回答 1查看 129关注 0票数 0

我正在寻找一种方法来合并来自两个独立的YAML的数组(将一个附加到另一个)。但是,YAML有一个用{}包装的字段(不在数组中),它将被替换为运行时值。i.e

代码语言:javascript
复制
# 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和输出:

代码语言:javascript
复制
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: default
  name: {ClusterRoleName: ''}
...

有没有一种方法可以只合并一个字段,或者忽略特定的键或值类型?如果有人能够提出替代方法,我也不会使用yq来解决这个问题。

EN

Stack Overflow用户

回答已采纳

发布于 2021-01-08 20:41:33

虽然使用专用的yaml解析器(如yq )将是理想的,但使用awk可能是一种替代方案:

代码语言:javascript
复制
 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

解释:

代码语言:javascript
复制
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
票数 1
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65611163

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档