1. Home
  2. Blog
  3. DevOps

DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML runs Kubernetes, Docker Compose, GitHub Actions and countless config files. It looks friendly, but unquoted values can silently turn into booleans, floats and octal numbers. We fed a test file to a real parser to show exactly what happens.

10 min read
YAML explained: syntax, the Norway problem and other traps we tested

Key takeaways

  • YAML represents data with indentation: key-value maps, lists with dashes, and scalar values.
  • Unquoted values are guessed: in our test, NO became False and version 1.10 became 1.1.
  • Quote strings that look like booleans, numbers, times or versions.
  • Never load untrusted YAML with an unsafe loader; use yaml.safe_load in Python.

A configuration file lists the countries a feature is enabled for: GB, SE, FI and NO. Everything works except Norway. The code receives False instead of the string “NO”, because the YAML parser decided that “NO” means “no”. This is the famous Norway problem, and it is only one of several ways YAML quietly changes your data.

We parsed a deliberately tricky file with PyYAML 6.0 on Python 3.13. Every value and type shown below comes from that run. Other parsers, especially those that follow YAML 1.2, can give different results, which is part of the problem.

What is YAML?

YAML, short for “YAML Ain’t Markup Language”, is a human-friendly format for structured data. It holds the same kinds of things as JSON, maps, lists, strings, numbers, booleans and nulls, but uses indentation instead of braces and allows comments. In fact, valid JSON is almost always valid YAML. Its readability made it the default for configuration in DevOps tooling: Kubernetes manifests, Docker Compose files, GitHub Actions workflows and Ansible playbooks.

Basic syntax

# a comment
name: shop-api            # a map: key, colon, space, value
replicas: 3
enabled: true
tags:                     # a list: each item starts with "- "
  - web
  - payments
database:                 # a nested map, indented by two spaces
  host: db.internal
  port: 5432
inline_list: [a, b, c]
inline_map: {x: 1, y: 2}

Indentation shows nesting, and spaces are required after colons and dashes. Two spaces per level is the common convention. Lists of maps, very common in Kubernetes, combine both: each - starts a new map whose keys line up underneath it.

How YAML guesses types

An unquoted value is not automatically a string. The parser looks at it and decides whether it is a boolean, a number, null or a string. Here is what PyYAML produced from our test file:

YAML Parsed value Type
country: NO False bool
enabled: yes True bool
debug: off False bool
version: 1.10 1.1 float
python: 3.10 3.1 float
zip: 01234 668 int
octal: 0755 493 int
port: 08 '08' str
time: 12:30 750 int
sha: 1e10 '1e10' str
empty: None NoneType
tilde: ~ None NoneType
quoted_no: "NO" 'NO' str
quoted_version: "1.10" '1.10' str

Only the quoted values came through exactly as written. Every row above the quoted ones is a potential bug.

The Norway problem

countries: [GB, NO, SE, FI]
# parsed: ['GB', False, 'SE', 'FI']

Under the YAML 1.1 rules, which PyYAML follows, the words yes, no, on, off, y and n in various capitalisations are booleans. So the country code for Norway became False, while its neighbours stayed strings. The same thing can happen to answers in a survey file, to feature flags named “on”, or to any short code that matches one of those words. The fix is simple once you know it: quote the value, "NO".

Numbers that change

Versions become floats

1.10 and 3.10 were parsed as the numbers 1.1 and 3.1, losing the trailing zero. A CI file that asks for Python 3.10 may really be asking for Python 3.1. GitHub Actions users have hit exactly this, and the standard advice is to quote versions: python-version: "3.10". See also our semantic versioning guide for why versions are not numbers.

Leading zeros mean octal

The zip code 01234 became 668, because a leading zero marks an octal (base 8) number in YAML 1.1. That is useful for file permissions like 0755, which became 493, but disastrous for postcodes, phone numbers and IDs. Oddly, 08 stayed a string, because 8 is not a valid octal digit, so similar-looking values can end up with different types in the same file.

