I have several Docker Compose YAML files in a directory and want validation to fail whenever a database volume is named anything other than `db-data`. For example, a service might contain `- db-data:/var/lib/postgresql/data`, while another could have an unexpected name such as `cache-data:/data`. Is there a reliable way to check this from the command line? I was considering grep and a regular expression, but I'm open to using a YAML-aware tool if that is safer.
3 Answers
For dependable validation, load the YAML and inspect the data structure with Python or another YAML library. Iterate through `services`, inspect each service’s `volumes`, and reject any volume whose source portion does not begin with `db-data:`. Then run that validator for every `*.yaml` file and use its exit code to fail the build or script. This also handles multiple volume entries and avoids assumptions about whitespace.
Because these are YAML documents, use `yq` rather than trying to make grep understand indentation and structure. Extract each service’s volumes and select entries that do not start with `db-data:`; if any are found, return a nonzero status or print the offending service. A YAML parser will keep working even if formatting or indentation changes.
A regex can work for a very tightly controlled file format, but it is fragile for YAML and may accidentally match the wrong service or section. With GNU grep, a rough multiline check could identify files containing a `db` section whose following `volumes` block does not immediately contain `- db-data:`, but this will not fully parse YAML. Treat it as a quick check, not a complete validator.

That makes sense. I’ll try validating the parsed YAML instead of matching the raw text.