Skip to content
Quasar Tools Logo

How to Detect and Fix YAML Errors

A complete guide to YAML error detection and fixing — covers the most common YAML syntax mistakes, how to read parser messages, and free tools to validate and fix YAML in seconds.

DH
Tutorials & How-Tos12 min read2,700 words

YAML is the configuration language of modern infrastructure — it runs your GitHub Actions, your Kubernetes manifests, your Docker Compose stacks, and your CI/CD pipelines. It is also one of the most error-prone formats to write by hand, because a single misaligned space, an invisible tab, or an unquoted colon produces either a hard parse failure or a silently wrong document. This guide covers every category of YAML error, how to read the messages parsers produce, and the fastest way to detect and fix each one.

#1Error causeIndentation is always the culprit
0Tabs allowedSpec forbids them as indentation
< 1sValidation timeBrowser-local, no upload

Why YAML Errors Are Hard to Debug

YAML derives its structure entirely from whitespace. There are no brackets, no braces, no explicit block delimiters — just indentation levels and colons. This makes YAML remarkably readable when it is correct and remarkably frustrating when it is not, because the same character that organises your data can silently destroy it if it is one column off.

The parser reports where it gave up, not where you made the mistake

The core difficulty with YAML error messages is that parsers report the line where they stopped being able to interpret the document — not the line where the original mistake was made. A missing colon on line 15 may not surface as an error until line 22 when the next key arrives in an unexpected context. This means you almost always need to look several lines above the reported error to find the actual cause.

  • Indentation errors cascade — a misindented parent block makes every child key report an error
  • Tab characters look identical to spaces but throw a parse failure in any spec-compliant parser
  • Duplicate keys pass basic syntax checks silently — one value is overwritten without any warning
  • Unquoted special characters like :, #, *, and & change the document meaning unexpectedly
  • Anchors and aliases fail silently if an alias references a non-existent anchor in the same file

Note

YAML error messages vary significantly by parser. PyYAML, js-yaml, Go's gopkg.in/yaml.v3, and Ruby's Psych all produce different wording for the same underlying mistake. The error categories in this guide are language-agnostic — once you understand the category, you can fix the problem regardless of which parser you are using.

YAML version matters

Most modern tools target YAML 1.2, which tightened several parsing rules that YAML 1.1 permitted. For example, YAML 1.1 treated yes, no, on, and off as boolean values; YAML 1.2 does not. If your configuration uses these bare strings and your validator reports unexpected type coercion, the YAML version mismatch is the cause. Always check which spec version your runtime parser implements.

Most Common YAML Syntax Errors

YAML errors fall into a small number of repeating categories. Recognising the category from the error message — or from the visual appearance of the file — cuts diagnosis time from minutes to seconds.

Indentation errors

YAML requires consistent indentation. The spec does not mandate a specific number of spaces, but every level must be indented further than its parent by the same amount within that block. Mixing two-space and four-space indentation in the same file, or indenting a sequence item by one space less than its sibling, will produce an "unexpected indent" or "could not find expected block entry" error. The safest practice is two spaces per level across the entire file.

Tab characters instead of spaces

The YAML specification explicitly forbids tab characters as indentation. Most parsers throw a "found character that cannot start any token" or "tab character present at the beginning of a line" error when they encounter one. The problem is invisible in most editors unless you enable a "show whitespace" or "render whitespace" option. Configure your editor to always expand tabs to spaces for .yaml and .yml files to eliminate this category entirely.

Warning

Many developers paste YAML from documentation sites, Slack messages, or Stack Overflow answers. These sources frequently convert spaces to tabs during copy-paste. Always paste into a plain-text editor or an online validator first when working with copied YAML.

Unquoted strings with special characters

YAML reserves several characters for structural purposes: colon, hash, asterisk, ampersand, exclamation mark, pipe, greater-than, square brackets, and curly braces. When any of these characters appear in an unquoted string value, the parser may misinterpret them as syntax tokens. The most common manifestation is a URL value like https://example.com:8080 causing a "mapping values are not allowed here" error because the :8080 is parsed as a new mapping key. Quote any string value that contains these characters.

Error TypeTypical Parser MessageRoot CauseFix
Indentation"could not find expected :"Block indented at wrong levelAlign to parent + 2 spaces
Tab character"character that cannot start token"Tab used instead of spaceReplace all tabs with spaces
Unquoted colon"mapping values not allowed here"Colon in bare string valueQuote the value
Duplicate keySilent or implementation-definedSame key appears twice in blockRemove or rename duplicate
Undefined alias"found undefined alias"* references undeclared & anchorDeclare anchor before alias
Multiline scalarParser stops mid-blockWrong block scalar indicatorUse | for literal, > for folded
Boolean coercionWrong type at runtimeyes/no/on/off in YAML 1.1 modeQuote the string: "yes"

