YAML · 12 min read

Common YAML Syntax Errors and How to Fix Them

By StringTo Editorial Team · Updated

Most YAML syntax errors are caused by indentation, misplaced punctuation, ambiguous scalar values, or a structure that changes unexpectedly between mappings and sequences. Messages such as “mapping values are not allowed here,” “expected block end,” and “found character that cannot start any token” indicate where a YAML parser became unable to continue, but the real mistake may be on an earlier line. To fix invalid YAML reliably, start with the first parser error, expose whitespace, and compare the document with the structure the application expects. This guide explains the most common failures with broken and corrected examples, then shows how to separate valid YAML syntax from valid Kubernetes, Docker Compose, or CI configuration.

Fix YAML indentation errors first

Indentation defines hierarchy in YAML. Keys aligned at the same column are siblings, while a more deeply indented key belongs to the preceding mapping or sequence item. One extra or missing space can move a setting into the wrong object or produce an expected block end error. Use a consistent indentation width throughout each block; two spaces per level is a common project convention.

When a parser points at a correctly written key, inspect the lines immediately above it. The previous block may not have returned to the expected indentation level. Format a small surrounding section, count spaces from the left margin, and verify that sibling keys begin in the same column.

Do not repair YAML by aligning values visually after their colons. Only leading indentation controls nesting. Long key names do not require extra spaces before their values, and cosmetic alignment can create confusing diffs. Configure the editor to display whitespace and use a YAML-aware formatter after the document parses successfully.

Invalid:
services:
  api:
    image: example/api
   ports:
      - 8080

Valid:
services:
  api:
    image: example/api
    ports:
      - 8080
  • Keep sibling keys at exactly the same indentation level.
  • Indent child mappings and sequences consistently.
  • Inspect the previous block when the highlighted line looks correct.
  • Use visible whitespace while diagnosing nested configuration.

Replace tabs with spaces

YAML indentation must use spaces, not tab characters. A file can appear aligned in an editor while containing tabs because tab width is rendered visually. Parsers may report a generic token error or reject the line where the first indentation tab appears.

Enable the editor's render-whitespace option and convert leading tabs to spaces. Avoid replacing every tab without review because tab characters inside quoted or block scalar text may be intentional data. The important rule concerns indentation used to establish structure.

Prevent recurrence with editor settings, an EditorConfig file, and continuous-integration validation. Configure YAML files to insert spaces when the Tab key is pressed. A pre-commit check can reject indentation tabs before they enter code review.

# The arrow represents an invisible tab used for indentation.
Invalid:
services:
→api:
→→image: example/api

Valid:
services:
  api:
    image: example/api
  • Convert indentation tabs to spaces.
  • Preserve intentional tabs contained inside quoted data.
  • Configure editors to insert spaces in YAML files.
  • Validate YAML in pre-commit hooks or continuous integration.

Add spaces after colons and sequence markers

A colon separates a mapping key from its value and normally needs whitespace after it. Writing port:8080 can be interpreted as plain text rather than a key named port with the number 8080. This may leave the surrounding mapping incomplete and cause a later parser error that seems unrelated.

A dash introduces an item in a block sequence and also needs a following space. Write dash-space-value, not a dash attached directly to the value. Negative numbers are different: the minus sign belongs to the numeric scalar, while a sequence marker appears at the current indentation level and is followed by whitespace.

Colons can legitimately appear inside strings such as URLs and timestamps. Quote a value when a colon followed by whitespace is part of the intended text, or when syntax highlighting shows that the parser is treating part of the value as a new mapping.

Invalid:
server:
  host:localhost
  ports:
    -8080
    -8081

Valid:
server:
  host: localhost
  ports:
    - 8080
    - 8081
  • Write a space after a mapping colon before a value.
  • Write a space after a block-sequence dash.
  • Quote text containing colon-space when it is not a mapping.
  • Distinguish a sequence marker from the sign of a negative number.

Keep mappings and sequences structurally consistent

A YAML mapping contains key-value pairs, while a sequence contains ordered items. Problems occur when a block begins as one type and later lines are written as the other without the required nesting. A list of service objects needs a dash for each object, and properties belonging to that object must align beneath the same item.

Errors such as expected block end or expected key often mean the parser was still inside a mapping when it encountered a sequence marker at the wrong depth. Trace the hierarchy from the nearest parent key and label each level as mapping or sequence before changing punctuation.

Empty values also require intent. An empty sequence is written as brackets, an empty mapping as braces, an empty string as quotes, and absence can be expressed as null. Leaving a key with no visible value may parse as null, which is different from an empty collection expected by an application schema.

Invalid:
services:
  - name: api
    image: example/api
  name: worker
    image: example/worker

Valid:
services:
  - name: api
    image: example/api
  - name: worker
    image: example/worker
  • Use a dash for every item in a block sequence.
  • Align properties that belong to the same sequence object.
  • Identify whether every nesting level is a mapping or sequence.
  • Represent empty lists, mappings, strings, and null values explicitly.

Quote ambiguous values and special characters

Many strings can be written without quotes, but values beginning with YAML indicators or containing special character combinations may need quoting. A hash preceded by whitespace begins a comment, so unquoted text after it is discarded. A colon followed by whitespace may begin another mapping, and leading braces, brackets, asterisks, ampersands, or exclamation marks have structural meanings.

Quote values that resemble numbers, booleans, nulls, dates, or timestamps when the application requires a string. Parser versions and schemas can interpret plain scalars differently. Account identifiers with leading zeros, application versions, and environment variables are common cases where explicit quotes preserve intent.

