Basic YAML Syntax
Introduction
YAML, which stands for "YAML Ain't Markup Language," is a human-readable data serialization standard that is commonly used for configuration files and data exchange between languages with different data structures. In this tutorial, we'll cover the basics of YAML syntax, providing you with the foundation to start working with YAML in the context of tools like Ansible.
Basic Structure
YAML files use indentation to indicate structure. Indentation is done using spaces, and the level of indentation indicates the level of nesting. Here is an example of a basic YAML structure:
key: value another_key: sub_key: sub_value
In this example, key
has a value of value
, and another_key
contains a nested key sub_key
with a value of sub_value
.
Lists
YAML supports lists, which are indicated by a dash followed by a space. Here is an example of a list in YAML:
items: - item1 - item2 - item3
In this example, items
is a list containing three items: item1
, item2
, and item3
.
Dictionaries
YAML also supports dictionaries (or maps), which are collections of key-value pairs. Here's an example:
person: name: John Doe age: 30 address: street: 123 Main St city: Anytown
In this example, person
is a dictionary with keys name
, age
, and address
. The address
key is itself a dictionary containing street
and city
.
Comments
Comments in YAML are denoted by the #
character. Everything on a line after a #
is ignored by the parser. Here's an example:
# This is a comment key: value # This is an inline comment
Multi-line Strings
YAML supports multi-line strings using the pipe |
or greater-than >
characters. The pipe character preserves line breaks, while the greater-than character folds line breaks into spaces. Here are examples of both:
# Using pipe description: | This is a multi-line string that preserves line breaks. # Using greater-than summary: > This is a multi-line string that folds line breaks into spaces.
Anchors and Aliases
YAML allows you to define reusable content with anchors and aliases. An anchor is defined using the &
character, and an alias is used with the *
character. Here is an example:
defaults: &default_values name: Default Name age: Default Age person1: <<: *default_values name: John Doe person2: <<: *default_values age: 25
In this example, &default_values
defines an anchor with default values. The alias *default_values
is used to merge these default values into person1
and person2
, with individual overrides for specific keys.