How to Read YAML Error Messages

YAML error messages are notoriously terse. Understanding how to decode the two or three pieces of information they do provide saves significant debugging time. Every parser message contains a line and column reference, a description of what was expected, and sometimes a description of what was found instead.

An error on line 30 column 1 usually means the problem started on line 20. Read upward.

YAML error interpretation best practice

The three parts of a parser error

  • Line and column: Points to where parsing failed, not necessarily where the mistake is — look 5–10 lines above
  • Expected token: What the parser was looking for — "expected mapping value" means it expected a colon after a key
  • Found token: What the parser actually encountered — "found block sequence entry" means it hit a - list item where it expected a key

Decoding common message patterns

"could not find expected ':' means the parser read a mapping key but reached the end of the line or a non-colon token before finding the separator. The key may contain a reserved character that ended the key token early, or the colon was accidentally omitted. "mapping values are not allowed here" means a : appeared in a context where the parser was not in a mapping block — typically caused by an unquoted URL or version string. "found duplicate key" is raised by strict parsers (Go's yaml.v3, ruamel.yaml) when the same key name appears more than once in a block — a configuration change where the old key was not removed.

Tip

When debugging, reduce the file to the minimum that still reproduces the error. Comment out or remove large blocks until the error disappears, then add back the last removed block to isolate the exact section. The [YAML Validator](/tools/data/validators/yaml-validator) makes this fast — paste a partial file to check it without running any local tooling.

How to Detect and Fix YAML Errors Step by Step

The fastest path from a broken YAML file to a working one is a structured, category-aware workflow rather than line-by-line eyeballing. These five steps cover every common scenario.

1

Validate the raw document first

Open the YAML Validator and paste your full document. If the validator reports errors, note the line numbers and the message categories before making any changes. Fixing one error at a time and re-validating after each fix prevents accidentally introducing new problems while fixing the original ones.

2

Fix indentation and tab errors

Enable visible whitespace rendering in your editor (VS Code: View → Render Whitespace → All). Replace every tab with two spaces. Ensure every child block is indented exactly two more spaces than its parent. Sequence items (-) count as an indentation level: the content after - should be on the same line or indented two spaces on the next line. Re-validate after this step before proceeding.

3

Quote strings containing special characters

Review every unquoted string value that contains colons, hash signs, asterisks, ampersands, exclamation marks, or pipes. Wrap them in double quotes. Pay particular attention to URLs, version strings like v2.0:latest, and values that start with a brace or bracket (which would be parsed as flow collections, not strings). After quoting, re-validate to confirm the mapping errors are resolved.

4

Check for duplicate keys

Run the YAML Duplicate Key Detector on the same document. Duplicate keys pass basic syntax validation but silently overwrite values at runtime — most CI/CD tools and Kubernetes apply the last value seen, while others apply the first. Either behaviour is dangerous. Remove or rename any duplicates the detector finds.

5

Validate anchors and aliases if used

If your YAML uses & anchors and * aliases — common in Helm values files, Ansible playbooks, and complex Docker Compose configs — run the YAML Anchors and Aliases Validator. It checks that every alias references a declared anchor, that no circular merge-keys exist, and that the anchor names follow consistent conventions.

YAML Validator

Paste any YAML document and get instant syntax and structural error reporting with line and column numbers — runs entirely in your browser, nothing is uploaded.

Open tool

YAML Errors by File Type

Different YAML file types attract different error patterns. Knowing which mistakes are most common in each file type lets you check the right things first instead of scanning the entire document.

GitHub Actions workflows

GitHub Actions workflows fail at the parse stage before any jobs execute, making YAML errors the first thing to fix. The most common mistakes are on: treated as a boolean (true) because on is a YAML 1.1 boolean — quote it as "on" or use the full trigger name. Step run: blocks with multi-line shell scripts using the wrong block scalar indicator (folded > instead of literal |) also cause silent errors where newlines are collapsed. Use | for multi-line shell scripts. The GitHub Actions Workflow Validator checks both YAML syntax and workflow-specific structural rules in one pass.

Kubernetes manifests

Kubernetes YAML errors typically involve deeply nested indentation mistakes — a containers block indented under spec by four spaces when the surrounding blocks use two, or a resources.limits block placed at the wrong nesting level. The Kubernetes API server reports these as field validation errors, not YAML syntax errors, because kubectl apply first parses the YAML successfully and then validates the object schema. Use the Kubernetes Validator to catch both YAML and schema-level issues before applying. The Diff Highlighter for JSON/YAML Configs is useful for comparing manifests across environments.

Docker Compose files

