Modify YAML to include label under each entry in metadata using yq

807 views Asked by At

I have a yaml file like below.This yaml file needs to be patched with a new label under each configmap.

apiVersion: v1
kind: ConfigMapList
items:
  - apiVersion: v1
    data:
      test: 1
    kind: ConfigMap
    metadata:
      name: grafana-dashboard-apiserver1
      namespace: monitoring   
  - apiVersion: v1
    data:
      test: 2
    kind: ConfigMap
    metadata:
      name: grafana-dashboard-apiserver2
      namespace: monitoring   
  - apiVersion: v1
    data:
      test: 3
    kind: ConfigMap
    metadata:
      name: grafana-dashboard-apiserver3
      namespace: monitoring    

I want to insert labels under every configmap in this configmaplist as below,

apiVersion: v1
kind: ConfigMapList
items:
  - apiVersion: v1
    data:
      test: 1
    kind: ConfigMap
    metadata:
      name: grafana-dashboard-apiserver1
      namespace: monitoring
      labels:
        grafana_dashboard: "1"   
  - apiVersion: v1
    data:
      test: 2
    kind: ConfigMap
    metadata:
      name: grafana-dashboard-apiserver2
      namespace: monitoring   
      labels:
        grafana_dashboard: "1" 
  - apiVersion: v1
    data:
      test: 3
    kind: ConfigMap
    metadata:
      name: grafana-dashboard-apiserver3
      namespace: monitoring    
      labels:
        grafana_dashboard: "1" 

I am not sure how to do this in bash..Please help me how to do this bash..does yq help? or Kustomize?

1

There are 1 answers

0
Inian On BEST ANSWER

If you are using mikefarah/yq, you can use the following path expression to write on all metadata fields under the array of items

yq w yaml 'items[*].metadata.labels.grafana_dashboard' --tag '!!str' 1

If the YAML output produced is as expected, you can write in-place with the -i flag i.e. yq w -i '..'