Search code examples
arraysyamlyq

Update a specific value in a nested array by applying a condition on the parent (name or key) to proceed further in YAML using yq command


Let say my YAML is :

releases:
  - chart: ../charts/foo
    name: foo
    namespace: '{{ .Values.stack }}'
    values:
      - ../config/templates/foo-values.yaml.gotmpl
    set:
      - name: image.tag
        value: 22
      - name: replicas
        value: 1
  - chart: ../charts/bar
    name: bar
    namespace: '{{ .Values.stack }}'
    values:
      - ../config/templates/bar-values.yaml.gotmpl
    set:
      - name: image.bar_proxy.tag
        value: 46
      - name: image.bar.tag
        value: 29
      - name: replicas
        value: 1

I want to replace the value of 'image.tag' for bar chart only. I tried several commands but it is replacing both the image.tag values.

I tried with command :

yq -y '.releases[].set |= map(select(.name == "image.tag").value=51)' yaml and I agree there is no condition applied for releases.name but my used syntax is not working.

Can anybody please help to generate the valid yq command.

I tried several yq commands to filter the releases.name but couldn't get the actual result.


Solution

  • Just .releases[] will iterate over all items. Use select to filter for the one(s) you need. Then repeat alike with .set[]. I have used endswith and == for the two selector comparisons. Adapt as needed.

    (.releases[] | select(.chart | endswith("/bar")).set[] | select(.name == "image.tag").value) = 51
    
    releases:
      - chart: ../charts/foo
        name: foo
        namespace: '{{ .Values.stack }}'
        values:
          - ../config/templates/foo-values.yaml.gotmpl
        set:
          - name: image.tag
            value: 22
          - name: replicas
            value: 1
      - chart: ../charts/bar
        name: bar
        namespace: '{{ .Values.stack }}'
        values:
          - ../config/templates/bar-values.yaml.gotmpl
        set:
          - name: image.tag
            value: 51
          - name: image.bar.tag
            value: 29
          - name: replicas
            value: 1
    

    Please explicate which implementation of yq you are using. As you have used the -y flag, it seems to be kislyuk/yq (as opposed to mikefarah/yq).