Ansible user Module: Create & Manage Users (Complete Guide)
By Luca Berton · Published 2024-01-01 · Category: containers-kubernetes
How to create, modify, and delete users with the Ansible user module (ansible.builtin.user). Manage passwords, SSH keys, groups, home directories, and expiry dates with practical YAML examples.
Ansible user Module: Create & Manage Users (Complete Guide)
The Ansible user module (ansible.builtin.user) manages user accounts on Linux, macOS, and other UNIX systems. This guide covers creating users, setting passwords, managing groups, SSH keys, and removal.
Create a User
Key Parameters
| Parameter | Description | Default |
|-----------|-------------|---------|
| name | Username (required) | — |
| state | present or absent | present |
| uid | User ID number | Auto-assigned |
| group | Primary group | Same as username |
| groups | Supplementary groups | — |
| append | Append to groups (don't replace) | false |
| shell | Login shell | /bin/bash |
| home | Home directory path | /home/
Set User Password
Passwords must be hashed — never pass plaintext:
update_password Options • always — Update password every run (default) • on_create — Only set password when creating the user
Manage Groups
Generate SSH Keys
Add Authorized SSH Key
Combine with ansible.posix.authorized_key:
Create System Account
Set Account Expiry
Remove a User
Manage Multiple Users with Loop
Data-Driven User Management
Lock and Unlock Accounts
FAQ
How do I create a user with Ansible?
Use the ansible.builtin.user module with name and state: present. Set shell, groups, and password as needed. Example: ansible.builtin.user: name=deploy shell=/bin/bash groups=sudo.
How do I set a user password in Ansible?
Use the password parameter with a hashed password. Use the password_hash filter: password: "{{ 'plaintext' | password_hash('sha512') }}". Never pass plaintext passwords.
How do I add a user to a group without removing existing groups?
Set append: true when specifying groups. Without append: true, Ansible removes the user from all groups not listed.
How do I create multiple users in Ansible?
Use a loop with the user module. Define users as a list of dictionaries and iterate over them. This approach is idempotent and handles creation, modification, and removal.
What is the difference between group and groups in Ansible user module?
group sets the primary group (one group). groups sets supplementary groups (list). Use append: true with groups to add without replacing existing group memberships.
Conclusion
The Ansible user module handles complete user lifecycle management — from creation with passwords and SSH keys to group management and removal. Use append: true for groups, password_hash for passwords, and loops for managing multiple users at scale.
Related Articles • Ansible group Module: Manage Groups on Linux • Ansible authorized_key Module: Manage SSH Keys • Ansible Vault: Encrypt Sensitive Data
Category: containers-kubernetes