Search code examples
selectyamlyq

How to add yaml to file.yaml in a specific place?


I'm using yq and i'm struggling to figure out the below problem.

Given a file.yaml containing the below:

apiVersion: v1
clusters:
  - cluster:
      age: 50
      server: dev
    name: apple
  - cluster:
      age: 50
      server: prod
    name: orange

what is the yq command i need to replace file.yaml with a file that adds yaml for the cluster where name: orange only, so that file.yaml looks like this afterwards:

apiVersion: v1
clusters:
  - cluster:
      age: 50
      server: dev
    name: apple
  - cluster:
      age: 50
      server: prod
      extensions:
      - name: xx.io
        extension:
          subnet:
          - 1.2.3.4/32
    name: orange

Solution

  • Which implementation of yq do you mean? In any case, select can pick the right object, += will update.

    Using mikefarah/yq:

    yq '(.clusters[] | select(.name == "orange")).cluster += load("extension.yaml")' file.yaml
    

    Using kislyuk/yq:

    yq -y '(.clusters[] | select(.name == "orange")).cluster += input' file.yaml extension.yaml
    

    Input file.yaml:

    apiVersion: v1
    clusters:
      - cluster:
          age: 50
          server: dev
        name: apple
      - cluster:
          age: 50
          server: prod
        name: orange
    

    Input extension.yaml:

    extensions:
    - name: xx.io
      extension:
        subnet:
        - 1.2.3.4/32
    

    Output:

    apiVersion: v1
    clusters:
      - cluster:
          age: 50
          server: dev
        name: apple
      - cluster:
          age: 50
          server: prod
          extensions:
            - name: xx.io
              extension:
                subnet:
                  - 1.2.3.4/32
        name: orange