How can I validate Docker Compose volume names with grep or a YAML-aware tool?
Asked by
MellowPine42
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.
Answers
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.
Reply to this answer
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.
Reply to this answer
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.
Reply to this answer
Add your answer
Answers are reviewed before publication.
MellowPine42: That makes sense. Iโll try validating the parsed YAML instead of matching the raw text.