Times become seconds

12:30 became 750. YAML 1.1 reads colon-separated numbers as base 60, the “sexagesimal” format, so 12 × 60 + 30 = 750. A schedule or a port mapping such as 22:22 can be silently converted. Docker Compose documentation recommends quoting port mappings for this reason.

And the opposite surprise

1e10 stayed a string in PyYAML, because its float pattern requires a decimal point. Another parser might read it as ten billion. Relying on the parser to guess is the root of every problem in this section.

Rule of thumb: if a value is meant to be text, and it is made only of digits, dots, colons, or is a short word like yes, no, on or off, put it in quotes. Quoting a string is never wrong.

YAML 1.1 vs 1.2

YAML 1.2, published in 2009, fixed much of this. It accepts only true and false as booleans, uses 0o for octal, and drops base-60 numbers. But many widely used libraries, including PyYAML, still follow 1.1 by default, and tools built on them inherit the behaviour. Libraries such as ruamel.yaml for Python implement 1.2. Because two tools may read the same file differently, the only safe habit is to quote ambiguous values regardless of version.

Indentation and tabs

YAML does not allow tab characters for indentation. Our test with a tab produced an error starting while scanning for the next token. Misaligned indentation is just as fatal: a list item indented one space less than its siblings produced while parsing a block mapping. Configure your editor to insert spaces and to show whitespace, and always validate after editing. Indentation errors are the most common reason a deployment fails right after a “small config change”.

Duplicate keys

name: first
name: second
# parsed: {'name': 'second'}

PyYAML accepted the duplicate silently and kept the last value. The YAML specification says keys must be unique, and some parsers reject duplicates, but many do not. In a long Kubernetes manifest, a duplicated key can quietly override a setting defined earlier. Linters catch this reliably.

Multi-line strings

literal: |
  line one
  line two
folded: >
  line one
  line two

# literal: 'line one\nline two\n'
# folded:  'line one line two\n'

The pipe | keeps line breaks, which suits scripts, certificates and SQL. The > folds lines into one, which suits long descriptions. Adding -, as in |-, removes the final newline, which matters when the value is compared exactly or used as a secret.

Anchors and merge keys

defaults: &defaults
  retries: 3
  timeout: 30
prod:
  <<: *defaults
  timeout: 60

# prod: {'retries': 3, 'timeout': 60}

&defaults names a block, *defaults reuses it, and << merges it into a map, with local keys winning. This avoids repetition in Docker Compose and CI files. Use it sparingly: heavy anchor use makes files hard to read, and the << merge key is not part of YAML 1.2, so support varies between tools.

Safe loading

Some YAML loaders can create arbitrary programming-language objects from special tags, which means loading untrusted YAML can run code. PyYAML’s safe_load refuses such tags. When we tried to load a document that asked for os.system, it failed with could not determine a constructor for the tag 'tag:yaml.org,2002:python/object/apply:os.system'. Always use yaml.safe_load unless you have a specific reason not to, and never use the unsafe loaders on files from users or the internet.

Linting and validation

  • yamllint catches tabs, bad indentation, duplicate keys, trailing spaces and truthy values like yes.
  • Schemas check structure and types; editors such as VS Code can validate Kubernetes, Compose and GitHub Actions files against JSON Schemas as you type.
  • Tool-specific checks, such as kubectl apply --dry-run=server or docker compose config, validate against what the tool will actually accept.
  • Run them in CI, so a broken config fails a pull request, not a deployment.

We did not run yamllint or these tool checks for this article. For secrets, keep them out of YAML files altogether and load them from environment variables or a secrets manager.

Final thoughts

YAML is pleasant to read and dangerous to trust blindly. Its type guessing turned a country code into a boolean, versions into floats, a postcode into an octal number and a time into seconds in our test. Quote anything that is meant to be text, use spaces not tabs, load with a safe loader, and put a linter in your pipeline.

Frequently asked questions

What is the Norway problem in YAML?

