Skip to main content

YAML basics for Ansible

Ansible playbooks are written in YAML. YAML, or "YAML Ain't Markup Language," is a human-friendly data serialization standard. It's often used for configuration files, but its simplicity makes it a broad-use language. Let's talk about the basics of YAML that you'll need to understand to write Ansible playbooks effectively.

YAML Basics

Indentation

YAML uses indentation to determine the structure of data. Spaces are used for indentation, not tabs. The number of spaces for indentation is not enforced, but two spaces are commonly used.

person:
name: John Doe
age: 45

In the example above, name and age are indented two spaces under person, indicating they belong to person.

Key-Value Pairs

Data in YAML is represented as key-value pairs. The key and value are separated by a colon.

name: John Doe

In the example above, name is the key, and John Doe is the value.

Lists

Lists are denoted by a hyphen, or dash, -, before each item in the list.

fruits:
- Apple
- Banana
- Cherry

In the example above, fruits is a list that includes Apple, Banana, and Cherry.

Dictionaries

Dictionaries, or maps, are collections of key-value pairs.

person:
name: John Doe
age: 45

In the example above, person is a dictionary that includes the keys name and age with their respective values.

YAML in Ansible

In Ansible, playbooks are written in YAML. Each playbook is composed of one or more 'plays' in an ordered list. A play is a mapping of a group of hosts to some well-defined roles, represented by tasks.

Here's a simple Ansible playbook example:

---
- hosts: webservers
tasks:
- name: Ensure Apache is installed
yum:
name: httpd
state: present
- name: Ensure Apache is running
service:
name: httpd
state: started

In the playbook example, we have:

  • A list of plays, denoted by the - before hosts.
  • A dictionary for each play, including hosts and tasks.
  • A list of tasks, each of which is a dictionary that includes name and an Ansible module (in this case, yum and service).

Remember, YAML is sensitive to spaces and indentation. The structure of a YAML file can determine whether your Ansible playbook runs successfully. Practice writing YAML files to become more comfortable creating Ansible playbooks.


This should be a good start to understanding YAML for use in Ansible. Remember, practice is key when learning a new language. Keep experimenting with different YAML structures and Ansible playbooks, and you'll become proficient over time.