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.
- Edit the Vault File :
Use the following command to edit the vault file:
ansible-vault edit ~/secret.yml
- Add User Information :
Inside the vault file, add user details in the following format:
users:
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.
-
Create the Playbook :
Open a new file in your text editor:nano loops_test.yml
-
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…
- name: Create multiple users
hosts: managed-node-1
become: yes
vars_files:
No comments yet. Add the first comment to start the discussion.