Search code examples
docker-composeyamlyq

Subkey yq query on docker-compose.yml


What I'm looking for is a yq query that returns the service names that are using a specified volume for a given docker-compose.yml file.

For example, in the stripped down docker-compose.yml file below, say I am looking for the names of all services that use the volume v-app-olorin.

version: "3"
services:
  arwen:
    this: that
    volumes:
      - v-app-mithrandir:/data/mithrandir
      - v-app-olorin:/data/olorin
  boromir:
    volumes:
      - v-app-mithrandir:/data/mithrandir
      - v-app-stormcrow:/data/stormcrow
  cirdan:
    volumes:
      - v-app-mithrandir:/data/mithrandir
      - v-app-olorin:/data/olorin
volumes:
  v-app-mithrandir:
    name: v-app-mithrandir
  v-app-olorin:
    name: v-app-olorin
  v-app-stormcrow:
    name: v-app-stormcrow

The expected response would be:

arwen
cirdan

I can match simple key values with something like this:

yq e '.services | with_entries(select(.value.this == "that")) | to_entries | .[] | .key' docker-compose.yml
arwen

But I'm having trouble matching an element of the volumes array. Thank you for any help.


Solution

  • here's an expression that does that:

    yq '.services[] | select(.volumes[] | contains("v-app-olorin")) | key' docker-compose.yml
    

    Explanation:

    • splat out the services entries into their invidiual nodes .services[]
    • select the ones that have "v-app-olorin" in their volumes array: select(.volumes[] | contains("v-app-olorin"))
    • get the key of that services entry

    Disclaimer: I wrote yq