Search code examples
yamlkubernetes-helmyq

yq - Search and replace a node's specific value (If exists)


I have a helm dependencies chart that I'm willing to programmatically search and replace a specific Chart name with a given version. For example, here's my file:

apiVersion: v2
name: my-chart
version: 1.2.3
dependencies:
  - name: dependency-1
    version: 1.0.20
    repository: https://my.registry.com/helm/
  - name: dependency-2
    version: 1.0.1
    repository: https://my.registry.com/helm/
  - name: dependency-3
    version: 1.0.20
    repository: https://my.registry.com/helm/
  - name: dependency-4
    version: 0.3.24
    repository: https://my.registry.com/helm/
  - name: dependency-5
    version: 3.1.2
    repository: https://my.registry.com/helm/

I'm trying to work on workflow that would take two inputs:

  1. chartName
  2. newVersion

Then, when invoked, the workflow will check if $chartName exists in .dependencies (I was able to achieve that using select directive, as following:

yq ".dependencies[] | select (.name == \"dependency-3\")" my-chart/Chart.yaml

Which only outputs the node that matches the select:

$ yq ".dependencies[] | select (.name == \"dependency-3\")" my-chart/Chart.yaml
name: dependency-3
version: 1.0.20
repository: https://my.registry.com/helm/
$

And then I tried to use strenv directive to update the version to the new one ($newVersion), as below:

ver=1.0.0 yq ".dependencies[] | select (.name == \"dependency-3\") | strenv(ver)" my-chart/Chart.yaml

But it only outputs the updated version, so if I run yq -i - it replaces the entire file with simply 1.0.0:

$ ver=1.0.0 yq -i ".dependencies[] | select (.name == \"dependency-3\") | strenv(ver)" my-chart/Chart.yaml
$ cat my-chart/Chart.yaml
1.0.0

How can I get yq to only update the version of the provided dependency name in the dependencies array?

Thanks!


Solution

  • You basically already have all the components, just the assignment = was missing. All put together:

    chart="dependency-3" newver="2.0.0" yq '
      (.dependencies[] | select (.name == strenv(chart))).version = strenv(newver)
    ' my-chart/Chart.yaml
    

    Use the -i option to not just output but update the file.