Categories

Category cover

Automation
155 posts

Category cover

Learning paths
119 posts

Category cover

CISO
22 posts

Category cover

Security
20 posts

Category cover

Notes
19 posts

Category cover

Personal Security
18 posts

Category cover

Infrastructure
12 posts

Category cover

OT/ICS
5 posts

Category cover

Books
3 posts

Category cover

UNetLab
3 posts

Category cover

Write-up
3 posts

Category cover

OSInt
2 posts

Category cover

My life
1 posts

Ansible Playbooks and variables

Andrea Dainese
August 15, 2024
Post cover

A playbook is a YAML file that sequentially outlines the operations to be performed on devices or groups of devices. Each playbook is composed of one or more plays, which can include pre_tasks, tasks, and post_tasks.

When planning and writing playbooks, variables play a crucial role. These variables can be defined at different levels, such as configuration, playbook, inventory, environment, files, or facts. It’s helpful to have a method for printing the value of all defined variables.

Let’s start by opening the Cisco Legacy Core-Access topology lab and ensuring all devices are active and reachable.

Printing All Variables

As we know, a playbook is a YAML file containing a list of plays. Each play defines the operations to be performed and where they should be executed:

The example above defines a play with a general list of pre_tasks, tasks, and post_tasks. This play runs on all inventory objects (all) and collects facts before executing any tasks. Although gathering facts can slow down the play, it’s essential for our purpose.

The first line, known as the “shebang,” allows the playbook file to be executed directly without specifying the ansible-playbook interpreter manually. As the name suggests, pre_tasks and post_tasks group tasks that need to be executed before any other tasks or just before finishing the play, respectively. In this example, we’ll focus only on the tasks.

The playbook’s goal is defined by the hosts key, which can select all hosts in the inventory (all), specific groups, or individual hosts. Here are some examples:

  • all: selects all hosts in the inventory;
  • r1.example.com: selects only R1;
  • routers,switches: selects hosts in the routers or switches groups;
  • routers,!switches: selects hosts in the routers group but not in the switches group.

Now, let’s write a playbook to print all environment variables. The variables we want to print are grouped into:

  • Module variables (vars)
  • Environment variables (environment)
  • Group names variables (group_names)
  • Groups variables (groups)
  • Host variables (hostvars)

We’ll define five tasks to print these variables:

Each task uses the ansible.builtin.debug module to define the msg variable, which is set to the contents of vars, environment, group_names, groups, and hostvars.

Continue reading the post on Patreon .