Using Ansible to Batch Create and Delete Users on Remote Hosts
This article demonstrates how to employ Ansible, a Python‑based SSH automation framework, to create a user with a home directory on multiple remote servers, verify the creation, and then remove the user and its home directory in a batch operation.
Ansible is built on Paramiko and operates without installing client agents on remote hosts, using SSH to execute modules that provide true batch deployment capabilities.
Batch creating a user
ansible web -m user -a 'name=test01 shell=/bin/bash home=/opt/test01 state=present'
Output (truncated):
{ "ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": true, "create_home": true, "group": 1002, "home": "/opt/test01", "name": "test01", "shell": "/bin/bash", "state": "present", "system": false, "uid": 1002 }
The same command runs on each host in the web inventory, confirming the user was added.
Verifying the user
ansible web -m shell -a 'tail -1 /etc/passwd'
Result shows the new entry:
test01:x:1002:1002::/opt/test01:/bin/bash
ansible web -m shell -a 'ls /opt/'
Lists the directory contents, confirming the home folder exists.
Deleting the user and its home directory
ansible web -m user -a 'name=test01 remove=yes state=absent'
After deletion, re‑run the tail -1 /etc/passwd command to verify the entry is gone.
Images in the original article illustrate the command output and the removal verification.
Practical DevOps Architecture
Hands‑on DevOps operations using Docker, K8s, Jenkins, and Ansible—empowering ops professionals to grow together through sharing, discussion, knowledge consolidation, and continuous improvement.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.