Level 1
0 / 100 XP

Ansible Loops

In this lesson, you will learn how to effectively use Ansible loops in Ansible. Loops are useful for automating repetitive tasks. By the end of this lesson, you will be able to utilize loops in your Ansible playbooks.

We'll start by adding a list of users and passwords to our secret.yml file for secure storage, then we'll create a new playbook that will loop over the list and create the user accounts with their respective passwords.

Adding a List of Users To Our Ansible Vault File

You already have an Ansible Vault file at ~/secret.yml. This file will store user passwords securely. We will edit this file to add user information.

  1. Edit the Vault File :
    Use the following command to edit the vault file:
ansible-vault edit ~/secret.yml
  1. Add User Information :
    Inside the vault file, add user details in the following format:
users:
Text
- username: user1 password: password1 - username: user2 password: password2 - username: user3 password: password3 - username: user4 password: password4 - username: user5 password: password5

Note that we are using insecure passwords for each user, you are free to change this how you see fit. Save and close the file with the :wq key sequence.

Creating the Playbook

Let’s create a playbook called loops_test.yml. This playbook will loop through the user information stored in the Ansible Vault to create user accounts on your managed node.

  1. Create the Playbook :
    Open a new file in your text editor:

    nano loops_test.yml

  2. Add the Playbook Content :
    Insert the following content into your playbook:


    • name: Create multiple users hosts: managed-node-1 become: yes vars_files:
      • ~/secret.yml tasks:
      • name: Create user accounts…