Search code examples
jsondocker-composeyamljq

sort and update a docker-compose.yaml with jq


This is my docker-compose file:

{
  "name": "movies-docker-test",
  "services": {
    "movies-rp": {
      "volumes": [
        {
          "type": "volume",
          "source": "certs",
          "target": "/etc/nginx/certs",
        },
        {
          "type": "bind",
          "source": "/home/nblanchet/jeudi_infra/kubernetes/okd/movies-docker-test/reverse-proxy/wikibase.conf.template",
          "target": "/etc/nginx/templates/wikibase.conf.template"
        }
      ]
    }
  }
}

I'd like to update this file so that each volumes of each service to be sorted by the '.type':

{
  "name": "movies-docker-test",
  "services": {
    "movies-rp": {
      "volumes": [
        {
          "type": "bind",
          "source": "/home/nblanchet/jeudi_infra/kubernetes/okd/movies-docker-test/reverse-proxy/wikibase.conf.template",
          "target": "/etc/nginx/templates/wikibase.conf.template"
        },
        {
          "type": "volume",
          "source": "certs",
          "target": "/etc/nginx/certs"
        }
      ]
    }
  

I managed to do this, but the file is not updated:

jq  '[.services[].volumes[]?]|sort_by(.type)'

Solution

  • here is what I successfully tested with ''yq'' and the wrapped ''jq'' syntax

    yq '.services|=with_entries(.value|=(select(has("volumes")).volumes |= sort_by((.type)) ))' docker-compose.yml
    

    or what I initially did with regular ''jq''

    cat movies.yml | yq eval -ojson |  jq '.services|=with_entries(.value|=(select(has("volumes")).volumes |= sort_by((.type)) ))' | yq -P