Ansible: Structure of a Playbook

From Glitchdata
Jump to navigation Jump to search

Let's break this down in sections so we can understand how these files are built and what each piece means.

The File Starts

The file starts with:


This is a requirement for YAML to interpret the file as a proper document. YAML allows multiple "documents" to exist in one file, each separated by ---, but Ansible only wants one per file, so this should only be present at the top of the file.

YAML is very sensitive to white-space, and uses that to group different pieces of information together. You should use only spaces and not tabs and you must use consistent spacing for your file to be read correctly. Items at the same level of indentation are considered sibling elements.

Items that begin with a - are considered list items. Items that have the format of key: value operate as hashes or dictionaries. That's pretty much all there is to basic YAML.

YAML documents basically define a hierarchical tree structure with the containing elements further to the left.

Select Applicable Servers

On the second line, we have this:

- hosts: droplets

This is a list item in YAML as we learned above, but since it is at the left-most level, it is also an Ansible "play". Plays are basically groups of tasks that are performed on a certain set of hosts to allow them to fulfill the function you want to assign to them. Each play must specify a host or group of hosts, as we do here.

The Set of Tasks

Next, we have a set of tasks:

- hosts: droplets
    - name: Installs nginx web server
      apt: pkg=nginx state=installed update_cache=true
        - start nginx

At the top level, we have "tasks:" at the same level as "hosts:". This contains a list (because it starts with a "-") which contains key-value pairs.

The first one, "name", is more of a description than a name. You can call this whatever you would like.

Ansible Execution

The next key is "apt". This is a reference to an Ansible module, just like when we use the ansible command and type something like:

ansible -m apt -a 'whatever' all

This module allows us to specify a package and the state that it should be in, which is "installed" in our case. The update-cache=true part tells our remote machine to update its package cache (apt-get update) prior to installing the software.

The "notify" item contains a list with one item, which is called "start nginx". This is not an internal Ansible command, it is a reference to a handler, which can perform certain functions when it is called from within a task. We will define the "start nginx" handler below.