Introduction

Ansible is a powerful tool used for automation and configuration management. While it is commonly associated with tasks like server provisioning and application deployment, its flexibility allows it to be used for a wide variety of tasks, even something as simple as searching for a specific band member in a list of bands. In this article, we'll create an Ansible playbook that searches for bands formed with a member named "Starr" and outputs the result.

Disclaimer

Full example: https://www.redhat.com/sysadmin/ansible-jinja-lists-dictionaries

The Playbook

Below is the Ansible playbook designed for this task. It includes a list of bands, each with its members, formation year, and the decade they were most active. The playbook filters through this list to find any band that has a member named "Starr."

``yaml

---

  • name: List bands formed with a member named Starr

hosts: localhost

gather_facts: no

vars:

bands:

- name: The Beatles

members:

- Lennon

- McCartney

- Harrison

- Starr

formed: 1960

decade: 60s

- name: The Eagles

members:

- Frey

- Henley

- Leadon

- Meisner

formed: 1971

decade: 70s

- name: Run DMC

members:

- Simmons

- McDaniels

- Mizell

formed: 1983

decade: 80s

- name: Red Hot Chili Peppers

members:

- Kiedis

- Smith

- Frusciante

- Balzary

formed: 1982

decade: 90s

- name: Destiny's Child

members:

- Knowles

- Rowland

- Williams

formed: 1990

decade: 00s

- name: Black Eyed Peas

members:

- Adams

- Lindo

- Gomez

formed: 1995

decade: 00s

tasks:

- name: Display bands with a member named Starr

ansible.builtin.debug:

msg: "{{ bands | selectattr('members', 'search', 'Starr') | map(attribute='name') | list }}"

`

Explanation of the Code

  • Playbook Structure:

- The playbook targets the localhost and does not gather facts, as this is a simple data-processing task.

  • Variables Section:

- The bands variable is defined as a list containing information about several bands, including their names, members, formation year, and the decade they were active.

  • Task:

- A single task is defined that uses the ansible.builtin.debug module to filter through the bands list and find any band with a member named "Starr."

- The filtering is done using Jinja2 templating with the selectattr filter, which searches for "Starr" within the members list of each band.

Running the Playbook

To run this playbook, save it as list_bands.yml and execute the following command in your terminal:

`bash

ansible-playbook list_bands.yml

``

Expected Output

When the playbook is executed, the