yq command to append to another yaml file

105 views Asked by At

Given a yaml file, I want to select all fields which contain a key named "graph" and append those fields into another yaml file called result.yaml.

for example: Given a yaml file called myfile.yaml

services_list:
  - name: service1
    location: europe
    graph: true
  - name: service2
    location: asia
  - name: service3
    location: asia
    graph: true

and result.yaml:

services_list:
  - name: my-service
    location: europe
    graph: true

The result.yaml should be:

services_list:
  - name: my-service
    location: europe
    graph: true
  - name: service1
    location: europe
    graph: true
  - name: service3
    location: asia
    graph: true

Couldn't find a proper command for it, would appreciate your help here!

2

There are 2 answers

1
0stone0 On

You can use

yq e '.services_list | map(select(.graph))' myFile.yaml > tmp.yaml

to write the select() result to a temporary file.


Then use load() to read that file while updating result.yaml:

yq '.services_list *= load("tmp.yaml")' result.yanl

This is probably possible in a single yq call tho

2
pmf On

As with your last question, please provide which implementation of yq you are using. The solution to this one is essentially the same, just use the has function. Yet still, the two implementations differ in how to access the second file (input vs load).

Here's the approach using kislyuk/yq:

yq -y '.services_list += (
  input.services_list | map(select(has("graph")))
)' result.yaml myfile.yaml

And here's the one using mikefarah/yq:

yq '.services_list += (
  load("myfile.yaml").services_list | map(select(has("graph")))
)' result.yaml

Both output:

services_list:
  - name: my-service
    location: europe
    graph: true
  - name: service1
    location: europe
    graph: true
  - name: service3
    location: asia
    graph: true

With mikefarah/yq, use the -i flag to modify the file, with kislyuk/yq use a temporary file along the lines of yq … > tmp && mv tmp result.yaml.