How do I validate my YAML file from command line?

Viewed 143783

I am having issues pulling from a YAML config file:

Fatal error: while parsing a block mapping; expected <block end>, but found block entry

While there are plenty of online YAML validators, which I have tried and have helped, I'd like to validate my YAML files from the command line and integrate this into my continuous integration pipeline.

7 Answers

With basic Ruby installation this should work:

ruby -ryaml -e "p YAML.load(STDIN.read)" < data.yaml

Python version (thx @Murphy):

pip install pyyaml
python -c 'import yaml, sys; print(yaml.safe_load(sys.stdin))' < data.yaml

You could use yamllint. It's available in Homebrew, etc. It can be used for syntax validation as well as for linting.

To correct your .yaml files I recommend the tool yamllint. It can be launched easily from the local console.

The package yamllint is available for all major operating systems.

It's installable from the system's package sources. (e.g. sudo apt-get install yamllint). See documentation for quick start and installation.

My preferd way is yamllint -d "{extends: default, rules: {quoted-strings: enable}}" .

Since I really want to catch quote errors, e.g. validate: bash -c ' ' \""

This is valid yaml, since yaml will just quote the string and turn it into: validate: "bash -c ' ' \\\"\""

Whilst there was just clearly a quote missing at the beginning of the validate comand.

So a normal yaml checker will not detect this, yamllint wil not even detect this in it's default configuration, so turn on quoted-strings checker.

If you got no interpreter installed in your environment but still got a curl, then you could use an online linter project like Lint-Trilogy:

curl -X POST  --data "data=$(cat myfile.yml)" https://www.lint-trilogy.com/lint/yaml/json

It delivers the validation result incl. error descriptions (if any) as json or csv or, where sufficient, as plain text true or false.

It's available as docker file, too. So if you often need a REST based linter, perhaps in a CI/CD pipeline, it may be handy to host an own instance on your site.

Related