YAML and Ansible

A gentle introduction to YAML for SDN.

When learning YAML and Ansible, I would recommend following along in both the YAML website page here and Ansible’s playbook documentation located at this URI.

Almost every YAML file you write will start with a list. Items in the list consist of key : value pairs that are commonly known as a ‘hash‘ or as known in Python, a ‘dictionary‘. Therefore knowing how to write a list and dictionary using YAML will get you far. YAML also has a convention (optional) that starts a file with three dashes ( —) and ends the file with (optional) three dots ( …) indicating the beginning and end of a document.

Below is an example of a ‘list’ file.

---
# This is a simple list.
# Comments use a # before text and will not be outputted.
# All members of a list have the same indentation level, and
# include a 'dash' and a 'space'.
animals:
    - dog
    - rabbit
    - lion
    - wolf
...

A dictionary is written in a simple format as a KEY:VALUE pair. The colon (:) MUST be followed up by a SPACE.

---
# This is an employee record written as a - dictionary.
# Using key/value pairs with a colon and a space.
anderson:
    name: Conroy Tim
    title: programmer
    language: python
...
    

Another example suing a data structure that uses a list of dictionaries. You can also have lists of dictionaries: dictionaries whose values are lists or a mixture of both.

# An example showing list's of dictionaries. 
# Notice the (-) and space used below. What does this tell you? 
-  engineer:
    name: Tim Conroy
    job: Software Networking Developer
    skills:
      - python
      - ansible
      - yaml
-  support:
    name: Kevin Mark
    job: Developer
    skills:
      - networking
      - html
      - powershell

You can also use an abbreviated format that is very similar to Python’s syntax for dictionaries.

---
# a dictionary uses curly braces and key: value pairs.
vehicles: {truck: Ford, sport-car: Mini, van: volkswagen}
# a list uses square brackets.
weekdays: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday ]