Book Image

Mastering Ansible, 4th Edition - Fourth Edition

By : James Freeman, Jesse Keating
Book Image

Mastering Ansible, 4th Edition - Fourth Edition

By: James Freeman, Jesse Keating

Overview of this book

Ansible is a modern, YAML-based automation tool (built on top of Python, one of the world’s most popular programming languages) with a massive and ever-growing user base. Its popularity and Python underpinnings make it essential learning for all in the DevOps space. This fourth edition of Mastering Ansible provides complete coverage of Ansible automation, from the design and architecture of the tool and basic automation with playbooks to writing and debugging your own Python-based extensions. You'll learn how to build automation workflows with Ansible’s extensive built-in library of collections, modules, and plugins. You'll then look at extending the modules and plugins with Python-based code and even build your own collections — ultimately learning how to give back to the Ansible community. By the end of this Ansible book, you'll be confident in all aspects of Ansible automation, from the fundamentals of playbook design to getting under the hood and extending and adapting Ansible to solve new automation challenges.
Table of Contents (18 chapters)
1
Section 1: Ansible Overview and Fundamentals
7
Section 2: Writing and Troubleshooting Ansible Playbooks
13
Section 3: Orchestration with Ansible

Iterative tasks with loops

Loops deserve a special mention in this chapter. So far, we have focused on controlling the flow of a playbook in a top-to-bottom fashion—we have changed the various conditions that might be evaluated as the playbook runs, and we have also focused on creating concise, efficient code. What happens, however, if you have a single task, but need to run it against a list of data; for example, creating several user accounts, directories, or indeed something more complex?

Looping changed in Ansible 2.5—prior to this, loops were generally created with keywords such as with_items and you may still see this in legacy code. Although some backward compatibility remains, it is advisable to move to the newer loop keyword instead.

Let's take a simple example—we need to create two directories. Create loop.yaml as follows:

---
- name: looping demo
  hosts: localhost
  gather_facts: false...