ANSIBLE TUTORIALS #4: LOOPS
Learn how to use Ansible loops to create multiple users in different groups in one click…
Welcome to the fourth tutorial in this Ansible series. Here, we would simply learn how to create and add multiple users to different groups on a remote host using Ansible loop.
Task
Create the following 4 users on a remote host:
- james,
- amaka,
- joy
- cloudtopg
using loop in Ansible. Add the users james and cloudtopg to the sudo group, amaka to the root group, and joy to the admin group.
First, we would create a new working directory and all necessary files.
vagrant@ubuntu-control:~$ sudo mkdir ansible_tasks4; cd ansible_tasks4
vagrant@ubuntu-control:~/ansible_tasks4$ touch hosts ansible.cfg playbook.yml
These three files created with the touch command are all empty until we edit them. Let’s start with the host file.
The Host File
We would use only one remote server to demonstrate this task. There will be no need for host variable files. So, our host file goes thus:
[workstation]
ubuntu-node-2 ansible_host=192.168.53.21
The Ansible Configuration File
[defaults]
inventory=./hosts
host_key_checking=false
remote_user=ansible3
private_key_file=/home/vagrant/.ssh/id_ed25519
[privilege_escalation]
become=true
become_method=sudo
become_user=root
become_ask_pass=false
We created the remote user, ansible3 in our previous tutorial, and assigned a hashed password to it. This password will be used here when we run our playbook.
The Playbook
---
- name: ansible loop
hosts: all
tasks:
- name: update cache
package:
update_cache: yes
state: latest
- name: Add several users to several groups
ansible.builtin.user:
name: "{{ item.name }}"
state: present
groups: "{{ item.groups }}"
loop:
- { name: 'james', groups: 'sudo' }
- { name: 'amaka', groups: 'root' }
- { name: 'joy', groups: 'admin' }
- { name: 'cloudtopg', groups: 'sudo' }
Good!
Copy your public SSH key, and run your playbook with the -kK flags;
vagrant@ubuntu-control:~/ansible_tasks4$ ansible-playbook playbook.yml -kK
At the prompt, paste your public SSH key and press Enter; also enter the password we assigned to the ansible3 user.
Great!
Now go to your host and list out the groups present to confirm the successful execution of our task. Run the command below;
vagrant@ubuntu-node-1:~$ tail /etc/group
You would find the users we created
Or, run
vagrant@ubuntu-node-1:~$ cat /etc/group | grep sudo; cat /
etc/group | grep root; cat /etc/group | grep admin
and find the groups we have added our users to by using the grep command.
Conclusion
We have now come to the end of “ANSIBLE TUTORIALS #4: LOOP.” You can access the files created in this tutorial on my GitHub repository.
https://github.com/ozirichigozie/ansible_tasks4.git
If you encountered any challenge not addressed within this tutorial or have any other Ansible concept you want us to learn about, I look forward to hearing from you — please leave a message on WhatsApp.