Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove certain fields from a YAML map object using yq

Tags:

yaml

yq

I have some tricky thing that I need to do for a yaml file, this is how it looks before

Before

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

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

I need to remove all the fields under section metadata and the tricky part is to keep only the name and namespace in addition to removing the status section at all, it should look like following

After

  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

After link https://codebeautify.org/yaml-validator/y220531ef

Using yq (https://github.com/mikefarah/yq/) version 4.19.1

like image 522
Jenney Avatar asked Jul 26 '26 04:07

Jenney


2 Answers

Using mikefarah/yq (aka Go yq), you could do something like below. Using del for deleting an entry and with_entries for selecting known fields

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

Starting v4.18.1, the eval flag is the default action, so the e flag can be avoided

like image 168
Inian Avatar answered Jul 29 '26 12:07

Inian


This should work using yq in the implementaion of https://github.com/kislyuk/yq (not https://github.com/mikefarah/yq), and the -y (or -Y) flag:

yq -y '.items[] |= (del(.status) | .metadata |= {name, namespace})'
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
like image 39
pmf Avatar answered Jul 29 '26 11:07

pmf