Docker Compose docker-compose.yml errors are most commonly indentation mistakes in service definitions, unquoted port mappings like 3000:3000 (the colons cause a parser error unless quoted or written as a sequence item), and environment variable values that contain equals signs or hash characters without quoting. Always quote environment variable values. The Docker Compose Validator validates both the YAML structure and the Compose-specific schema.

Helm values.yaml files

Helm values.yaml files frequently use YAML anchors for DRY configuration — and anchor-related errors are common after restructuring. The Helm Values Validator validates Helm-specific syntax, while the Helm Values YAML Drift Diff Tool helps you compare values across releases to catch drift introduced by a recent edit.


Ansible playbooks

Ansible playbooks combine standard YAML with Jinja2 template expressions using double curly braces around variable names. The double curly braces are not YAML syntax, but they appear inside YAML string values. If a Jinja expression appears as the entire value of a key without being quoted, Ansible's YAML parser treats the opening brace as the start of a flow mapping. Always quote any YAML value that starts with double curly braces. The Ansible Validator handles both the YAML and Jinja2 layers of playbook validation.

Advanced YAML Error Categories

Beyond basic syntax, several YAML features have their own error categories that require specific diagnostic approaches. These are less common but tend to be harder to diagnose without the right tools.

Duplicate keys — silent data loss

Duplicate keys are the most dangerous YAML error category because they do not cause a parse failure in most parsers. When you refactor a config file and add a new value for a key without removing the old one, both keys coexist in the raw text. Depending on the parser, either the first or last value wins — PyYAML and js-yaml both silently use the last occurrence, while Go's yaml.v3 reports an error. The result is a config file that looks correct when you read it but behaves differently at runtime than you expect.

Warning

Duplicate keys in Kubernetes ConfigMaps and Secrets are particularly dangerous. The YAML parses successfully, kubectl apply accepts the resource, but only one of the duplicate values is stored. The dropped value causes silent misconfiguration in the pod consuming it. Always run the [YAML Duplicate Key Detector](/tools/data/validators/yaml-duplicate-key-detector) before applying infrastructure YAML.

Anchor and alias errors

YAML anchors (&name) allow you to define a value once and reference it elsewhere with an alias (*name). Errors occur when an alias references an anchor that is declared later in the file (forward references are not allowed in YAML), when two anchors share the same name (the second silently overwrites the first), or when a merge key (<<: *alias) is used on a non-mapping node. These errors are invisible to basic validators — only a validator that specifically tracks anchor declarations and alias references will catch them.

Environment variable substitution mismatches

Docker Compose, GitHub Actions, and Ansible all support environment variable substitution inside YAML values. When the environment variable is not set at parse time, the substitution either fails, uses an empty string, or falls back to a default — depending on the syntax used. A YAML document that validates correctly in CI may fail in production because a required environment variable is absent. The YAML Env Substitution Preview Tool lets you preview the expanded YAML document with a specific set of variable values before deployment.

  • $VAR with no default: Fails silently if VAR is unset — substitute an empty string
  • ${"{"}VAR:-default{"}"} syntax: Falls back to "default" if VAR is unset — test both paths
  • ${"{"}VAR:?error message{"}"} syntax: Throws an explicit error if VAR is unset — preferred for required vars
  • Unquoted substitutions starting with a brace: Parser treats variable substitutions as flow mappings — always quote

Preventing YAML Errors Long Term

Fixing individual YAML errors is fast once you know the category. Preventing them from reaching production requires a small set of consistent habits and automated checks.

Editor configuration

Configure your editor to use two-space indentation for YAML files, insert spaces instead of tabs, and enable visible whitespace. In VS Code, install the YAML extension by Red Hat which provides real-time syntax checking, schema validation (for Kubernetes, GitHub Actions, and other formats with published JSON Schemas), and auto-completion. Add a .editorconfig file to your project to enforce these settings for every team member regardless of their local editor configuration.

  • .editorconfig settings for YAML: indent_style = space, indent_size = 2, trim_trailing_whitespace = true
  • VS Code: Install the YAML extension (Red Hat) — it validates schema and syntax in real time
  • JetBrains IDEs: Enable YAML support and set the inspection level to Warning for structural errors
  • Vim/Neovim: Use yaml-language-server via nvim-lspconfig for inline diagnostics
  • Prettier: Formats YAML consistently — prevents whitespace and indentation drift across team members

Automated validation in CI/CD

Add a YAML linting step to your CI pipeline that runs on every pull request touching any .yaml or .yml file. yamllint is the standard CLI tool — it validates syntax, checks for duplicate keys, enforces line length limits, and catches truthy string coercion issues. Configure it with a .yamllint.yaml file at your project root and add it as a pre-commit hook or a CI step that runs before any deployment jobs.

Tip