Single-quoted YAML strings treat most content literally and escape an apostrophe by doubling it. Double-quoted strings support escape sequences such as newline and Unicode escapes, but backslashes may need escaping. Choose the style that represents the required value clearly rather than adding quotes randomly until validation succeeds.

Potentially ambiguous:
accountId: 00125
release: 1.20
message: deployment #2
pattern: *.json

Explicit strings:
accountId: "00125"
release: "1.20"
message: "deployment #2"
pattern: "*.json"
  • Quote strings containing comment-like or mapping-like characters.
  • Quote numeric-looking identifiers and version strings.
  • Use single quotes for mostly literal content.
  • Use double quotes when YAML escape sequences are required.

Correct multiline block scalar indentation

The vertical bar and greater-than indicators introduce multiline block scalars. A literal block preserves line breaks, while a folded block normally folds line breaks into spaces. The content must be indented more deeply than the key that introduced it, and subsequent mapping keys must return to the correct parent indentation.

An under-indented content line can end the scalar earlier than intended, causing its text to be parsed as a new key or invalid token. An accidentally over-indented line may become part of the content. Review the indentation of every line, including blank lines and embedded shell or configuration snippets.

Chomping indicators control trailing newlines and should be used deliberately. A minus removes final line breaks, while a plus preserves them. These indicators are not usually the cause of syntax failures, but changing them can alter scripts, certificates, templates, and application values even when the YAML remains valid.

Invalid:
script: |
  npm install
npm test
timeout: 60

Valid:
script: |
  npm install
  npm test
timeout: 60
  • Indent every block scalar line beneath its key.
  • Return to the parent indentation for the next mapping key.
  • Choose literal or folded style according to newline requirements.
  • Review trailing-newline behavior for executable scripts and certificates.

Check anchors, aliases, tags, and duplicate keys

Anchors and aliases let a YAML document reuse nodes, but every alias must refer to an anchor available in the document. Misspelled alias names can produce an undefined alias error. Merge behavior and tag support also vary between parsers and destination applications, so syntactically accepted constructs may still be unsupported.

Duplicate mapping keys are especially dangerous because parsers do not handle them uniformly. One loader may reject the document, while another silently keeps the first or last value. Treat duplicate keys as errors and remove the ambiguity rather than relying on a particular loader's behavior.

Use anchors sparingly in deployment configuration. They can reduce repetition but also make effective values harder to review. If the destination platform does not support merge keys or custom tags, expand shared values explicitly or use the platform's supported templating mechanism.

Invalid duplicate key:
service:
  image: example/api:v1
  image: example/api:v2

Clear result:
service:
  image: example/api:v2

Invalid alias:
defaults: &default
  retries: 3
worker: *defaults
  • Ensure alias names exactly match defined anchors.
  • Reject duplicate mapping keys during validation.
  • Verify whether the destination supports merge keys and tags.
  • Prefer explicit configuration when indirection harms reviewability.

Validate YAML syntax and the destination schema

Fix the first reported YAML parser error and validate again until the entire document parses. A YAML validator catches indentation problems, malformed mappings, invalid sequences, undefined aliases, and other grammar failures. Formatting afterward makes the corrected hierarchy easier to inspect.

Syntax validation does not prove that a configuration is usable. Kubernetes requires recognized API versions, resource kinds, metadata, and resource-specific fields. Docker Compose defines allowed service properties and value types. CI platforms may accept only specific keys, expressions, and event structures. Run the destination's schema validator or native validation command after generic YAML parsing succeeds.

Keep sensitive configuration local where possible. Remove credentials from examples, avoid placing private YAML in shareable URLs, and use a secret-management system instead of committing plaintext secrets. StringTo's YAML Validator and Formatter process interactive editor content locally, while YAML to JSON can help inspect the parsed data structure.

Debugging checklist:
1. Preserve the original file.
2. Display spaces and tabs.
3. Fix the first parser error.
4. Repeat YAML syntax validation.
5. Format and review the hierarchy.
6. Run platform-specific validation.
7. Test the change before production.
  • Separate YAML syntax validity from application-schema validity.
  • Use platform-specific validators after generic parsing.
  • Review the formatted diff before merging changes.
  • Process private configuration locally and manage secrets separately.

Frequently asked questions

How do I find a YAML syntax error?

Start with the first line and column reported by a strict YAML parser. Inspect that location and the preceding block, display whitespace, and verify the indentation of sibling keys. Fix one error at a time and validate again.

What does mapping values are not allowed here mean?

The parser encountered a colon where a mapping value cannot begin. Common causes include incorrect indentation, a missing quote around colon-containing text, a missing space after an earlier colon, or an unfinished structure on the preceding line.

What causes expected block end in YAML?

A mapping or sequence usually changed indentation unexpectedly. Check whether a sibling key returned to the correct column, whether a sequence item is missing a dash, and whether a multiline block ended at the intended indentation.

Can YAML use tabs for indentation?

No. YAML indentation uses spaces. Configure your editor to insert spaces for YAML files and display whitespace so leading tabs can be identified and replaced safely.

Why is valid YAML rejected by Kubernetes or Docker Compose?

Generic YAML validation checks syntax only. Kubernetes and Docker Compose apply their own schemas with required fields, supported properties, and type rules. Run the appropriate platform-specific validator after YAML parsing succeeds.

Should YAML values always be quoted?

No. Quote values when they contain syntax-significant characters or must remain strings despite resembling numbers, booleans, nulls, dates, or timestamps. Unnecessary quoting is valid in many cases but can reduce readability.

Related developer tools