Home > database >  YQ - replace values of subfields of list based on list of values
YQ - replace values of subfields of list based on list of values

Time:06-29

Given a list in YAML, I want to dynamically replace all values of source.targetRevison's based on a input list to an input variable:

replace_list=[argocd,argocd-projects]
replace_to_value=v1.0.0

yq version 4.2.x

Input YAML:

server:
  additionalApplications:
    - name: argocd
      path: argocd/argocd-install
      source:
        targetRevision: feature/3-dns
    - name: argocd-projects
      source:
        path: argocd/argocd-projects
        targetRevision: feature/3-dns
      syncPolicy:
        automated:
          selfHeal: true
          prune: true
    - name: argocd-tools-aks-apps
      namespace: argocd
      destination:
        namespace: argocd
        server: https://kubernetes.default.svc
      project: argocd
      source:
        targetRevision: HEAD
      syncPolicy:
        automated:
          selfHeal: true
          prune: true

Expected output:

server:
 additionalApplications:
  - name: argocd
    path: argocd/argocd-install
    source:
      targetRevision: v1.0.0
  - name: argocd-projects
    source:
      path: argocd/argocd-projects
      targetRevision: v1.0.0
    syncPolicy:
      automated:
        selfHeal: true
        prune: true
  - name: argocd-tools-aks-apps
    namespace: argocd
    destination:
      namespace: argocd
      server: https://kubernetes.default.svc
    project: argocd
    source:
      targetRevision: HEAD
    syncPolicy:
      automated:
        selfHeal: true
        prune: true

Current progress:

yq '.server.additionalApplications.[] | (.source.targetRevision)' argocd/argocd-install/values-override.yaml

gives me:

  • feature/3-dns
  • feature/3-dns
  • HEAD

CodePudding user response:

you can do this:

yq '(  .server.additionalApplications[] | 
       select(.name == ("argocd", "argocd-projects")) | 
       .source.targetRevision ) 
   |= "v1.0.0"' examples/data1.yaml

Explanation: You want to update a selection of the additionalApplication entries.

  • First you navigate to those entries and expand them .server.additionalApplications[]
  • Next, we filter them by the name: select(.name == ("argocd", "argocd-projects")
  • Now we can update their .source.targetRevision property. Importantly, note that the whole LHS expression is in brackets, as that's what we want to pass to the 'update' (|=) operator. If you don't put it in brackets, then you will see that it seems to discard everything else (because it filters first, then updates separately).

Hope that makes sense!

Disclaimer: I wrote yq.

  • Related