For Kubernetes-specific projects, combine yamllint for YAML syntax with kubeval or kubeconform for schema validation. The two tools cover different error categories: yamllint catches whitespace and syntax issues, while kubeval catches wrong field names, missing required fields, and type mismatches against the Kubernetes API schema.

Code review discipline

YAML diffs in code review are deceptively easy to approve without catching errors. Two-space versus four-space indentation looks like a formatting preference but changes the document structure. A key moved to a different indentation level changes its parent block. Use the Diff Highlighter for JSON/YAML Configs to review YAML changes semantically — it shows which keys were added, removed, or changed by value rather than by raw line diff, making structural changes immediately visible.

Diff Highlighter for JSON/YAML Configs

Compare two YAML config files at the key-path level to catch structural changes, moved keys, and value updates — better than raw line diffs for infrastructure review.

Open tool

Key takeaways

  • Indentation and tab characters cause the majority of YAML errors — configure your editor to use spaces and show whitespace.
  • YAML parser errors point to where parsing failed, not where the mistake was made — always look 5–10 lines above the reported line.
  • Duplicate keys are the most dangerous error category because they parse successfully but silently overwrite values at runtime.
  • Unquoted strings containing colons, hash signs, asterisks, or braces are misinterpreted as YAML structural tokens — always quote them.
  • Use the YAML Validator for syntax errors, the YAML Duplicate Key Detector for silent overwrites, and the YAML Anchors and Aliases Validator for anchor issues.
  • Add yamllint to your CI pipeline and a .editorconfig to your project to prevent YAML errors from reaching code review.
  • File-type-specific validators (Kubernetes, Docker Compose, GitHub Actions, Ansible) catch schema errors that YAML syntax validation alone cannot.

Frequently Asked Questions

Indentation mistakes are by far the most common cause — YAML uses whitespace to define structure, so a block indented by three spaces instead of two creates a completely different document than intended. The second most common cause is tabs: the YAML spec forbids tab characters as indentation, but many text editors insert them silently. After those two, missing colons, unquoted special characters, and duplicate keys account for the majority of YAML parsing failures encountered in real-world configs.

The Quasar Tools YAML Validator processes your document entirely in your browser with no upload required. Paste your YAML, click Validate, and every error is reported with a line number and a description of what the parser expected. For deeper audits — finding duplicate keys that pass basic validation, or checking anchor and alias references — the YAML Duplicate Key Detector and YAML Anchors and Aliases Validator on the same platform cover those categories.

YAML parsers report the line where they gave up trying to interpret the document, not always the line where the original mistake was made. For example, if you omit a closing colon on line 15, the parser may not notice until line 20 when the next key arrives in an unexpected context. Always look at the 5–10 lines above the reported error line to find the actual source of the problem. An indentation error on a parent block will cascade and surface as an error on a child key lines later.

Yes, and they are one of the hardest bugs to spot because tabs and spaces look identical in most editors. The YAML specification explicitly forbids tab characters for indentation — only space characters (U+0020) are valid. If your editor is configured to expand tabs to spaces, you are safe. If it inserts literal tab characters, the YAML parser will throw a "found character that cannot start any token" or similar error. Enable visible whitespace in your editor or use a validator to catch this instantly.

This error almost always means a colon was placed where the parser did not expect a mapping key. The most frequent cause is an unquoted string value that contains a colon — for example, writing url: https://example.com:8080 without quotes causes the parser to interpret 8080 as a mapping key inside the value. Fix it by quoting the value: url: "https://example.com:8080". A stray colon on a comment-looking line or a misindented key also triggers this error.

A duplicate key error occurs when the same key appears more than once in the same mapping block. The YAML spec says behaviour is undefined for duplicate keys, so different parsers handle it differently: some throw an error, others silently keep the last value, and others keep the first. The dangerous case is silent overwriting — your file parses without an error, but one of the values is ignored. Use the YAML Duplicate Key Detector to find these before they cause runtime bugs in production configs.

This error means the parser expected a colon to separate a mapping key from its value but found something else. The most common cause is a string key that contains special characters (like #, *, :, or &) without being quoted. Wrap the key in double quotes: "key:with:colons": value. A missing colon after a block mapping indicator or a key on a flow mapping line that was not closed before the next key also triggers this message. Check the reported line and the line immediately above it.

Yes. GitHub Actions parses workflow YAML files before executing any jobs. A syntax error in a workflow file causes the run to fail immediately at the parse stage with an "Invalid workflow file" message that references the problematic line. Tab-versus-space errors and misaligned steps are the most common culprits in Action workflows. Run your workflow YAML through the Quasar Tools YAML Validator before pushing, or use the GitHub Actions Workflow Validator for workflow-specific structural checks beyond basic YAML syntax.

ShareXLinkedIn

Related articles