How to validate yaml from the command line (using Python)

This guide will show you how to validate yaml on the command line using Python.

1

python -c 'import yaml, sys; yaml.safe_load(sys.stdin)' < cfg.yaml

If your file contains valid yaml, it will do nothing.

[tmp]$ python -c 'import yaml, sys; yaml.safe_load(sys.stdin)' < cfg.yaml
2

If the file does not contain valid yaml, you'll get a traceback. From that traceback you should be able to identify the problem.

[tmp]$ python -c 'import yaml, sys; yaml.safe_load(sys.stdin)' < cfg.yaml
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  ...
could not find expected ':'
  in "<stdin>", line 5, column 1

The traceback contains a lot of lines that are very useful, but near the end you'll find the line number and column of the error.