# YAML Data Format

> Chapter 103 of the Courseiva CCNA curriculum — https://courseiva.com/learn/ccna/yaml-networking

**Official objective:** 6.4 — CCNA 200-301 v2.0 Objective 5.3

## Introduction

YAML (YAML Ain't Markup Language) is a human-readable data serialization standard that is widely used in network automation for defining configuration, inventory, and variables. For the CCNA 200-301 exam (Objective 6.4: Describe characteristics of REST-based APIs, YAML, JSON, and Ansible), understanding YAML is essential because it is the primary format for Ansible playbooks and many network automation tools. Mastering YAML syntax will help you write, read, and troubleshoot automation scripts—a skill that separates modern network engineers from those stuck in the CLI-only era.

## The Recipe Card Analogy

A recipe card for a signature dish organises its data into a title, ingredients, and a procedure. The recipe card has a clear structure: a title, a list of ingredients with quantities, and a step-by-step procedure. YAML is like that recipe card—it organizes data in a way that is easy for both humans and machines to read. In a recipe, you might write:

  - Ingredient: 2 cups flour
  - Ingredient: 1 cup sugar

This is a list. YAML uses dashes to represent lists. Now consider the ingredient details: flour has a quantity (2) and a unit (cups). In YAML, that would be a mapping (key-value pair):

  flour:
    quantity: 2
    unit: cups

Indentation matters in YAML just as it does in a recipe's nested instructions. If you mis-indent, the recipe becomes ambiguous—does "2 cups" belong to flour or sugar? YAML uses indentation (spaces, not tabs) to show hierarchy, similar to how a recipe groups ingredients under a heading. Comments in YAML (starting with #) are like chef's notes—ignored by the machine but helpful for humans. When a network engineer writes an Ansible playbook, they are essentially writing a recipe for the network: "for this device (host), apply these configurations (tasks) with these parameters (variables)." The playbook's structure mirrors the recipe card: top-level keys (hosts, tasks), nested lists (tasks under a play), and mappings (variables). YAML's simplicity avoids the clutter of brackets and quotes found in JSON or XML, making it the preferred format for automation workflows in platforms like Ansible, SaltStack, and many CI/CD pipelines.

## Core explanation

### What is YAML?

YAML (YAML Ain't Markup Language) is a data serialization language designed for human readability. It is commonly used for configuration files, data exchange, and defining automation workflows. YAML structures data using indentation (spaces) to denote hierarchy, making it visually clean compared to JSON or XML. The CCNA 200-301 exam expects you to understand YAML's basic syntax, data types, and how it is used in network automation contexts like Ansible playbooks.

### Why YAML Exists

Before YAML, configuration files often used INI, XML, or JSON. XML is verbose; JSON, while lighter, still uses braces and quotes that can be hard to read for large configurations. YAML was created to be a superset of JSON (meaning valid JSON is valid YAML) but with a more human-friendly syntax. For network automation, YAML is the default format for Ansible—a tool Cisco heavily promotes for managing network devices at scale. The exam objective 6.4 explicitly lists YAML alongside JSON and Ansible, so you must be able to read and write basic YAML.

### YAML Syntax Basics

YAML files use three primary constructs:
- **Scalars**: single values (strings, numbers, booleans, null).
- **Sequences (lists)**: ordered items prefixed with dashes (`-`).
- **Mappings (dictionaries)**: key-value pairs using a colon and space (`key: value`).

Indentation is critical: YAML uses spaces (not tabs) to indicate nesting. The number of spaces must be consistent within the same file (commonly 2 spaces per level). Comments start with `#` and are ignored by the parser.

#### Example: A Simple Playbook Fragment

```yaml
---
- name: Configure interfaces
  hosts: routers
  vars:
    dns_server: 8.8.8.8
    ntp_server: 192.168.1.10
  tasks:
    - name: Set DNS server
      ios_config:
        lines:
          - ip name-server {{ dns_server }}
    - name: Set NTP server
      ios_config:
        lines:
          - ntp server {{ ntp_server }}
```

In this example:
- `---` indicates the start of a YAML document (optional).
- `hosts`, `vars`, `tasks` are keys in a mapping.
- `- name: Configure interfaces` starts a sequence (the list of plays).
- `vars` is a mapping containing `dns_server` and `ntp_server`.
- `tasks` is a sequence of dictionaries, each with a `name` and module (e.g., `ios_config`).
- `lines` is a list of commands to apply.
- `{{ dns_server }}` is a Jinja2 template variable (not pure YAML, but commonly used with Ansible).

### Data Types

YAML supports several data types:
- **Strings**: can be quoted (single or double) or unquoted if no special characters. For example: `name: "Router 1"` or simply `name: Router 1`.
- **Numbers**: integer or floating-point: `port: 22`, `timeout: 30.5`.
- **Booleans**: true/false, yes/no, on/off: `enabled: true`.
- **Null**: `~` or nothing: `description:` (empty value).
- **Lists**: `- item1`
- **Dictionaries**: `key: value`

### Multi-line Strings

YAML provides two ways to handle multi-line strings:
- **Literal block scalar** (`|`): preserves newlines.
- **Folded block scalar** (`>`): folds newlines to spaces.

Example:
```yaml
banner: |
  This is a banner
  that spans multiple lines.
```
This results in the string "This is a banner\nthat spans multiple lines.\n".

### Anchors and Aliases

YAML allows reusing data with anchors (`&`) and aliases (`*`). This is useful for DRY (Don't Repeat Yourself) configurations.

```yaml
defaults: &defaults
  timeout: 30
  retries: 3

server1:
  <<: *defaults
  host: 10.1.1.1
```

Here, `server1` merges the `defaults` mapping and adds `host`. The `<<` key is a merge key (not standard YAML but supported by many parsers).

### How YAML Interacts with Automation Tools

In network automation, YAML files are typically used as:
- **Inventory files**: list of hosts and groups.
- **Variable files**: define device-specific or group-specific variables.
- **Playbooks**: define the automation workflow (tasks to execute).

Ansible, for example, reads YAML playbooks and executes tasks on network devices via modules like `ios_config`, `ios_command`, etc. The YAML structure defines the order and parameters of these tasks. Understanding YAML is therefore prerequisite to using Ansible effectively.

### Common Pitfalls

- **Tabs vs. spaces**: YAML forbids tabs. Always use spaces.
- **Inconsistent indentation**: All items at the same level must have the same indentation.
- **Missing space after colon**: `key:value` is invalid; must be `key: value`.
- **Unquoted strings with special characters**: If a string contains `:`, `#`, `{`, `}`, `[`, `]`, `,`, `&`, `*`, `?`, `|`, `-`, `<`, `>`, `=`, `!`, `%`, `@`, `` ` ``, it should be quoted.

### Verification in the Exam

You will not be asked to write YAML from scratch on the exam, but you will need to:
- Interpret YAML content (e.g., given a playbook snippet, identify the hosts, tasks, or variables).
- Identify syntactically correct YAML vs. incorrect.
- Understand how YAML maps to JSON (since many REST APIs return JSON, and YAML can be converted).

Example exam-like question: "Which of the following is valid YAML?" with options containing tab indentation or missing spaces.

Correct answer would be the one using consistent spaces and proper syntax.

## Real-world context

### Scenario 1: Automating Router Configuration with Ansible

A network engineer at a mid-size enterprise manages 50 Cisco routers across multiple sites. Manually configuring each router for a new DNS server is tedious and error-prone. They decide to use Ansible with a YAML playbook. The inventory file (hosts.yml) is written in YAML:

```yaml
all:
  hosts:
    router1:
      ansible_host: 10.1.1.1
    router2:
      ansible_host: 10.2.2.2
  vars:
    dns_server: 8.8.8.8
```

The playbook (config.yml) uses the `ios_config` module to apply the DNS configuration:

```yaml
- name: Configure DNS
  hosts: all
  gather_facts: no
  tasks:
    - name: Set DNS server
      ios_config:
        lines:
          - ip name-server {{ dns_server }}
```

Running `ansible-playbook -i hosts.yml config.yml` pushes the command to all routers. The engineer saves hours and eliminates typos. YAML's readability makes it easy to audit the playbook before execution. If a syntax error occurs (e.g., missing space after colon), Ansible will fail with a parse error, prompting the engineer to fix the YAML.

### Scenario 2: Defining Device Variables for a Large Network

A service provider uses Ansible to manage hundreds of devices. They store device-specific parameters in YAML variable files. For example, `group_vars/routers.yml` contains:

```yaml
snmp_community: public
ntp_servers:
  - 192.168.1.10
  - 192.168.1.11
```

And `host_vars/router3.yml` overrides the SNMP community:

```yaml
snmp_community: private
```

When Ansible runs, it merges variables in a specific order (group vars, then host vars). The YAML structure allows clear separation of common and specific configurations. A mis-indentation in these files could cause variables to be ignored or misapplied, leading to configuration drift. For example, if `ntp_servers` is accidentally indented under `snmp_community`, the NTP servers would not be applied. Engineers use YAML linters (e.g., yamllint) to validate syntax before deployment.

### Scenario 3: CI/CD Pipeline for Network Changes

A DevOps team integrates network configuration into a CI/CD pipeline using GitLab. Developers submit changes to a YAML-based configuration template. The pipeline runs Ansible to push changes to a staging network, then after approval, to production. YAML's simplicity enables non-network engineers to review changes via merge requests. If a developer accidentally uses a tab instead of spaces, the pipeline fails early, preventing misconfiguration. The team also uses YAML anchors to define common ACL rules that are reused across multiple devices, reducing duplication.

## Exam focus

### What the 200-301 Exam Tests on YAML

Objective 6.4: "Describe characteristics of REST-based APIs (CRUD, HTTP verbs, and data encoding), YAML, JSON, and Ansible." For YAML specifically, the exam expects you to:
- Recognize valid YAML syntax (proper indentation, use of dashes for lists, colons for mappings).
- Understand that YAML is human-readable and uses whitespace for structure.
- Know that YAML is a superset of JSON.
- Identify common data types: scalars, lists, mappings.
- Interpret simple YAML snippets (e.g., from an Ansible playbook).

### Common Wrong Answers and Why Candidates Choose Them

1. **"YAML uses tabs for indentation"** – Many candidates come from programming backgrounds where tabs are acceptable. In YAML, tabs are strictly forbidden. The exam may show a snippet with a tab and ask if it's valid. Always look for spaces.
2. **"YAML requires quotes around all strings"** – Unlike JSON, YAML strings often do not require quotes. Candidates familiar with JSON assume quotes are mandatory. In YAML, quotes are only needed for strings with special characters.
3. **"YAML is a markup language like XML"** – The name originally stood for "Yet Another Markup Language", but the official name is now "YAML Ain't Markup Language" to emphasize it is a data serialization format, not a markup language. The exam may test this trivia.
4. **"YAML cannot represent lists"** – This is false; lists are represented with dashes. Candidates might confuse YAML with other formats.

### Specific Values and Command Outputs

You will not see CLI commands for YAML, but you might see a sample YAML file and be asked to identify its structure. For example:
```yaml
students:
  - name: Alice
    age: 22
  - name: Bob
    age: 23
```
Questions: "How many students are in the list?" Answer: 2. "What is the age of the second student?" Answer: 23.

### Calculation Traps

There are no calculations in YAML, but watch for trick questions about indentation levels. For example, a YAML snippet might have inconsistent indentation (e.g., one item indented 2 spaces, another 3). The exam expects you to identify that as invalid.

### Decision Rule for Scenario Questions

When given a scenario asking which format is best for human-readable configuration files, choose YAML over JSON or XML because YAML is designed for readability. If the scenario involves data exchange between systems (API), JSON might be more appropriate. But for configuration management (Ansible), YAML is the standard.

## Step by step

1. **Understand YAML's role in automation** — YAML is a data format used to define configurations and automation workflows. In the context of CCNA, you will most often encounter YAML in Ansible playbooks and inventory files. Recognize that YAML is human-readable and uses indentation to structure data. The exam objective 6.4 expects you to describe characteristics of YAML, so start by knowing that YAML stands for 'YAML Ain't Markup Language', it is a superset of JSON, and it relies on whitespace (spaces) for structure.
2. **Learn basic YAML syntax: scalars, lists, mappings** — Scalars are simple values like strings, numbers, booleans. Lists are ordered sequences prefixed with `-`. Mappings are key-value pairs with `key: value`. Practice writing a simple YAML snippet representing a list of network devices: `- device: router1` `- device: switch1`. Then create a mapping for a device with properties: `device: router1`, `ip: 10.1.1.1`. Ensure you use a space after the colon. Remember: no tabs, only spaces.
3. **Master indentation rules** — Indentation in YAML indicates nesting. All items at the same level must have the same number of spaces. For example, two tasks under a play must be indented the same amount. A common mistake is mixing tabs and spaces—always use spaces. In the exam, you might be shown a YAML snippet and asked if it is valid. Look for inconsistent indentation or tab characters. The correct indentation is typically 2 spaces per level.
4. **Handle multi-line strings and comments** — Multi-line strings use `|` (literal) or `>` (folded). Comments start with `#` and extend to the end of the line. In Ansible playbooks, you often see multi-line strings for banner messages or command sets. For example: `banner: |` followed by indented lines. Comments are useful for documenting playbooks. The exam may test whether you can identify a comment or a multi-line string.
5. **Use anchors and aliases for reuse** — Anchors (`&name`) and aliases (`*name`) allow you to repeat data without duplication. This is advanced but may appear in complex playbooks. For example, define a default set of variables with an anchor, then merge it into multiple hosts using `<<: *defaults`. Understanding this concept helps you read and debug YAML files. On the exam, you might be asked what `*defaults` refers to.
6. **Convert between YAML and JSON** — YAML is a superset of JSON, so any valid JSON is valid YAML. However, YAML's syntax is more concise. For the exam, you should be able to recognize that a JSON object `{"key": "value"}` is equivalent to YAML `key: value`. Many tools convert between the two. This skill is useful when working with REST APIs that return JSON but you need to write YAML for Ansible. Practice converting a simple JSON to YAML and vice versa.

## Comparisons

### YAML vs JSON

**YAML:**
- Uses indentation for structure.
- More human-readable with less punctuation.
- Supports comments (with #).
- Superset of JSON.
- Commonly used for configuration files (Ansible, Kubernetes).

**JSON:**
- Uses braces and brackets for structure.
- More verbose but machine-friendly.
- No comments in standard JSON.
- Strict subset of YAML.
- Commonly used for API data exchange (REST).

## Common misconceptions

- **Misconception:** YAML uses tabs for indentation. **Reality:** YAML strictly forbids tabs; only spaces are allowed. The parser will throw an error if a tab is encountered. (Many people are used to tabs in code editors, but YAML's specification explicitly prohibits them to avoid ambiguity across different editors.)
- **Misconception:** YAML requires quotation marks around all string values. **Reality:** Strings in YAML generally do not require quotes unless they contain special characters (e.g., `:`, `#`, `{`, `}`, `[`, `]`, `,`, `&`, `*`, `?`, `|`, `-`, `<`, `>`, `=`, `!`, `%`, `@`, `` ` ``). (This misconception stems from JSON, where all strings must be double-quoted. YAML's design prioritizes readability, so quotes are optional for most strings.)
- **Misconception:** YAML is a markup language like HTML or XML. **Reality:** YAML is a data serialization language, not a markup language. Its name is a recursive acronym for 'YAML Ain't Markup Language'. (The original name 'Yet Another Markup Language' caused confusion, so the acronym was redefined to emphasize it is not a markup language.)
- **Misconception:** YAML does not support nested structures. **Reality:** YAML supports deeply nested structures using indentation. For example, a list of dictionaries can contain further lists and mappings. (Beginners may think YAML is flat because they only see simple key-value pairs, but nesting is fundamental to YAML's design.)

## Key takeaways

- YAML uses indentation (spaces, not tabs) to denote structure.
- Lists are represented with dashes (`-`), mappings with colons (`key: value`).
- YAML is a superset of JSON: any valid JSON is valid YAML.
- YAML supports scalars, sequences, and mappings as core data types.
- Comments in YAML start with `#`.
- Anchors (`&`) and aliases (`*`) allow data reuse.
- YAML is the default format for Ansible playbooks, inventory, and variables.

## FAQ

**What is the difference between YAML and JSON?**

YAML and JSON are both data serialization formats, but YAML is designed to be more human-readable. YAML uses indentation for structure, supports comments, and has a cleaner syntax (no braces or quotes required for most strings). JSON is more compact and machine-friendly, and it is the standard for REST APIs. YAML is a superset of JSON, meaning any valid JSON is valid YAML. For CCNA, you need to know that YAML is commonly used in Ansible playbooks, while JSON is used in API responses.

**Why can't I use tabs in YAML?**

The YAML specification explicitly forbids tabs because tab width varies across editors and systems, leading to ambiguous indentation. Consistent indentation is critical for YAML to correctly parse nested structures. Always use spaces (typically 2 per indentation level). Many YAML parsers will throw an error if a tab is detected. Exam tip: if you see a YAML snippet with a tab, it is invalid.

**How do I comment in YAML?**

Comments in YAML start with a `#` character and extend to the end of the line. They can appear at the beginning of a line or after a value. For example: `# This is a comment` or `key: value # inline comment`. Comments are ignored by the parser. This is useful for documenting Ansible playbooks. Unlike JSON, YAML supports comments natively.

**What are anchors and aliases in YAML?**

Anchors and aliases allow you to reuse data without duplication. An anchor is defined with `&name` and an alias with `*name`. For example: `defaults: &defaults` defines an anchor; later `<<: *defaults` merges the anchored data into the current mapping. This is useful for DRY (Don't Repeat Yourself) configurations in Ansible. The `<<` is a merge key (not standard YAML but supported by many parsers). Exam tip: you may be asked what `*name` refers to.

**Does YAML support multi-line strings?**

Yes, YAML supports multi-line strings using block scalars. The literal block scalar (`|`) preserves newlines, while the folded block scalar (`>`) replaces newlines with spaces. For example: `banner: |` followed by indented lines. This is commonly used for configuration banners or long descriptions. Know the difference between `|` and `>` for the exam.

**How is YAML used in Ansible?**

Ansible uses YAML for playbooks, inventory files, and variable files. Playbooks are YAML files that define automation workflows: hosts, variables, tasks, and handlers. Inventory files list managed hosts and groups. Variable files define device-specific or group-specific parameters. Understanding YAML syntax is essential for writing and debugging Ansible automation. The CCNA exam objective 6.4 groups YAML with Ansible, so expect to interpret simple playbook snippets.

**What are common YAML errors to watch for?**

Common errors include: using tabs instead of spaces, inconsistent indentation, missing space after colon (`key:value`), unquoted strings with special characters (e.g., colons in values), and improper list formatting (dashes not aligned). Use a YAML linter (like yamllint) to catch these errors. On the exam, always check for proper spacing and indentation.

---

Interactive version with quiz and diagrams: https://courseiva.com/learn/ccna/yaml-networking
