使用 yq 从 YAML 映射对象中删除某些字段

Alb*_*rto 5 yaml yq

我需要为 yaml 文件做一些棘手的事情,这就是它之前的样子

apiVersion: v1
items:
  - apiVersion: core.k8s.com/v1alpha1
    kind: Test
    metadata:
      creationTimestamp: '2022-02-097T19:511:11Z'
      finalizers:
        - cuv.ssf.com
      generation: 1
      name: bar
      namespace: foo
      resourceVersion: '12236'
      uid: 0117657e8
    spec:
      certificateIssuer:
        acme:
          email: myemail
      provider:
        credentials: dst
        type: foo
      domain: vst
      type: bar
    status:
      conditions:
        - lastTransitionTime: '2022-02-09T19:50:12Z'
          message: test
          observedGeneration: 1
          reason: Ready
          status: 'True'
          type: Ready
      lastOperation:
        description: test
        state: Succeeded
        type: Reconcile
Run Code Online (Sandbox Code Playgroud)

https://codebeautify.org/yaml-validator/y22fe4943

我需要删除部分下的所有字段metadata,棘手的部分是仅保留name并且namespace 除了完全删除该status部分之外,它应该如下所示

  apiVersion: v1
    items:
      - apiVersion: core.k8s.com/v1alpha1
        kind: Test
        metadata:
          name: bar
          namespace: foo
        spec:
          certificateIssuer:
            acme:
              email: myemail
          provider:
            credentials: dst
            type: foo
          domain: vst
          type: bar
Run Code Online (Sandbox Code Playgroud)

链接后 https://codebeautify.org/yaml-validator/y220531ef

使用 yq ( https://github.com/mikefarah/yq/ ) 版本 4.19.1

Ini*_*ian 7

使用mikefarah/yq(又名 Go yq),您可以执行如下操作。使用del删除条目,使用with_entries选择已知字段

yq '.items[] |= (del(.status) | .metadata |= with_entries(select(.key == "name" or .key == "namespace")))' yaml
Run Code Online (Sandbox Code Playgroud)

从v4.18.1开始,evalflag 是默认操作,因此e可以避免 flag