Search code examples
yamlkubernetes-helmyq

Is there a way to search through a yaml file for any instance of a key


I am currently trying to solve a problem with yq where we are updating the values file of a helm chart with an automated process. Most values files have the image tag in the following format:

image:
  repository: repo-name
  tag: 0.0.1

which we were updating with:

yq -i e '.image.tag = env(TAG)' chart-name/values.yaml

however not all charts follow the same format e.g. some have:

controller:
  image:
    repository: repo-name
    tag: 0.0.1

I want to be able to update the value of tag where ever it is nested within the yaml file if that is possible with yq or an alternative if it is possible.


Solution

  • Assuming you are using mikefarah/yq, you can use the recursive descent operator to update any key matching the name tag

    yq '( .. |  select(has("tag")).tag ) |= env(TAG)' yaml
    

    Unfortunately, the path operator is not efficient enough (unlike in jq) to get the paths of all root to leaf paths and update its value.

    Note: If you are using yq version 4.18.1 or beyond, the eval flag e is no longer needed as it has been made the default action.