Replace value in yaml if name : xxx with bash

Ranvijay Sachan picture Ranvijay Sachan · Jan 27, 2020 · Viewed 11.3k times · Source

I want to change yaml file value based on name:

Example:

spec:
  containers:
    - name: app1
      image: imageurl.com
      command: []
      env:
      - name: MONGO_HOST
        value: localhost

Here you can see we have added an env for mongo host. Now using BASH i want to change MONGO_HOST value based on condition like if - name: MONGO_HOST set value: 172.16.87.98

Answer

Inian picture Inian · Jan 27, 2020

kislyuk/yq is a YAML syntax aware parser which uses jq as its JSON processor. yq takes YAML input, converts it to JSON, and feeds it to jq

The filter, the part under '..' is applied on the JSON object, and the resulting JSON with the IP updated is formed and it is converted back to YAML format, because of the -y argument.

yq -y '(.spec.containers[].env[]|select(.name == "MONGO_HOST").value)|="172.16.87.98"' yaml  

Installation and usage is pretty straightforward which is available in yq: Command-line YAML/XML processor

You can use the in-place edit option -i just like sed -i to avoid re-directing to a temporary file with yq -yi '...'


mikefarah/yq

mikefarah/yq is a Go implementation of the YAML parser which since v4 has adopted a DSL similar to that of jq. So using the same, one could do

yq e '(.spec.containers[].env[]|select(.name == "MONGO_HOST").value) |= "172.16.87.98"' yaml