Under YAML 1.1 rules, the unquoted country code NO is read as the boolean false. In our test, [GB, NO, SE, FI] became [‘GB’, False, ‘SE’, ‘FI’]. Quoting “NO” fixes it.

Why did my version 3.10 become 3.1?

An unquoted 3.10 is parsed as a floating-point number, which drops the trailing zero. Quote versions, such as “3.10”.

Can I use tabs in YAML?

No. YAML requires spaces for indentation. A tab causes a parsing error, as it did in our test.

What is the difference between | and > in YAML?

The | style keeps line breaks exactly. The > style folds lines into one, joining them with spaces.

Is YAML a superset of JSON?

YAML 1.2 is designed to be a superset of JSON, so nearly all JSON documents are valid YAML. The reverse is not true.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
DevOps

SSH Keys Explained: How They Work, ssh-keygen, Ed25519 and Safe Habits

SSH keys explained with keys we generated: public vs private keys, ssh-keygen, Ed25519 vs RSA, fingerprints, passphrases, ssh-agent, authorized_keys, config…

Read article →
DevOps

HTTP Caching Explained: Cache-Control, ETag and 304 Responses, With a Live Test

HTTP caching explained with a small server we ran: Cache-Control directives, max-age, no-cache vs no-store, ETag revalidation and 304 responses,…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →
Databases & SQL

SQL Constraints Explained: NOT NULL, UNIQUE, CHECK and FOREIGN KEY, Tested

SQL constraints explained with tests we ran: NOT NULL, UNIQUE, CHECK, DEFAULT, PRIMARY and FOREIGN KEY, the NULL loopholes, SQLite's…

Read article →
Databases & SQL

SQL Date Functions Explained: Adding, Comparing and Grouping Dates Without Bugs

SQL date functions explained with queries we ran: adding intervals, month-end surprises, date differences, the BETWEEN trap, grouping by day,…

Read article →
Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

Python asyncio explained with code we timed: coroutines, await, gather, TaskGroup, error handling, timeouts, limiting concurrency and the blocking-call mistake…

Read article →
Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Debounce vs throttle in JavaScript explained with timings we measured in Node.js: how each works, simple implementations, leading and trailing…

Read article →
Software Development

Python Context Managers Explained: The with Statement, contextlib and Real Uses

Python context managers explained with code we ran: how with works, __enter__ and __exit__, contextlib.contextmanager, suppress, ExitStack, database transactions and…

Read article →
Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

LLM temperature and top-p explained with a simulation we ran: how probabilities are reshaped, what top-p keeps, recommended settings by…

Read article →
DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML explained with a parser test: basic syntax, lists and maps, the Norway problem, versions turning into floats, octal zip…

Read article →
DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron jobs explained with schedules we verified: the five fields, operators, real examples, the day-of-month OR day-of-week trap, environment problems,…

Read article →
Software Testing

Bug Life Cycle in Software Testing: Every Status, Who Owns It and Common Mistakes

The bug life cycle explained: every defect status from New to Closed, who owns each step, rejected, deferred and reopened…

Read article →
Test Automation

Property-Based Testing in Python: Hypothesis Finds the Bugs Your Examples Miss

Property-based testing explained with Hypothesis tests we ran: properties vs examples, strategies, shrinking, the real bugs it found in our…

Read article →
Databases & SQL

SQL Pagination Explained: OFFSET vs Keyset, With a Million-Row Test

SQL pagination explained with a million-row test we ran: LIMIT and OFFSET, why deep pages get slow, keyset (cursor) pagination,…

Read article →
Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

SQL EXISTS vs IN explained with queries we ran: how each works, why NOT IN returns no rows when a…

Read article →
Software Development

Python Logging Explained: Levels, Handlers, Formatters and Mistakes to Avoid

Python logging explained with code we ran: levels, basicConfig quirks, named loggers, handlers and formatters, logger.exception, lazy formatting, duplicate logs…

Read article →
Software Development

JavaScript Map vs Object: Key Differences, Pitfalls and a Benchmark

JavaScript Map vs Object explained with code we ran in Node.js: key types, ordering, the prototype trap, JSON, size, WeakMap…

Read article →
Software Development

Python Type Hints Explained: Annotations, mypy and the Errors It Catches

Python type hints explained with a real mypy run: basic annotations, Optional and unions, TypedDict, Literal, Protocol, generics, Callable, strict…

Read article →
Artificial Intelligence

LLM Tokens Explained: How AI Models Read Text, Count Costs and Fill Context Windows

LLM tokens explained with a tokenizer we ran: how text is split, why counts differ by language and tokenizer, context…

Read article →
DevOps

Semantic Versioning Explained: MAJOR.MINOR.PATCH, Ranges and Release Rules

Semantic versioning explained with code we ran: MAJOR.MINOR.PATCH rules, pre-releases, correct version sorting, caret and tilde ranges, 0.x versions, lockfiles…

Read article →
DevOps

Git Reset vs Revert: How to Undo Commits Safely, With a Tested Example

Git reset vs revert explained with a repository we built: soft, mixed and hard reset, revert commits, reverting merges, recovering…

Read article →
Software Testing

The Test Pyramid Explained: Layers, Ratios and When to Break the Shape

The test pyramid explained: unit, integration and end-to-end layers, sensible ratios, the ice cream cone anti-pattern, the testing trophy and…

Read article →
Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

pytest fixtures explained with a suite we ran: how fixtures work, scopes, yield teardown, conftest.py, factory fixtures, parametrized fixtures, built-ins…

Read article →
Databases & SQL

SQL Upsert Explained: INSERT ON CONFLICT, MERGE and the REPLACE Trap

SQL upsert explained with queries we ran: INSERT ON CONFLICT DO UPDATE and DO NOTHING, the excluded row, conditional updates,…

Read article →
Databases & SQL

SQL LIKE Operator Explained: Wildcards, Case Sensitivity and Performance

The SQL LIKE operator explained with queries we ran: % and _ wildcards, escaping, NOT LIKE and NULL, case sensitivity…

Read article →
Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

AI hallucinations explained: what they are, why language models produce them, common types, how to reduce them with grounding and…

Read article →
Test Automation

Mocking in Python: unittest.mock, patch and the Mistakes That Make Tests Lie

Mocking in Python with unittest.mock, tested: Mock and return_value, side_effect, patching where a name is used, spec and autospec, mocking…

Read article →
Software Testing

Code Coverage Explained: Line vs Branch Coverage and What 100% Really Means

Code coverage explained with a real coverage.py run: line, branch and condition coverage, reading a report, why 100% coverage can…

Read article →
Artificial Intelligence

What Are AI Agents? How They Work, With a Simple Agent Loop You Can Run

What are AI agents? A plain guide to the agent loop, tools, memory and guardrails, with a small Python loop…

Read article →
Test Automation

TDD vs BDD: Key Differences, One Feature Built Both Ways and When to Use Each

TDD vs BDD explained with one discount feature built both ways: red-green-refactor with code we ran, Given-When-Then scenarios, tools, trade-offs…

Read article →
Software Testing

User Acceptance Testing (UAT): Process, Checklist and Real Examples

User acceptance testing explained: who runs it, how it differs from QA, a seven-step process, a UAT test case template,…

Read article →
Artificial Intelligence

What Are Embeddings? Vectors and Cosine Similarity Explained Simply

What are embeddings? A plain-language guide to vectors, cosine similarity and semantic search, with a small example we ran, common…

Read article →
Test Automation

Flaky Tests: What Causes Them and How to Fix Them for Good

Flaky tests explained with demos we ran: the main causes, how to confirm and diagnose one, proper fixes for timing,…

Read article →
Software Testing

Load Testing vs Stress Testing: Differences, Metrics and k6 Examples

Load testing vs stress testing explained: what each proves, spike and soak tests, the metrics that matter, why averages mislead,…

Read article →