Yaml - how to replace key value using sed?

393 views Asked by At

I have a yaml config, and I want to replace one of the fields with a new value?

Here is an example of the yaml config:

application: "app_name"
pipeline: "app-pipeline"
parameters:
  spinnaker_environment: "production"
  perform_cleanup: false
  build_image_tag: "foobar"

I want to replace "foobar" under the build_image_tag field and replace it with a different value like "latest". How do I do this?

I tried the following:

sed '/^parameters:/{n;s/build_image_tag:.*/build_image_tag: "latest"/;}' exec.yml

But that didn't seem to work. The yaml config should look like this:

application: "app_name"
pipeline: "app-pipeline"
parameters:
  spinnaker_environment: "production"
  perform_cleanup: false
  build_image_tag: "latest"
2

There are 2 answers

1
Gilles Quénot On BEST ANSWER

With go yq or python yq, the proper tools:

$ yq -i '.parameters.build_image_tag="latest"' file.yaml
application: "app_name"
pipeline: "app-pipeline"
parameters:
  spinnaker_environment: "production"
  perform_cleanup: false
  build_image_tag: "latest"
  • yq use the same syntax than jq for JSON
  • the -i is the same as sed -i: replace on the fly
0
Ivan On

There is an 'S' command in sed for this. It works like so:

# sed 's/pattern/replacement/[g]' - g is an optional flag to replace all instances

# examples:
echo "a b b c" | sed 's/b/d/'
a d b c

echo "a b b c" | sed 's/b/d/g'
a d d c

For your example it would be like this:

sed 's/foobar/latest/' exec.yml

I'd recommend to create a template file like this to simplify things:

cat template.yml
application: "_APP_"
pipeline: "_PIP_"
parameters:
  spinnaker_environment: "_ENV_"
  perform_cleanup: _CLN_
  build_image_tag: "_IMG_"

and change it with sed like so:

sed '
  s/_APP_/app_name/;
  s/_PIP_/app-pipeline/;
  s/_ENV_/production/;
  s/_CLN_/false/;
  s/_IMG_/latest/;
' template.yml > new.yml

Using vars:

app=app_name
pip=app-pipeline
env=production
cln=false
img=latest

sed "
  s/_APP_/$app/;
  s/_PIP_/$pip/;
  s/_ENV_/$env/;
  s/_CLN_/$cln/;
  s/_IMG_/$img/;
" template.yml > new.yml