At times you may want to execute a single tasks with multiple variable values one after the other. For example create 3 user accounts using one task. One way is to write three tasks in the same playbook, where each user is created by each task. The other way is to loop the values associated with a variable.
Below is a playbook that created three users using just one task in a playbook
[root@centos9vm ~]# cat adduserLoop.yml
==== ==
– – –
– name: Playbook to create 3 users
hosts: 192.168.48.129
vars:
myUser:
– shiju01
– shiju02
– shiju03
tasks:
– name: Create a user at a time
ansible.builtin.user:
name: “{{ item }}”
state: present
loop: “{{ myUser }}”
===== =====
[root@centos9vm ~]# ansible-navigator run -m stdout adduserLoop.yml
====== ===
PLAY [Playbook to create 3 users] **********************************************
TASK [Gathering Facts] *********************************************************
ok: [192.168.48.129]
TASK [Create a user at a time] *************************************************
changed: [192.168.48.129] => (item=shiju01)
changed: [192.168.48.129] => (item=shiju02)
changed: [192.168.48.129] => (item=shiju03)
PLAY RECAP *********************************************************************
192.168.48.129 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
==== =====
Let us check if the users got created
[root@centos9vm ~]# ssh 192.168.48.129 ‘tail -3 /etc/passwd’
==== ====
shiju01:x:1012:1012::/home/shiju01:/bin/bash
shiju02:x:1013:1013::/home/shiju02:/bin/bash
shiju03:x:1014:1014::/home/shiju03:/bin/bash