Introduction
An idempotent Ansible playbook for Linux users and sudoers manages account state declaratively. The core pieces are ansible.builtin.user for account attributes and group membership, ansible.posix.authorized_key for SSH keys, and a sudoers path that validates with visudo -c before replacing a file. The goal is not only changed=0 on a second run, but also a playbook that can be rerun safely after partial changes, host drift, or inventory growth.
Common breakages are avoidable. Shell commands such as useradd hide state and can fail or diverge on reruns. groups without append can replace secondary group membership. Password-hash generation can report changes on every run when the hash is not stable. A sudoers write without validation can leave a host with broken sudo policy. This article walks through a safe, reviewable pattern and the checks that belong around it.
Why shell-based user management fails on the second run
Many playbooks still start with a command module and a creates guard:
- name: Create deploy user ansible.builtin.command: useradd -m -s /bin/bash deploy args: creates: /home/deployThis looks idempotent because of creates. It is not. The guard only checks whether the home directory exists. If someone changed the shell, added a group, or lost the directory, the task skips silently and reports ok. Ansible has no idea what state the account is in. The same applies to shell: usermod -aG docker deploy without a guard: it reports changed on every run because Ansible cannot know that usermod already did the work. Adding changed_when: false hides the symptom and keeps the playbook lying to you.
The command module is the wrong tool for account state. Use the user, group, and authorized_key modules, which read the current state from /etc/passwd, /etc/group, and the key file, then act only on the delta.
The user module parameters that decide idempotency
ansible.builtin.user manages account attributes by comparing requested values with target state, then changing attributes that differ. Exact behavior depends on the platform utilities and parameters in use. Review the module documentation for the deployed ansible-core version, especially when managing supplementary groups, passwords, or account removal.
Four parameters change the outcome. append controls what happens when groups is set. The default is false, which means the groups list replaces every secondary group the account has. append: true merges the list into the existing set. For management accounts this is nearly always the setting you want.
update_password controls whether the password argument is applied on every run. always is the default: the module evaluates the hash every time and reports changed if the hash differs from /etc/shadow. on_create sets the password only when the account does not exist yet.
remove: true requests removal of the user’s home directory and mail spool when supported by the target platform. Treat this as destructive: confirm ownership, backups, and retention requirements before enabling it. Avoid force: true unless you have reviewed the target platform’s userdel --force behavior and have an approved recovery plan.
password_expire_max, password_expire_min, and password_expire_warn set the aging fields in /etc/shadow. They are idempotent but only work on systems with chage installed (shadow-utils on RHEL, the passwd package on Debian).
A minimal idempotent task:
- name: Ensure deploy user exists ansible.builtin.user: name: deploy uid: 1500 group: deploy groups: - wheel - docker append: true shell: /bin/bash home: /home/deploy create_home: true password: "{{ deploy_password_hash }}" update_password: on_create state: presentadmin_group should be set per distribution or inventory group. On RHEL-family hosts the administrative group is typically wheel; on Debian-family hosts it is commonly sudo. Do not hardcode either name across a mixed fleet. If the target group does not exist on the host, ansible.builtin.user/usermod will fail.
Password hashes without churn on every run
ansible.builtin.user expects password to be a hash, not plaintext; it writes the string into the password database as given. Passing plaintext leaves the account with a value the PAM stack cannot verify, so password login fails.
The password parameter expects a platform-appropriate encrypted password hash, not plaintext. Protect the source secret with Ansible Vault or an external secrets manager, and mark password-related tasks no_log: true to reduce exposure in normal output. Be aware that no_log also hides useful diagnostics; test the workflow with non-sensitive data first.
If you manage password hashes declaratively, compute a stable hash using the password_hash filter and a protected, fixed salt. A newly generated salt changes the output hash even when the plaintext is unchanged, which can cause repeated changes with update_password: always. The filter may require passlib in the controller’s Ansible Python environment; pin and install that dependency through the project’s supported environment or collection requirements, not an unscoped system pip install.
Do not place plaintext passwords in shell command arguments, task output, or unencrypted inventory. Avoid printing /etc/shadow in diagnostics. Verify password-management behavior in a disposable test environment using the exact Ansible version and target OS; accepted hash schemes vary by platform and PAM configuration.
update_password: on_create sets the supplied hash when creating an account and does not rotate it on subsequent runs. That can be appropriate when password rotation is managed separately, but document the ownership boundary. If Ansible must rotate an existing account, use a controlled rotation workflow, a stable hash input, no_log: true, and a recovery path.
How group membership gets overwritten
When groups is set without append, the user module replaces the secondary group list. A task like:
- ansible.builtin.user: name: deploy groups: dockerremoves deploy from every secondary group that is not docker on its next run. If the desired list omits the group that sudo depends on, the account loses sudo access even though the task reports changed only once.
When the playbook manages a subset of groups and leaves the rest alone, use append: true:
- ansible.builtin.user: name: deploy groups: - docker append: trueIf the playbook owns the full list, keep append: false and list every group explicitly. That makes the account state fully declarative, but it also means any group a human adds by hand will be removed on the next run. Pick one model and state it in the role’s README, because mixing the two across hosts produces inventory drift that takes a day to trace.
- name: Ensure app groups exist ansible.builtin.group: name: "{{ item }}" state: present loop: - docker - deploySkipping this step is the source of usermod: group 'docker' does not exist. The user module does not create groups for you.
SSH keys with authorized_key
ansible.posix.authorized_key manages the specified public key in ~/.ssh/authorized_keys. Start by managing only the key or keys this play owns:
- name: Install deploy SSH key ansible.posix.authorized_key: user: deploy key: "{{ lookup('file', 'files/keys/deploy_ed25519.pub') }}" state: presentThe module parses authorized-key records; it does not require byte-for-byte equality of the whole file. Keep the key material stable and use the module’s key parameter as documented. Avoid filters that could alter the key contents unexpectedly.
exclusive: true removes every key not included in the supplied key value. The module documentation notes that exclusive mode is not loop-aware, so pass the complete newline-delimited key list in one task if using it. Enable this only when the playbook is authoritative for the account’s entire key file and you have an out-of-band recovery path. For shared or break-glass accounts, leave it disabled and coordinate key removals explicitly.
authorized_key moved from the core repository to the ansible.posix collection in Ansible 2.10. The ansible.builtin.authorized_key name still resolves through a redirect, but pinning the collection is cleaner:
ansible-galaxy collection install ansible.posixSudoers: lineinfile, template, or community.general.sudoers
You can manage sudo policy in /etc/sudoers or a separate file included from it. Before writing to /etc/sudoers.d/, verify the main file includes that directory. On systems using @includedir or #includedir, sudo applies filename filtering rules; use a simple name such as 90-deploy and verify the effective policy with visudo -c and sudo -l -U deploy.
lineinfile writes or replaces one line and is the smallest change:
- name: Grant deploy passwordless sudo ansible.builtin.lineinfile: path: /etc/sudoers.d/90-deploy regexp: '^deploy\s' line: "deploy ALL=(ALL) NOPASSWD: ALL" create: true owner: root group: root mode: "0440" validate: /usr/sbin/visudo -cf %sregexp is not optional. Without it, changing the line appends the new version next to the old one, and the file grows every time the playbook changes the desired rule. The regexp anchors the match to the start of the line, so an existing deploy ALL=(ALL) ALL line is replaced, not duplicated.
template renders the whole file:
- name: Render sudoers file for deploy ansible.builtin.template: src: sudoers.j2 dest: /etc/sudoers.d/90-deploy owner: root group: root mode: "0440" validate: /usr/sbin/visudo -cf %swith templates/sudoers.j2:
# Managed by Ansible. Do not edit.{{ item.name }} ALL=(ALL) {{ item.sudo }}This is cleaner for multi-line rules such as Cmnd_Alias blocks, but it wipes any edit a human made in the file. That is the point of a template, and the header line says so.
community.general.sudoers can be an alternative for some teams, but this article keeps the safer copy-validated path shown above to emphasize the visudo -cf %s validation guarantee. The module has its own validation option name (validation), and supports nopassword, commands, and setenv. Pick the option that fits the role’s complexity, but retain validate: /usr/sbin/visudo -cf %s on lineinfile or template paths so a syntax mistake cannot lock the host out.
Validating sudoers before it locks you out
Every sudoers task must have validate. Without it, a typo in the line makes visudo on the host refuse to parse /etc/sudoers, and no one can run sudo until someone fixes the file from a recovery shell or the root console.
The validate argument runs a command against a temporary path before the file is moved into place. %s is replaced with the temp file. If the command returns non-zero, the task fails and the original file is untouched.
validate: /usr/sbin/visudo -cf %svisudo -c checks syntax, and -f points at a file instead of the default /etc/sudoers. Use the absolute path, because Ansible runs validate without a login shell on some connection plugins, so visudo alone can fail with No such file or directory even when the binary is on the host.
The rendered command looks like:
/usr/sbin/visudo -cf /tmp/ansible.builtin.tmp.f8c2b1If sudo is not installed (minimal containers, some Alpine images), the task fails with [Errno 2] No such file or directory. Install it first:
- name: Ensure sudo is installed ansible.builtin.package: name: sudo state: presentvisudo -c performs syntax checks on the sudoers files it reads. It does not confirm that every user or group named in a rule exists on the host, so a rule that references a group missing from /etc/group can pass validation and still be unusable. Resolve group names against the target host before applying them, and verify the effective policy afterwards with visudo -c and sudo -l -U <user>.
Removing users safely
Account removal is a separate, explicitly reviewed operation. state: absent removes the account entry; remove: true may also remove the home directory and mail spool, depending on the target platform. Keep those choices out of a routine user-provisioning run unless the inventory and approval process deliberately manage deprovisioning.
Before removing an account, verify the target host, account name and UID, active sessions, file ownership, service dependencies, and backup or retention requirements. Do not automatically kill all of the user’s processes. Stop or migrate services through their own change process, then remove the account in a reviewed maintenance window. Avoid force: true unless the platform-specific consequences are understood.
A separately gated deprovisioning task can remove the account and its sudoers entry after approval:
- name: Remove deploy sudoers entry after approval ansible.builtin.file: path: /etc/sudoers.d/90-deploy state: absent when: approve_deploy_removal | default(false) | bool
- name: Remove deploy account after approval ansible.builtin.user: name: deploy state: absent remove: false when: approve_deploy_removal | default(false) | boolThis intentionally leaves home data in place for a separate, reviewed retention decision. Confirm the effective sudo policy after the change with visudo -c and the relevant access check. A removal task should not be combined with routine provisioning in a way that allows an inventory mistake to delete accounts or data silently.
A role layout that stays idempotent
A working structure for the whole thing:
roles/users/ defaults/main.yml tasks/main.yml templates/sudoers.j2 files/keys/deploy.pub vars/vault.ymldefaults/main.yml:
managed_users: - name: deploy primary_group: "{{ admin_group | default('deploy') }}" groups: - "{{ admin_group | default('deploy') }}" - docker sudo: "NOPASSWD: ALL" ssh_key: files/keys/deploy.pub state: present - name: ops primary_group: "ops" groups: - ops sudo: "ALL" ssh_key: files/keys/ops.pub state: presenttasks/main.yml:
- name: Ensure managed groups exist ansible.builtin.group: name: "{{ item }}" state: present loop: "{{ managed_users | selectattr('groups', 'defined') | map(attribute='groups') | flatten | unique | list }}"
- name: Ensure managed users exist ansible.builtin.user: name: "{{ item.name }}" uid: "{{ item.uid | default(omit) }}" group: "{{ item.primary_group | default(omit) }}" groups: "{{ item.groups | default(omit) }}" append: true shell: "{{ item.shell | default('/bin/bash') }}" create_home: true state: "{{ item.state | default('present') }}" loop: "{{ managed_users }}"
- name: Install SSH keys ansible.posix.authorized_key: user: "{{ item.name }}" key: "{{ lookup('file', item.ssh_key) | trim }}" loop: "{{ managed_users | selectattr('ssh_key', 'defined') | list }}" when: (item.state | default('present')) == 'present'
- name: Render sudoers entries ansible.builtin.template: src: sudoers.j2 dest: "/etc/sudoers.d/90-{{ item.name }}" owner: root group: root mode: "0440" validate: /usr/sbin/visudo -cf %s loop: "{{ managed_users | selectattr('sudo', 'defined') | list }}" when: (item.state | default('present')) == 'present'
- name: Remove sudoers entries for absent users ansible.builtin.file: path: "/etc/sudoers.d/90-{{ item.name }}" state: absent loop: "{{ managed_users | selectattr('state', 'defined') | selectattr('state', 'equalto', 'absent') | list }}"Two design decisions in this layout are worth calling out. First, sudoers files are rendered from a template instead of lineinfile, so --diff mode shows the full file and a reviewer can read it in one pass. Second, the removal tasks use a selectattr filter instead of when, which keeps the condition next to the loop and makes the branch visible to someone reading the task in isolation.
Check mode and diff mode
Idempotency is a property you test, not a property you assert. Run the playbook twice:
ansible-playbook -i inventory site.ymlansible-playbook -i inventory site.ymlOn a stable host with no concurrent changes, the second run should report changed=0 for this role. Treat any remaining changed as a bug to investigate, with two exceptions: tasks that legitimately react to fresh facts, and command/shell tasks whose changed_when is not set. Modules in this article report changes by comparing requested state with the target, so a clean second run is the expected result, not an assertion to hardcode into other playbooks.
--check --diff shows what the playbook would change without changing it, and it is the fastest way to catch drift:
ansible-playbook -i inventory site.yml --check --diffThree caveats. Tasks built on command or shell do not follow check-mode semantics unless you define check_mode and changed_when; avoid them for account management. authorized_key with exclusive: true can report deletions, but it is not loop-safe, so supply the complete key list in a single task. Password handling depends on the module and platform; verify real behavior by running the playbook twice in a disposable test VM instead of trusting a check-mode report alone.
A CI assertion catches silent non-idempotency:
ansible-playbook -i inventory site.yml | tee /tmp/run.loggrep -E 'changed=[1-9]' /tmp/run.log && exit 1Troubleshooting real failures
If ansible.builtin.user or usermod reports that the platform tool failed locally, adjust the task to match platform expectations and review any platform-specific warnings or error text. For example, account removal failures may be related to the userdel behavior on the target OS, or to strict filesystem controls on minimal containers.
When using validate on sudoers tasks, a failing validation command aborts the operation and leaves the existing sudoers file unchanged. This makes it straightforward to hand-edit the sudoers configuration, rerun validation, and then retry the task once the syntax is correct.
If the collection is not installed on the controller, Ansible reports an error starting your task. Install the required collections with ansible-galaxy collection install <collection> and pin them in a collections.yml so CI reproduces the environment.
If password_hash expects passlib on the controller, getent shadow, or usermod failures after configuration may be due to mismatches between the hash scheme the module uses and what the target PAM stack expects on that platform; swap or regenerate a plain password, recompute the hash, retest in a disposable virtual machine with the exact Ansible version and OS configuration.
Permission errors may appear around sudoers files if the mode or owner do not match platform expectations. On Debian-style systems, /etc/sudoers.d files should be owned by root and modeled 0400 or 0440 so that they are readable only by root and optionally sudo. The lineinfile and template tasks set owner: root and mode: "0440", which matches the platform requirement. If you use custom templates, validate the final mode before deploying with a shell-based command by hand, or incorporate a shell task to check and fix permissions, then run validation.
Trade-offs and limits
The user module does not manage /etc/sudoers and does not manage SSH keys, so idempotency for account access spans three modules. That is by design. Each module reads and writes one file or one directory, and the playbook composes them.
update_password: on_create is idempotent but never rotates an existing password. A rotation play needs update_password: always, a vaulted fixed salt, and no_log: true on tasks that handle the password hash. Set no_log: true on any task that constructs or sends a password variable to prevent it from appearing in logs or CI output.
exclusive: true on authorized_key is safe only when the key list is complete. In an inventory where humans add break-glass keys out of band, exclusive removes them on the next run. Choose per account.
Collection dependencies (ansible.posix, community.general) are an operational cost. Pin them in collections/requirements.yml and install on the controller before the CI job runs, not inside the playbook.
The user module reads /etc/shadow, which requires root on most systems. Every playbook in this article runs with become: true and a sudo rule for the Ansible user. Audit that rule first, because the account that manages users and sudoers can create or modify any account on the host, including its own.