An Ansible playbook is the fundamental element in Ansible that declares what actions we would like to perform on our managed hosts (specified in the inventory). An Ansible playbook is a YAML-formatted file that defines a list of tasks that will be executed on our managed devices. In this recipe, we will outline how to write an Ansible playbook and how to define the hosts that will be targeted by this playbook.
Building Ansible's playbook
Getting ready
In order to follow along with this recipe, an Ansible inventory file must already be defined, along with all the group- and host-specific variable files created in accordance with previous recipes.
How to do it...
- Create a new file called playbook.yml inside the ch1_ansible folder and incorporate the following lines in this file:
$ cat playbook.yml
---
- name: Initial Playbook
hosts: all
gather_facts: no
tasks:
- name: Display Hostname
debug:
msg: "Router name is {{ hostname }}"
- name: Display OS
debug:
msg: "{{ hostname }} is running {{ os }}"
- Run the playbook as shown here:
$ ansible-playbook -i hosts playbook.yml
How it works...
The Ansible playbook is structured as a list of plays and each play targets a specific group of hosts (defined in the inventory file). Each play can have one or more tasks to execute against the hosts in this play. Each task runs a specific Ansible module that has a number of arguments. The general structure of the playbook is outlined in the following screenshot:
In the preceding playbook, we reference the variables that we defined in the previous recipe inside the {{ }} brackets. Ansible reads these variables from either group_vars or host_vars, and the module that we used in this playbook is the debug module, which displays as a custom message specified in the msg parameter to the Terminal output. The playbook run is shown here:
We use the -i option in the ansible-playbook command in order to point to the Ansible inventory file, which we will use as our source to construct our inventory.