Search code examples
yamlyq

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:

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"