Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace a block of YAML

I want to replace an array block in a yaml file with a specific different array. I don’t necessarily know how many elements are in the array to be replaced, nor what their values are.

yq seems like the best tool for the job (but I am open to other suggestions).

My yaml file looks kind of like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

name: mything

parameters:
  - name: environment
    type: string
    values:
      - storytest-DEV
      - storytest-PRD
  - name: destroy
    type: boolean
    default: false
  - name: validate
    type: boolean
    default: true

variables:
  - group: storytest
  - name: version
    value: "1.0.0"

and I want to replace the values of the parameters block with the name environment with a single element, lets say, foo.

so far I’ve got: yq '.parameters[] | select(.name == "environment").values = ["foo"]' infile.yml

which gives me

name: environment
type: string
values:
  - foo
name: destroy
type: boolean
default: false
name: validate
type: boolean
default: true

which is what I want except that, I assume because of the .parameters[] |, I’ve lost the rest of my file (and the name fields no longer show dashes – meaning it’s lost the fact that they’re array elements, I assume

How can I replace the

- storytest-DEV
- storytest-PRD

with

- foo

and leave the rest of the file intact?

>Solution :

Use parentheses to retain the context outside the iteration:

(.parameters[] | select(.name == "environment")).values = ["foo"]

Or let map do the iteration, and update the array:

.parameters |= map(select(.name == "environment").values = ["foo"])

Both work with kislyuk/yq, mikefarah/yq, and itchyny/gojq, resulting in:

name: mything
parameters:
  - name: environment
    type: string
    values:
      - foo
  - name: destroy
    type: boolean
    default: false
  - name: validate
    type: boolean
    default: true
variables:
  - group: storytest
  - name: version
    value: "1.0.0"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading