---
title: "YAML"
lang: "en"
author: "Mohammad Abu Mattar"
canonical: https://mkabumattar.com/yaml
---

[Home](/)›[Cheatsheets](/cheatsheets)

Cheatsheets

# YAML

YAML (YAML Ain't Markup Language) is a human-friendly data serialization language commonly used for configuration files, data exchange, and infrastructure-as-code. It emphasizes readability and uses indentation to structure data.

6 Categories18 Sections36 ExamplesPublished: 01 May 2023Updated: 27 Feb 2025

YAMLConfigurationData SerializationSyntaxIndentationKeysValuesAnchorsAliases

[Markdown for AI(opens in a new tab)](/yaml/index.md "Open the plain-Markdown version of this page, for pasting into an AI tool")

Series

[Config & Data Formats](/series/config--data-formats)2/5

[PreviousRegEx](/cheatsheets/regex)[NextJSON](/cheatsheets/json)

All posts in this series (5)

Cheatsheets5

1.  [RegEx](/cheatsheets/regex)
2.  [YAMLYou are here](/cheatsheets/yaml)
3.  [JSON](/cheatsheets/json)
4.  [Markdown](/cheatsheets/markdown)
5.  [TOML](/cheatsheets/toml)

YAML (YAML Ain’t Markup Language) is a human-friendly data serialization language widely used for configuration files, data exchange, and infrastructure-as-code. It emphasizes readability and uses indentation to structure data.

The sections below cover YAML syntax, data structures, and practical examples.

[Getting Started](#category-getting-started)

-   [Basic Syntax](#section-basic-syntax)
-   [Data Types](#section-data-types)
-   [Comments](#section-comments)

[Data Structures](#category-data-structures)

-   [Dictionaries](#section-dictionaries)
-   [Lists](#section-lists)
-   [Mixed Structures](#section-mixed-structures)

[Advanced Syntax](#category-advanced-syntax)

-   [Multiline Strings](#section-multiline-strings)
-   [Special Strings](#section-special-strings)
-   [Anchors and Aliases](#section-anchors-and-aliases)

[Advanced Features](#category-advanced-features)

-   [Anchors](#section-anchors)
-   [Aliases](#section-aliases)
-   [Merge Keys](#section-merge-keys)

[Collections and Nesting](#category-collections-and-nesting)

-   [Nested Dictionaries](#section-nested-dicts)
-   [Nested Lists](#section-nested-lists)
-   [Complex Nesting](#section-complex-nesting)

[Practical Examples](#category-practical-examples)

-   [Configuration Files](#section-configuration-files)
-   [Best Practices](#section-best-practices)
-   [Validation and Use](#section-validation-and-use)

No commands found

Try adjusting your search term

## Getting Started

Fundamental YAML concepts and basic syntax for beginners.

### Basic Syntax

YAML fundamentals including comments, key-value pairs, and indentation rules.

#### Accessibility

Ensure code examples are properly formatted for screen readers.

#### Best Practices

-   Use consistent indentation throughout your YAML files (typically 2 spaces).
-   Keep comments meaningful and up-to-date.
-   Use dashes consistently for list items.

#### Common Errors

-   **Mixing tabs and spaces for indentation:** Use only spaces for indentation; most editors can convert tabs to spaces.
-   **Missing space after colon in key-value pairs:** Always write key: value, not key:value.

#### Advanced Notes

-   **Indentation Rules:** Indentation determines nesting and structure; inconsistent indentation causes parsing errors.
-   **Schema Validation:** Use YAML schema validators to catch syntax errors early in development.

#### Keywords

syntaxyamlcommentsindentationkey-value

[Learn more](https://yaml.org/spec/1.2/spec.html)

#### Basic key-value pair

Simple key-value pairs are the foundation of YAML syntax. Keys are followed by a colon and space, then the value.

Code

```
1name: John Doe2age: 303city: New York
```

Execution

```
1python -c "import yaml; print(yaml.safe_load(open('config.yaml')))"
```

Output

```
1{'name': 'John Doe', 'age': 30, 'city': 'New York'}
```

-   Indentation matters in YAML; use spaces, not tabs.
-   Keys and values are separated by a colon and at least one space.

#### Comments in YAML

Comments begin with

Code

```
1# This is a comment2name: John Doe  # inline comment3age: 304# Another comment5city: New York
```

Execution

```
1python -c "import yaml; print(yaml.safe_load(open('config.yaml')))"
```

Output

```
1{'name': 'John Doe', 'age': 30, 'city': 'New York'}
```

-   Comments can be placed on their own line or at the end of a line.
-   Use comments to document configuration intent and choices.

### Data Types

Understanding YAML data types including strings, numbers, booleans, and null values.

#### Accessibility

Label data types clearly for screen reader access.

#### Best Practices

-   Be explicit with data types when clarity is needed.
-   Quote strings containing special characters or numbers.
-   Use null or empty values intentionally and document reasons.

#### Common Errors

-   **Number interpreted as string or vice versa:** Use quotes explicitly when you need to control type interpretation.
-   **Boolean values misinterpreted:** Quote booleans as strings if needed: "true" instead of true.

#### Keywords

data-typesyamlstringsnumbersboolean

[Learn more](https://yaml.org/spec/1.2/spec.html#id2805071)

#### Different data types

YAML automatically infers data types based on content. Explicitly quote strings to avoid type inference issues.

Code

```
1string: "Hello World"2integer: 423float: 3.144boolean_true: true5boolean_false: false6null_value: null
```

Execution

```
1python -c "import yaml; print(yaml.safe_load(open('types.yaml')))"
```

Output

```
1{'string': 'Hello World', 'integer': 42, 'float': 3.14, 'boolean_true': True, 'boolean_false': False, 'null_value': None}
```

-   YAML supports strings, integers, floats, booleans, and null values.
-   Unquoted strings like 'true' and 'false' are parsed as booleans.

#### Quoted strings

Quoting forces YAML to treat values as strings. Single and double quotes work similarly in YAML.

Code

```
1single_quoted: 'hello'2double_quoted: "world"3unquoted: plain text4number_as_string: '42'
```

Execution

```
1python -c "import yaml; print(yaml.safe_load(open('quotes.yaml')))"
```

Output

```
1{'single_quoted': 'hello', 'double_quoted': 'world', 'unquoted': 'plain text', 'number_as_string': '42'}
```

-   Quote numbers if you want them treated as strings.
-   Unquoted strings are converted based on content interpretation.

### Comments

How to use comments in YAML files for documentation and clarity.

#### Accessibility

Ensure comment content is semantically meaningful for all users.

#### Best Practices

-   Use comments to explain configuration intent and non-obvious choices.
-   Keep comments up-to-date when you modify configuration values.
-   Use section comments to organize large YAML files.

#### Common Errors

-   **Comments affecting parsing:** Keep comments on their own lines or at the end of lines.
-   **Outdated comments causing confusion:** Review and update comments regularly when modifying configuration.

#### Keywords

commentsyamldocumentationinlineblock

[Learn more](https://yaml.org/spec/1.2/spec.html#id2529584)

#### Comment placement and styles

Comments provide documentation without affecting the parsed data structure.

Code

```
1# Top-level comment explaining the file2# This configuration defines application settings3
4app:5  name: MyApp  # The application name6  version: 1.0  # Version number7  # Debug mode settings8  debug: false
```

Execution

```
1python -c "import yaml; print(yaml.safe_load(open('comments.yaml')))"
```

Output

```
1{'app': {'name': 'MyApp', 'version': 1.0, 'debug': False}}
```

-   Comments are ignored during parsing and do not appear in the output.
-   Use comments to explain the purpose of configuration values.

#### Documenting complex structures

Comments help explain the purpose of configuration sections and individual settings.

Code

```
1# Database connection settings2database:3  # Connection string for PostgreSQL4  host: localhost5  port: 5432  # Standard PostgreSQL port6  # Credentials for authentication7  username: admin8  password: secret
```

Execution

```
1python -c "import yaml; print(yaml.safe_load(open('db_config.yaml')))"
```

Output

```
1{'database': {'host': 'localhost', 'port': 5432, 'username': 'admin', 'password': 'secret'}}
```

-   Group related comments with the sections they document.
-   Keep comments concise and focused on the 'why', not the 'what'.

## Data Structures

Understanding dictionaries, lists, and mixed nested structures in YAML.

### Dictionaries

Creating and using dictionaries (key-value mappings) in YAML.

#### Accessibility

Clearly label dictionary structures for screen readers.

#### Best Practices

-   Use clear and descriptive key names.
-   Limit nesting depth to keep configurations readable (3-4 levels typically).
-   Group related keys within the same dictionary level.

#### Common Errors

-   **Incorrect indentation breaking dictionary structure:** Verify all related keys have the same indentation level.
-   **Mixing tabs and spaces breaking parsing:** Use a YAML linter to validate indentation consistency.

#### Keywords

dictionarymappingkey-valueyamlnested

[Learn more](https://yaml.org/spec/1.2/spec.html#id2504510)

#### Simple dictionary

A dictionary is created by indenting key-value pairs under a parent key.

Code

```
1person:2  name: John Doe3  age: 304  email: john@example.com
```

Execution

```
1python -c "import yaml; print(yaml.safe_load(open('person.yaml')))"
```

Output

```
1{'person': {'name': 'John Doe', 'age': 30, 'email': 'john@example.com'}}
```

-   Use consistent indentation to define dictionary membership.
-   Each key-value pair must have the same indentation level.

#### Nested dictionaries

Dictionaries can be nested multiple levels deep by continuing to indent.

Code

```
1user:2  profile:3    name: Alice4    contact:5      email: alice@example.com6      phone: "555-1234"7  settings:8    theme: dark9    notifications: true
```

Execution

```
1python -c "import yaml; print(yaml.safe_load(open('nested.yaml')))"
```

Output

```
1{'user': {'profile': {'name': 'Alice', 'contact': {'email': 'alice@example.com', 'phone': '555-1234'}}, 'settings': {'theme': 'dark', 'notifications': True}}}
```

-   Each level of nesting increases indentation by 2 spaces.
-   Maintain consistent indentation to correctly represent hierarchy.

### Lists

Creating and using lists (arrays) in YAML.

#### Accessibility

Mark list items clearly for screen reader navigation.

#### Best Practices

-   Keep list items simple; consider using dictionaries for complex items.
-   Use consistent indentation for all list items.
-   Order list items logically (alphabetical, by importance, etc.).

#### Common Errors

-   **Mixing list syntax with dictionary syntax:** Use dashes for lists, not colons; colons are for dictionaries.
-   **Incorrect dash placement breaking list structure:** Keep dashes at the same indentation level: - item.

#### Keywords

listarrayyamlitemsdash

[Learn more](https://yaml.org/spec/1.2/spec.html#id2534302)

#### Simple list

Lists are created using dashes (-) followed by a space, with each item on a new line.

Code

```
1fruits:2  - apple3  - banana4  - orange5  - grape
```

Execution

```
1python -c "import yaml; print(yaml.safe_load(open('fruits.yaml')))"
```

Output

```
1{'fruits': ['apple', 'banana', 'orange', 'grape']}
```

-   Each list item starts with a dash and a space.
-   All list items must have the same indentation level.

#### Nested lists

Lists can contain other lists, creating multi-dimensional structures.

Code

```
1matrix:2  - - 13    - 24    - 35  - - 46    - 57    - 68  - - 79    - 810    - 9
```

Execution

```
1python -c "import yaml; print(yaml.safe_load(open('matrix.yaml')))"
```

Output

```
1{'matrix': [[1, 2, 3], [4, 5, 6], [7, 8, 9]]}
```

-   Nested lists use additional indentation and dashes.
-   Readability decreases with deep nesting; simplify when possible.

### Mixed Structures

Combining dictionaries and lists in complex nested structures.

#### Accessibility

Clearly label mixed structure components for accessibility.

#### Best Practices

-   Avoid deeply nested structures; flatten when possible for readability.
-   Use meaningful key names to clarify structure purpose.
-   Test complex YAML structures with a parser to catch errors early.

#### Common Errors

-   **Mixing list and dictionary syntax incorrectly:** Remember dashes are for list items; use proper indentation for dictionary keys.
-   **Indentation misalignment breaking the structure:** Use a YAML linter and editor with YAML support for validation.

#### Keywords

mixedlistdictionaryyamlnestedcomplex

[Learn more](https://yaml.org/spec/1.2/spec.html#id2535173)

#### List of dictionaries

Each list item is a dictionary with multiple key-value pairs. The dash precedes the first key of each dictionary.

Code

```
1employees:2  - name: Alice3    department: Engineering4    salary: 800005  - name: Bob6    department: Sales7    salary: 600008  - name: Carol9    department: Engineering10    salary: 85000
```

Execution

```
1python -c "import yaml; print(yaml.safe_load(open('employees.yaml')))"
```

Output

```
1{'employees': [{'name': 'Alice', 'department': 'Engineering', 'salary': 80000}, {'name': 'Bob', 'department': 'Sales', 'salary': 60000}, {'name': 'Carol', 'department': 'Engineering', 'salary': 85000}]}
```

-   The dash and first key are at the same indentation level.
-   Subsequent keys are indented to align under the first key.

#### Dictionary with list values

Dictionary values can be lists. The list starts on the next indented line with dashes.

Code

```
1project:2  name: MyProject3  team:4    - Alice5    - Bob6    - Carol7  tools:8    - Python9    - Docker10    - Kubernetes
```

Execution

```
1python -c "import yaml; print(yaml.safe_load(open('project.yaml')))"
```

Output

```
1{'project': {'name': 'MyProject', 'team': ['Alice', 'Bob', 'Carol'], 'tools': ['Python', 'Docker', 'Kubernetes']}}
```

-   List values are indented further than the parent key.
-   Each list item is indented consistently.

## Advanced Syntax

Advanced YAML features like multiline strings and special characters.

### Multiline Strings

Handling strings that span multiple lines using block scalars.

#### Accessibility

Ensure multiline content is properly structured for accessibility.

#### Best Practices

-   Use literal blocks (|) for code and formatted text requiring exact formatting.
-   Use folded blocks (>) for descriptions and natural language text.
-   Add strip or keep indicators (|- or |+) to control trailing newlines.

#### Common Errors

-   **Incorrect indentation in block scalars causing parsing errors:** Indent all content below the block scalar indicator.
-   **Mixing literal and folded syntax:** Use | for exact formatting, > for natural text wrapping.

#### Keywords

multilinestringyamlliteralfoldedblock

[Learn more](https://yaml.org/spec/1.2/spec.html#id2793877)

#### Literal block scalar

The pipe (|) operator preserves newlines and formatting within the string.

Code

```
1description: |2  This is a literal block scalar.3  Newlines are preserved exactly as written.4  Each line becomes a separate line in the string.
```

Execution

```
1python -c "import yaml; print(repr(yaml.safe_load(open('literal.yaml'))['description']))"
```

Output

```
1'This is a literal block scalar.\nNewlines are preserved exactly as written.\nEach line becomes a separate line in the string.\n'
```

-   Literal blocks preserve all whitespace and newlines.
-   Content must be indented below the pipe character.

#### Folded block scalar

The greater-than (>) operator folds lines into a single line, preserving paragraph breaks.

Code

```
1summary: >2  This is a folded block scalar.3  Line breaks are converted to spaces.4  Paragraphs are separated by blank lines.
```

Execution

```
1python -c "import yaml; print(repr(yaml.safe_load(open('folded.yaml'))['summary']))"
```

Output

```
1'This is a folded block scalar. Line breaks are converted to spaces. Paragraphs are separated by blank lines.\n'
```

-   Folded blocks join lines with spaces.
-   Blank lines create paragraph separations.

### Special Strings

Handling quoted strings, escape sequences, and special characters.

#### Accessibility

Properly formatted special characters for screen readers.

#### Best Practices

-   Quote strings containing special characters or colons.
-   Use double quotes for escape sequences; single quotes for literal strings.
-   Document strings containing escape sequences to clarify intent.

#### Common Errors

-   **Unquoted colons or special characters breaking parsing:** Quote the entire string value.
-   **Escape sequences not working in single quotes:** Use double quotes if you need escape sequences to be interpreted.

#### Keywords

special-stringsyamlquotesescapecharacters

[Learn more](https://yaml.org/spec/1.2/spec.html#id2534521)

#### Quoted strings with escapes

Double and single quotes allow special characters and escape sequences within strings.

Code

```
1single: 'It''s a string'2double: "Line 1\nLine 2"3path: "C:\\Users\\name\\file.txt"4colon: "key: value"
```

Execution

```
1python -c "import yaml; d = yaml.safe_load(open('quoted.yaml')); print({k: repr(v) for k, v in d.items()})"
```

Output

```
1{'single': "It's a string", 'double': 'Line 1\nLine 2', 'path': 'C:\\Users\\name\\file.txt', 'colon': 'key: value'}
```

-   Single quotes preserve most escapes literally; double quotes interpret them.
-   Escape special characters like colons by quoting the entire string.

#### Escape sequences

Escape sequences in double-quoted strings are interpreted as special characters.

Code

```
1newline: "Line 1\nLine 2"2tab: "Column1\tColumn2"3quote: "She said \"hello\""4backslash: "Path: C:\\\\folder"
```

Execution

```
1python -c "import yaml; d = yaml.safe_load(open('escapes.yaml')); print({k: repr(v) for k, v in d.items()})"
```

Output

```
1{'newline': 'Line 1\nLine 2', 'tab': 'Column1\tColumn2', 'quote': 'She said "hello"', 'backslash': 'Path: C:\\folder'}
```

-   Common escapes include \\\\n (newline), \\\\t (tab), \\\\\\\\ (backslash).
-   Single quotes do not interpret most escape sequences.

### Anchors and Aliases

Creating references to reuse content within a YAML file.

#### Accessibility

Ensure anchor-alias relationships are clearly labeled.

#### Best Practices

-   Use anchors to reduce duplication in configuration files.
-   Name anchors clearly to indicate their purpose (e.g., &default\_db, &common\_settings).
-   Document which sections use aliases for clarity.

#### Common Errors

-   **Using undefined anchors in aliases:** Define anchors before they are referenced.
-   **Circular references between anchors causing infinite loops:** Verify anchor definitions do not directly or indirectly reference themselves.

#### Keywords

anchorsaliasesyamlreferencereuse

[Learn more](https://yaml.org/spec/1.2/spec.html#alias//)

#### Basic anchor and alias

Anchors (&) mark content for reference, and aliases (\*) reuse that content with the merge key (<<).

Code

```
1defaults: &default_settings2  timeout: 303  retries: 34  debug: false5
6api_config:7  <<: *default_settings8  endpoint: https://api.example.com
```

Execution

```
1python -c "import yaml; print(yaml.safe_load(open('anchor.yaml')))"
```

Output

```
1{'defaults': {'timeout': 30, 'retries': 3, 'debug': False}, 'api_config': {'timeout': 30, 'retries': 3, 'debug': False, 'endpoint': 'https://api.example.com'}}
```

-   Anchors are defined with & followed by a name.
-   Aliases reference anchors with \* followed by the same name.

#### Multiple alias usage

The same anchor can be referenced multiple times by different aliases throughout the file.

Code

```
1common: &common_values2  version: 1.03  author: 'Mohammad Abu Mattar'4
5service1:6  <<: *common_values7  name: Service One8
9service2:10  <<: *common_values11  name: Service Two
```

Execution

```
1python -c "import yaml; print(yaml.safe_load(open('multi_alias.yaml')))"
```

Output

```
1{'common': {'version': 1.0, 'author': 'Admin'}, 'service1': {'version': 1.0, 'author': 'Admin', 'name': 'Service One'}, 'service2': {'version': 1.0, 'author': 'Admin', 'name': 'Service Two'}}
```

-   Each alias creates an independent copy of the anchored content.
-   Anchors must be defined before they are used with aliases.

## Advanced Features

Anchors, aliases, and merge keys for configuration inheritance.

### Anchors

Defining and naming anchors for content reuse.

#### Accessibility

Clearly mark anchor definitions for reference and search.

#### Best Practices

-   Use descriptive anchor names: &database\_defaults, &common\_env.
-   Define anchors near the configuration they represent.
-   Document anchor usage for maintainability.

#### Common Errors

-   **Anchor defined but never used:** Remove unused anchors or use them with aliases.
-   **Duplicate anchor names in same file:** Use unique names for each anchor.

#### Keywords

anchorsyamlampersandreferencedefinition

[Learn more](https://yaml.org/spec/1.2/spec.html#alias-tag)

#### Defining anchors

Anchors are defined using & followed by a name, marking content for later reference.

Code

```
1default_env: &default_env2  LOG_LEVEL: info3  DEBUG: false4
5db_config: &db_defaults6  host: localhost7  port: 54328  pool_size: 10
```

Execution

```
1python -c "import yaml; print(yaml.safe_load(open('anchors.yaml')))"
```

Output

```
1{'default_env': {'LOG_LEVEL': 'info', 'DEBUG': False}, 'db_config': {'host': 'localhost', 'port': 5432, 'pool_size': 10}}
```

-   Anchor names should be descriptive and follow naming conventions.
-   Anchors mark the exact structure they're placed on (dictionaries or values).

#### Named anchors for inheritance

Named anchors allow defining base configurations that can be inherited by multiple services.

Code

```
1base_service: &base2  image: ubuntu:20.043  restart_policy: always4  environment:5    APP_ENV: production6
7web_service:8  <<: *base9  ports:10    - 80:8080
```

Execution

```
1python -c "import yaml; print(yaml.safe_load(open('base.yaml')))"
```

Output

```
1{'base_service': {'image': 'ubuntu:20.04', 'restart_policy': 'always', 'environment': {'APP_ENV': 'production'}}, 'web_service': {'image': 'ubuntu:20.04', 'restart_policy': 'always', 'environment': {'APP_ENV': 'production'}, 'ports': ['80:8080']}}
```

-   Anchors are local to the file and cannot be referenced across files.
-   The merge key (<<) combines anchored content with additional properties.

### Aliases

Using aliases to reference anchored content.

#### Accessibility

Clearly link aliases to their anchor definitions.

#### Best Practices

-   Use aliases when the same configuration is needed in multiple places.
-   Comment which anchor each alias references for clarity.
-   Limit anchor scope to related configurations.

#### Common Errors

-   **Reference to non-existent anchor:** Verify anchor name matches exactly and is defined before the alias.
-   **Circular alias references:** Check that aliases do not directly or indirectly reference themselves.

#### Keywords

aliasesyamlasteriskreferenceusage

[Learn more](https://yaml.org/spec/1.2/spec.html#alias//)

#### Using aliases

Aliases (asterisk) reference anchored content, creating independent copies in each location.

Code

```
1shared_config: &shared2  timeout: 303  retries: 34
5api_service:6  name: API7  config: *shared8
9worker_service:10  name: Worker11  config: *shared
```

Execution

```
1python -c "import yaml; d = yaml.safe_load(open('alias_usage.yaml')); import json; print(json.dumps(d, indent=2))"
```

Output

```
1{2  "shared_config": {"timeout": 30, "retries": 3},3  "api_service": {"name": "API", "config": {"timeout": 30, "retries": 3}},4  "worker_service": {"name": "Worker", "config": {"timeout": 30, "retries": 3}}5}
```

-   An alias creates a new copy of the anchored content, not a reference.
-   Aliases must refer to previously defined anchors.

#### Multiple references to same anchor

A single anchor can be referenced multiple times throughout the file via separate aliases.

Code

```
1defaults: &defaults2  cache: redis3  cache_ttl: 36004
5app_settings:6  cache_settings: *defaults7
8service_settings:9  cache_settings: *defaults10
11worker_settings:12  cache_settings: *defaults
```

Execution

```
1python -c "import yaml; print(yaml.safe_load(open('multi_ref.yaml')))"
```

Output

```
1{'defaults': {'cache': 'redis', 'cache_ttl': 3600}, 'app_settings': {'cache_settings': {'cache': 'redis', 'cache_ttl': 3600}}, 'service_settings': {'cache_settings': {'cache': 'redis', 'cache_ttl': 3600}}, 'worker_settings': {'cache_settings': {'cache': 'redis', 'cache_ttl': 3600}}}
```

-   Each alias reference creates an independent copy of the content.
-   Modifying one copy does not affect others.

### Merge Keys

Using the merge key (<<) to inherit and extend configurations.

#### Accessibility

Document merge key usage clearly for navigation.

#### Best Practices

-   Use merge keys to reduce configuration duplication.
-   Place merge keys at the beginning of a dictionary for clarity.
-   Document inherited properties to maintain clarity.

#### Common Errors

-   **Merge key does not properly override values:** Place override values after the merge key so they take precedence.
-   **Using merge key with non-existing anchor:** Verify the anchor exists and is defined before the merge key.

#### Keywords

merge-keysyamlinheritanceextendoverride

[Learn more](https://yaml.org/spec/1.2/spec.html#merge-key)

#### Using merge key for inheritance

The merge key (<<) incorporates anchored content and allows overriding specific values.

Code

```
1defaults: &defaults2  timeout: 303  retries: 34  debug: false5
6production:7  <<: *defaults8  environment: production9  debug: false10
11staging:12  <<: *defaults13  environment: staging14  debug: true
```

Execution

```
1python -c "import yaml; print(yaml.safe_load(open('merge_inherit.yaml')))"
```

Output

```
1{'defaults': {'timeout': 30, 'retries': 3, 'debug': False}, 'production': {'timeout': 30, 'retries': 3, 'debug': False, 'environment': 'production'}, 'staging': {'timeout': 30, 'retries': 3, 'debug': True, 'environment': 'staging'}}
```

-   The merge key must be used with an alias.
-   Values defined after the merge key override inherited values.

#### Multiple merge keys

Multiple anchors can be merged using a list syntax \[\*anchor1, \*anchor2\].

Code

```
1base: &base2  port: 80803  timeout: 304
5logging: &logging6  log_level: info7  log_file: /var/log/app.log8
9service:10  <<: [*base, *logging]11  name: MyService12  replicas: 3
```

Execution

```
1python -c "import yaml; print(yaml.safe_load(open('multi_merge.yaml')))"
```

Output

```
1{'base': {'port': 8080, 'timeout': 30}, 'logging': {'log_level': 'info', 'log_file': '/var/log/app.log'}, 'service': {'port': 8080, 'timeout': 30, 'log_level': 'info', 'log_file': '/var/log/app.log', 'name': 'MyService', 'replicas': 3}}
```

-   When multiple anchors are merged, keys from later anchors override earlier ones if there are conflicts.

## Collections and Nesting

Deep nesting, complex hierarchies, and organizing multi-level structures.

### Nested Dictionaries

Creating and managing deeply nested dictionary structures.

#### Accessibility

Ensure nested structure hierarchy is clear and navigable.

#### Best Practices

-   Limit nesting depth for readability.
-   Use meaningful key names to clarify structure purpose.
-   Avoid excessive indentation by structuring hierarchies appropriately.

#### Common Errors

-   **Indentation mismatch breaking dictionary structure:** Verify all related keys have the same indentation level.
-   **Over-nesting causing reduced readability:** Flatten structure by using more descriptive key names at higher levels.

#### Keywords

nested-dictsyamlhierarchyindentationdepth

[Learn more](https://yaml.org/spec/1.2/spec.html#id2504510)

#### Simple nested dictionaries

Nested dictionaries use increasing indentation to show hierarchical relationships.

Code

```
1company:2  name: TechCorp3  location: New York4  departments:5    engineering:6      team_lead: Alice7      members: 108    sales:9      team_lead: Bob10      members: 5
```

Execution

```
1python -c "import yaml; d = yaml.safe_load(open('nested_dict.yaml')); print(d['company']['departments']['engineering'])"
```

Output

```
1{'team_lead': 'Alice', 'members': 10}
```

-   Each indentation level represents one level of nesting.
-   Maintain consistent indentation (typically 2 spaces per level).

#### Deeply nested structure

Multiple levels of nesting create a clear hierarchy for complex configurations.

Code

```
1system:2  server:3    production:4      database:5        primary:6          host: prod-db-1.example.com7          port: 54328          credentials:9            username: prod_user10            password: secret123
```

Execution

```
1python -c "import yaml; d = yaml.safe_load(open('deep_nest.yaml')); print(d['system']['server']['production']['database']['primary']['credentials'])"
```

Output

```
1{'username': 'prod_user', 'password': 'secret123'}
```

-   Keep nesting reasonable (3-4 levels) for readability.
-   Consider flattening deeply nested structures using descriptive keys.

### Nested Lists

Creating and managing lists containing other lists.

#### Accessibility

Make nested list items clearly distinguishable.

#### Best Practices

-   Avoid deeply nested lists exceeding 2-3 levels.
-   Consider using list-of-dicts for more complex structures.
-   Use comments to clarify nested list purposes.

#### Common Errors

-   **Misaligned dashes breaking list nesting:** Keep the dashes at one indentation level for each list level.
-   **Mixing list and dictionary syntax:** Use dashes for lists, keys for dictionaries.

#### Keywords

nested-listsyamlarraymulti-dimensional

[Learn more](https://yaml.org/spec/1.2/spec.html#id2531618)

#### List of lists

Nested lists use additional dashes and indentation to represent multi-dimensional arrays.

Code

```
1grid:2  - - North3    - South4    - East5    - West6  - - Up7    - Down8    - Left9    - Right
```

Execution

```
1python -c "import yaml; print(yaml.safe_load(open('grid.yaml')))"
```

Output

```
1{'grid': [['North', 'South', 'East', 'West'], ['Up', 'Down', 'Left', 'Right']]}
```

-   Each nesting level adds one dash and indentation.
-   Readability decreases with excessive nesting.

#### List with mixed nesting

Nested lists can represent matrices or multi-dimensional structures.

Code

```
1data:2  - - 13    - 24  - - 35    - 46  - - 57    - 6
```

Execution

```
1python -c "import yaml; print(yaml.safe_load(open('mixed_nest.yaml')))"
```

Output

```
1{'data': [[1, 2], [3, 4], [5, 6]]}
```

-   Consistent indentation is critical for correct parsing.

### Complex Nesting

Combining lists and dictionaries in complex structures.

#### Accessibility

Label complex structures clearly for screen reader navigation.

#### Best Practices

-   Use meaningful names for keys and list items.
-   Keep nesting reasonable; simplify overly complex structures.
-   Use anchors and aliases to reduce duplication in nested structures.

#### Common Errors

-   **Indentation confusion breaking the structure:** Use a YAML validator to check structure integrity.
-   **Mixing list and dict syntax at nesting levels:** Be explicit about expected structure: lists use dashes, dicts use key names.

#### Keywords

complex-nestingyamllist-of-objectshierarchy

[Learn more](https://yaml.org/spec/1.2/spec.html#id2529726)

#### List of objects with nested values

Complex structures combine list items (projects) with nested list values (tasks), each containing dictionaries.

Code

```
1projects:2  - name: ProjectA3    status: active4    tasks:5      - name: Task 16        assigned_to: Alice7        priority: high8      - name: Task 29        assigned_to: Bob10        priority: medium11  - name: ProjectB12    status: planning13    tasks:14      - name: Task 315        assigned_to: Carol16        priority: high
```

Execution

```
1python -c "import yaml; d = yaml.safe_load(open('projects.yaml')); print(d['projects'][0]['tasks'])"
```

Output

```
1[{'name': 'Task 1', 'assigned_to': 'Alice', 'priority': 'high'}, {'name': 'Task 2', 'assigned_to': 'Bob', 'priority': 'medium'}]
```

-   The dash for list items aligns with the first key of each item.
-   Nested lists use additional indentation and dashes.

#### Hierarchical configuration

Hierarchical structures can represent multi-level configurations with lists of objects containing nested data.

Code

```
1environments:2  - name: development3    services:4      - name: api5        port: 30006        env_vars:7          DEBUG: 'true'8          LOG_LEVEL: debug9      - name: db10        port: 543211        env_vars:12          POSTGRES_DB: dev_db13  - name: production14    services:15      - name: api16        port: 808017        env_vars:18          DEBUG: 'false'19          LOG_LEVEL: error
```

Execution

```
1python -c "import yaml; d = yaml.safe_load(open('envs.yaml')); print(len(d['environments'][0]['services']))"
```

Output

```
12
```

-   Maintain consistent indentation throughout complex nesting.
-   Document structure clearly to aid understanding.

## Practical Examples

Real-world YAML usage, best practices, and solutions.

### Configuration Files

Using YAML for application and service configuration.

#### Accessibility

Ensure configuration examples are properly formatted.

#### Best Practices

-   Use descriptive names for sections and values.
-   Group related configuration under common keys.
-   Keep configuration files small and focused on one purpose.

#### Common Errors

-   **Syntax errors preventing configuration loading:** Validate YAML syntax with yamllint or online validators.
-   **Incorrect data types (string vs number):** Quote values explicitly when type ambiguity exists.

#### Keywords

configurationyamlconfig-filedocker-composeapp-settings

[Learn more](https://docs.docker.com/compose/compose-file/)

#### Application configuration

Application configurations define settings for the entire application, including database and logging.

Code

```
1app:2  name: MyApplication3  version: 1.0.04  port: 80005
6database:7  host: localhost8  port: 54329  name: myapp_db10  credentials:11    username: app_user12    password: secure_pwd13
14logging:15  level: info16  output: stdout
```

Execution

```
1python -c "import yaml; conf = yaml.safe_load(open('app.yaml')); print(f\"App: {conf['app']['name']}, DB: {conf['database']['name']}\")"
```

Output

```
1App: MyApplication, DB: myapp_db
```

-   Group related settings under common keys.
-   Use meaningful section names for clarity.

#### Docker Compose service

Docker Compose YAML defines multi-container services with images, ports, volumes, and environment variables.

Code

```
1services:2  web:3    image: nginx:latest4    ports:5      - "80:80"6    volumes:7      - ./html:/usr/share/nginx/html8    environment:9      NGINX_ENV: production10  db:11    image: postgres:1312    environment:13      POSTGRES_DB: mydb14      POSTGRES_PASSWORD: secret15    ports:16      - "5432:5432"
```

Execution

Terminal window

```
docker-compose config
```

Output

Terminal window

```
services defined and validated
```

-   Each service is a list item with specific configuration.
-   Environment variables are key-value pairs in a dictionary.

### Best Practices

Following YAML best practices for readability and maintainability.

#### Accessibility

Ensure best practices are clearly explained.

#### Best Practices

-   Use consistent indentation (2 spaces per level, never tabs).
-   Name keys and values descriptively.
-   Add comments explaining non-obvious configurations.
-   Validate YAML syntax regularly during development.

#### Common Errors

-   **Inconsistent indentation mixing spaces and tabs:** Use a YAML linter (yamllint) to enforce consistency.
-   **Unclear key names or abbreviations:** Use descriptive names that clearly indicate purpose.

#### Keywords

best-practicesyamlindentationreadabilityconventions

[Learn more](https://yaml.org/spec/1.2/spec.html#style-examples)

#### Proper indentation and structure

Proper indentation, comments, and consistent structure improve readability and maintainability.

Code

```
1# Database configuration - consistent spacing and indentation2database:3  primary:4    host: db-primary.example.com5    port: 54326    credentials:7      username: admin8      password: secure_password9  replica:10    host: db-replica.example.com11    port: 543212    credentials:13      username: replica_user14      password: replica_password
```

Execution

```
1python -c "import yaml; print(yaml.safe_load(open('db_config.yaml')))"
```

Output

```
1proper YAML structure loaded successfully
```

-   Use 2 spaces for each indentation level consistently.
-   Include comments explaining configuration purpose.

#### Avoiding common mistakes

Clear naming, proper structure, and meaningful comments make YAML files more maintainable.

Code

```
1# Good: Clear naming and structure2services:3  - name: api_service4    port: 80005    timeout: 306  - name: worker_service7    port: 80018    timeout: 609
10# Bad: Unclear abbreviations and comments11# svc:12#   - nm: api  # Too abbreviated13#     p: 8000
```

Execution

```
1python -c "import yaml; d = yaml.safe_load(open('good.yaml')); print(f\"Services: {[s['name'] for s in d['services']]}\")"
```

Output

```
1Services: ['api_service', 'worker_service']
```

-   Use full, descriptive names instead of abbreviations.
-   Avoid overly clever or minimal formatting.

### Validation and Use

Parsing YAML, validating syntax, and loading in different languages.

#### Accessibility

Ensure validation steps are clear and accessible.

#### Best Practices

-   Always validate YAML syntax before deploying configurations.
-   Use \`safe\_load()\` in Python to prevent code injection.
-   Test configuration parsing with different input values.

#### Common Errors

-   **Syntax errors not caught until runtime:** Validate YAML early in the development process.
-   **Using \`load()\` instead of \`safe\_load()\` creating security issues:** Always use \`safe\_load()\` for untrusted YAML input.

#### Advanced Notes

-   **Schema Validation:** Use YAML schema validators (e.g., JSON Schema, YAML Schema) for thorough validation.
-   **Multiple Parsers:** Different languages have different YAML libraries; test cross-language compatibility.

#### Keywords

validationparsingyamlpythonjavascript

[Learn more](https://pyyaml.org/wiki/PyYAMLDocumentation)

#### Parsing YAML in Python

Python's \`yaml\` module (PyYAML) can parse YAML files into Python dictionaries.

Code

```
1application:2  name: PythonApp3  debug: true4  port: 50005  database:6    host: localhost7    port: 5432
```

Execution

```
1import yaml2with open('app.yaml', 'r') as f:3  config = yaml.safe_load(f)4print(config['application']['name'])5print(config['application']['database']['host'])
```

Output

```
1PythonApp2localhost
```

-   Always use \`safe\_load()\` to avoid executing arbitrary code.
-   Handle file exceptions for missing or invalid YAML files.

#### YAML validation

YAML validation tools check for syntax errors and formatting issues before using configuration.

Code

Terminal window

```
# Using yamllint for syntax validationyamllint config.yaml
# Or validating with Pythonpython -c "import yaml; yaml.safe_load(open('config.yaml'))"
```

Execution

Terminal window

```
yamllint config.yaml
```

Output

Terminal window

```
config.yaml is valid
```

-   Use yamllint for linting and style checking.
-   Python's \`safe\_load()\` provides basic syntax validation.

Was this useful?

## Tags

#YAML#Configuration#Data Serialization#Syntax#Indentation#Keys#Values#Anchors#Aliases

## Share

[Facebook](https://facebook.com/sharer/sharer.php?u=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fyaml "Share on Facebook")[Twitter](https://twitter.com/intent/tweet/?text=YAML&url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fyaml "Share on Twitter")[LinkedIn](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fyaml&title=YAML&summary=YAML%20\(YAML%20Ain't%20Markup%20Language\)%20is%20a%20human-friendly%20data%20serialization%20language%20commonly%20used%20for%20configuration%20files%2C%20data%20exchange%2C%20and%20infrastructure-as-code.%20It%20emphasizes%20readability%20and%20uses%20indentation%20to%20structure%20data.&source=https://mkabumattar.com "Share on LinkedIn")[WhatsApp](https://wa.me/?text=YAML%20https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fyaml "Share on WhatsApp")[Telegram](https://t.me/share/url?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fyaml&text=YAML "Share on Telegram")[Reddit](https://www.reddit.com/submit?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fyaml&title=YAML "Share on Reddit")[Hacker News](http://news.ycombinator.com/submitlink?u=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fyaml&t=YAML "Share on Hacker News")[Pinterest](https://pinterest.com/pin/create/button/?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fyaml&media=&description=YAML%20\(YAML%20Ain't%20Markup%20Language\)%20is%20a%20human-friendly%20data%20serialization%20language%20commonly%20used%20for%20configuration%20files%2C%20data%20exchange%2C%20and%20infrastructure-as-code.%20It%20emphasizes%20readability%20and%20uses%20indentation%20to%20structure%20data. "Share on Pinterest")[Email](<mailto:?subject=YAML&body=Check out this article: https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fyaml>)

## Comments

## You might also enjoy

More posts on similar topics

## [TOML](/cheatsheets/toml)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Data Format
-   TOML
-   Configuration
-   Data Serialization
-   Settings

TOML (Tom's Obvious, Minimal Language) is a human-friendly configuration file format. Designed to be minimal, readable, and unambiguous, it's used extensively in package manifests (like Cargo.toml and

#TOML#Configuration#Data Format+5 tags

[read more](/cheatsheets/toml)

## [JSON](/cheatsheets/json)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Data Format
-   JSON
-   Data Serialization
-   Web API
-   Configuration

JSON (JavaScript Object Notation) is a lightweight, text-based data exchange format. It's universally supported across programming languages and provides a simple, readable way to structure and transm

#JSON#Data Format#Data Serialization+5 tags

[read more](/cheatsheets/json)

## [RegEx](/cheatsheets/regex)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Tools
-   Regular Expressions
-   Text Processing
-   Pattern Matching
-   Development

Regular expressions (regex or regexp) are patterns used to match character combinations in strings. They handle pattern matching, validation, and text processing across nearly all programming language

#RegEx#Regular Expressions#Pattern Matching+5 tags

[read more](/cheatsheets/regex)

## [Markdown](/cheatsheets/markdown)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Markup Language
-   Markdown
-   Documentation
-   Formatting
-   Content Creation
-   Writing

Markdown is a lightweight markup language for writing formatted content with a simple, readable syntax. It was created for writing on the web, and is now used in documentation, blogs, and note-taking

#Markdown#Formatting#Text+6 tags

[read more](/cheatsheets/markdown)

## [GitHub Actions](/cheatsheets/github-actions)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   CI/CD
-   DevOps
-   GitHub
-   Automation
-   YAML

GitHub Actions runs your CI/CD directly from YAML files in .github/workflows/, and most of the job is knowing which key does what. A workflow reacts to events, splits into jobs that run on runners,

#GitHub Actions#Workflow#CI/CD+5 tags

[read more](/cheatsheets/github-actions)

## [Docker](/cheatsheets/docker)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   DevOps
-   Docker
-   Containers
-   Deployment

Docker is a containerization platform that packages applications with their dependencies into isolated, portable environments called containers. It enables developers to build, ship, and run applicati

#Docker#Containers#Images+3 tags

[read more](/cheatsheets/docker)

6 related posts
