How do I validate YAML syntax?

Dark navy cover card with the title 'How do I validate YAML syntax?' in white and a green accent bar

To validate YAML syntax, run yamllint file.yml. It reports parse errors, duplicate keys and indentation problems with line numbers, and exits non-zero when it finds an error. If you only need to know whether the file parses, python3 -c "import yaml, sys; yaml.safe_load(open(sys.argv[1]))" file.yml does that with no extra install beyond PyYAML.

A clean result only proves the file is well-formed YAML. Whether your app, CI system or cluster accepts it is a separate check.

Three levels of YAML validation

YAML validation happens at three levels: does the file parse, is it clean, and does the target tool accept it. Most "my YAML is broken" problems sit at one of these, and each needs a different command.

Level What it catches Command
Parse Bad indentation, unclosed quotes, tabs, stray colons yaml.safe_load, any YAML parser
Lint Duplicate keys, mixed indentation, long lines, yes/no values yamllint
Tool Unknown fields, wrong types, missing required keys The tool's own dry run or validator

A file can pass the first level and fail the second. It can pass both and still be rejected by Kubernetes because a field name is misspelled. For anything that deploys, CI should run all three.

How to validate YAML syntax with yamllint

yamllint is the standard command-line linter to validate YAML syntax and style. Its documentation says it checks more than syntax validity: it also flags key repetition and cosmetic problems such as line length, trailing spaces and indentation.

Install it with the package manager you already have. The quickstart lists all four:

pip install --user yamllint
sudo apt-get install yamllint
brew install yamllint
sudo dnf install yamllint

Then point it at files or a whole folder:

yamllint config.yml
yamllint .
cat config.yml | yamllint -

The default output names the file and then lists problems as line:column, level, message and rule. A duplicate key looks like this:

config.yml
  4:4  error  duplication of key "id-00042" in mapping  (key-duplicates)

For editors and CI annotations, yamllint -f parsable prints one problem per line, such as file.yml:6:2: [warning] missing starting space in comment (comments).

Tune the rules so the output is useful

yamllint's default rules are strict, and the built-in relaxed preset loosens them. Per the rules reference, lines over 80 characters are flagged by default, and the truthy rule only allows true and false. That rule exists for good reason; the Norway problem shows what happens when no turns into a boolean.

If a legacy repo produces hundreds of warnings, start with yamllint -d relaxed . and tighten later. You can also override one rule inline: yamllint -d "{extends: relaxed, rules: {line-length: {max: 120}}}" file.yaml. Commit a .yamllint file to the repo root once you settle on rules; yamllint loads it automatically from the working directory.

Exit codes for CI

yamllint fails a CI job only on errors unless you pass --strict. The configuration page says the default return code is 1 only when there is at least one error. With --strict, the codes split three ways:

  1. 0: no errors or warnings
  2. 1: one or more errors
  3. 2: no errors, but one or more warnings

Use --strict when you want warnings to block a merge.

Validate YAML syntax in Python with safe_load

Python can check whether YAML parses by loading it with yaml.safe_load and catching yaml.YAMLError. The PyYAML documentation says every parse failure raises an instance of YAMLError or a subclass, and the exception's problem_mark holds the position.

import sys, yaml

try:
    with open(sys.argv[1]) as f:
        yaml.safe_load(f)
    print("OK")
except yaml.YAMLError as exc:
    mark = getattr(exc, "problem_mark", None)
    if mark:
        print(f"Error at line {mark.line + 1}, column {mark.column + 1}")
    print(exc)
    sys.exit(1)

Two details matter. First, line and column count from 0, so add 1 before showing them; the docs' own example input unbalanced blackets: ][ reports Error position: (1:22) after that adjustment. Second, use safe_load, not load. The same page warns that calling yaml.load on data from an untrusted source isn't safe, while safe_load only builds standard YAML types.

It won't complain about mixed indentation styles that still parse, and it won't flag yes as a likely mistake.

Check the top level with yq

A YAML file can parse cleanly and still be useless, because almost any text is valid YAML. A config file that got overwritten with a single line of plain text parses as a string. The yq tips page puts it plainly: YAML can be surprisingly lenient in what it accepts.

Its suggested check confirms the top level is a map or a list:

yq --exit-status 'tag == "!!map" or tag== "!!seq"' file.yml > /dev/null

The command exits non-zero when the document is a scalar, so a broken config fails the build instead of deploying as an empty string.

Common YAML syntax errors and what they mean

Most YAML syntax errors come from indentation, tabs, duplicate keys or unquoted special characters.

  • Tabs in indentation. The YAML 1.2.2 spec says tab characters must not be used for indentation, since systems treat them differently. See YAML and tabs for the fix in common editors.
  • Duplicate keys. The spec requires each key in a mapping to be unique. yamllint's key-duplicates rule catches them and is on by default.
  • A colon inside a value. title: Note: read this breaks parsing. Quote the value. The mapping values error guide covers this one in detail.
  • Inconsistent indentation. yamllint's default indentation rule wants spaces used consistently, so a file mixing 2 and 4 spaces gets flagged even when it parses.

Comments don't cause parse errors, but a missing space after # is a lint warning. YAML comments shows the accepted forms.

Validate against the tool that reads the file

Syntax validation can't tell you whether a field name or value is right for your tool. For that, ask the tool itself. Kubernetes is the clearest example: the kubectl apply reference offers --dry-run=server, which submits the request without persisting the resource.

kubectl apply -f deploy.yml --dry-run=server

--validate defaults to strict, which checks the object against a schema and fails the request if it's invalid. Setting it to ignore silently drops unknown or duplicate fields, which hides exactly the typos you were trying to catch. For other tools, look for a "check", "lint" or "dry run" flag in their docs.

A parse check is what most people reach for, and it's the weakest of the three. None of these commands knows your app's rules. If your own service reads the YAML, the only full check is loading it the way the service does. For quick, one-off checks, converting a snippet to JSON is another way to see exactly how a parser read it; JSON vs YAML for config files explains where the two formats differ.

FAQ

What is the best tool to validate YAML?

yamllint is the usual choice. It checks that the file parses and also flags duplicate keys, inconsistent indentation and long lines, and it returns a non-zero exit code on errors for CI.

How do I validate YAML in Python?

Call yaml.safe_load on the file inside a try block and catch yaml.YAMLError. The exception's problem_mark gives the line and column, counted from 0.

Are tabs allowed in YAML?

Not for indentation. The YAML 1.2.2 spec says tab characters must not be used in indentation because systems treat them differently.

Are duplicate keys valid in YAML?

No. The spec requires every key in a mapping to be unique. yamllint reports duplicates through its key-duplicates rule, which is on by default.

Does valid YAML mean my config is correct?

No. A syntax check only proves the file parses. To confirm a tool accepts it, run that tool's own check, such as kubectl apply with --dry-run=server for Kubernetes.

Sources