AnsiblePilot — Master Ansible Automation

AnsiblePilot is the leading resource for learning Ansible automation, DevOps, and infrastructure as code. Browse over 1,400 tutorials covering Ansible modules, playbooks, roles, collections, and real-world examples. Whether you are a beginner or an experienced engineer, our step-by-step guides help you automate Linux, Windows, cloud, containers, and network infrastructure.

Popular Topics

About Luca Berton

Luca Berton is an Ansible automation expert, author of 8 Ansible books published by Apress and Leanpub including "Ansible for VMware by Examples" and "Ansible for Kubernetes by Example", and creator of the Ansible Pilot YouTube channel. He shares practical automation knowledge through tutorials, books, and video courses to help IT professionals and DevOps engineers master infrastructure automation.

Ansible Remove User Account: Delete Users with user Module

By Luca Berton · Published 2024-01-01 · Category: troubleshooting

How to remove user accounts with Ansible user module. Delete users, remove home directories, force removal of logged-in users, and manage bulk deprovisioning.

Ansible Remove User Account: Delete Users with user Module

How to remove a user account with Ansible?

I'm going to show you a live Playbook with some simple Ansible code. I'm Luca Berton and welcome to today's episode of Ansible Pilot.

See also: Ansible Create User Account: user Module Complete Guide

Ansible remove user account

Today we're talking about the Ansible module user. The full name is ansible.builtin.user, which means that is part of the collection of modules "builtin" with ansible and shipped with it. It's a module pretty stable and out for years, it manages user accounts. It supports a huge variety of Linux distributions, SunOS and macOS, and FreeBSD. This module uses Linux distributions userdel to delete, on FreeBSD, this module uses pw userdel, on macOS, this module uses dscl. For Windows, use the ansible.windows.win_user module instead.

Main Parameters

name _string_ - username • state _string_ - present/absent • remove _boolean_ - no/yes

This module has many parameters to perform any task. The only required is "name", which is the username. "state" allows us to create or delete a user, in the use case we need to specify "absent" to delete a user. If we would like to try to remove the directories associated with the user, we need to set the parameter "remove". The behavior is the same as userdel --remove. Files in the user's home directory will be removed along with the home directory itself and the user's mail spool. Files in other parts of the file system will have to be searched for and deleted manually.

## Playbook Let's jump into a real-life Ansible Playbook to delete a user. • _delete_user.yml_

---
- name: user module Playbook
  hosts: all
  become: true
  tasks:
    - name: user example not present
      ansible.builtin.user:
        name: example
        state: "absent"
        remove: true

code with ❤️ in GitHub

See also: Ansible Password Expiration: Manage User Account Aging & Policies

Conclusion

Now you know how to remove a user account with Ansible.

Advanced User Removal Examples

Remove user and their home directory

- name: Remove user and home directory
  ansible.builtin.user:
    name: olduser
    state: absent
    remove: true  # Removes home directory and mail spool
  become: true

Force remove user (even if logged in)

- name: Force remove user with active sessions
  ansible.builtin.user:
    name: olduser
    state: absent
    remove: true
    force: true  # Kills user processes and removes even if logged in
  become: true

Remove multiple users

- name: Remove decommissioned users
  ansible.builtin.user:
    name: "{{ item }}"
    state: absent
    remove: true
  loop:
    - contractor1
    - contractor2
    - temp_user
  become: true

Safe removal with backup

- name: Check if user exists
  ansible.builtin.getent:
    database: passwd
    key: "{{ target_user }}"
  register: user_check
  failed_when: false

- name: Backup home directory before removal ansible.builtin.archive: path: "/home/{{ target_user }}" dest: "/backup/{{ target_user }}-{{ ansible_date_time.date }}.tar.gz" when: user_check.ansible_facts.getent_passwd[target_user] is not none become: true

- name: Remove user ansible.builtin.user: name: "{{ target_user }}" state: absent remove: true when: user_check.ansible_facts.getent_passwd[target_user] is not none become: true

Remove user from groups without deleting account

- name: Remove user from sudo group
  ansible.builtin.user:
    name: restricted_user
    groups: ""  # Remove from all supplementary groups
    append: false
  become: true

See also: Ansible Change Windows User Password: win_user Module (Examples)

Key Parameters for User Removal

| Parameter | Type | Description | |-----------|------|-------------| | name | string | Username to remove | | state | string | absent to remove | | remove | bool | Delete home dir and mail spool | | force | bool | Kill processes and force removal |

Windows User Removal

- name: Remove Windows user
  ansible.windows.win_user:
    name: olduser
    state: absent

FAQ

What happens to files owned by deleted user?

Files outside the home directory remain but are owned by the UID (shown as a number). Find and reassign them:

- name: Find orphaned files
  ansible.builtin.command: "find / -nouser -ls"
  register: orphans
  become: true
  changed_when: false

How do I remove a user from LDAP?

The user module manages local accounts. For LDAP, use community.general.ldap_entry with state: absent.

Does remove: true delete /home/username?

Yes, and also the mail spool at /var/mail/username. It does NOT delete files owned by the user in other locations.

Remove User

- name: Remove user account
  ansible.builtin.user:
    name: olduser
    state: absent
  become: true

Remove with Home Directory

- ansible.builtin.user:
    name: olduser
    state: absent
    remove: true  # Deletes home directory and mail spool
  become: true

Remove with Force

# Force removal even if user is logged in
- ansible.builtin.user:
    name: olduser
    state: absent
    remove: true
    force: true
  become: true

Safe Removal Pattern

- name: Kill user processes
  command: "pkill -u {{ item }}"
  loop: [olduser1, olduser2]
  ignore_errors: true
  become: true

- name: Remove crontab command: "crontab -r -u {{ item }}" loop: [olduser1, olduser2] ignore_errors: true become: true

- name: Remove user accounts ansible.builtin.user: name: "{{ item }}" state: absent remove: true force: true loop: [olduser1, olduser2] become: true

Disable Instead of Delete

# Lock account (safer than deletion)
- ansible.builtin.user:
    name: departing_employee
    shell: /sbin/nologin
    password_lock: true
    expires: 0
  become: true

Batch User Management

- name: Ensure only approved users exist
  vars:
    approved_users: [alice, bob, deploy, appuser]
  block:
    - command: "awk -F: '$3>=1000 && $3<65534 {print $1}' /etc/passwd"
      register: current_users
      changed_when: false

- set_fact: users_to_remove: "{{ current_users.stdout_lines | difference(approved_users) }}"

- name: Remove unauthorized users user: name: "{{ item }}" state: absent remove: true loop: "{{ users_to_remove }}" when: users_to_remove | length > 0 become: true

Revoke SSH Access

- name: Remove SSH authorized keys
  ansible.builtin.file:
    path: "/home/{{ item }}/.ssh/authorized_keys"
    state: absent
  loop: [olduser1, olduser2]
  become: true
  ignore_errors: true

- name: Remove from sudoers ansible.builtin.file: path: "/etc/sudoers.d/{{ item }}" state: absent loop: [olduser1, olduser2] become: true

Windows User Removal

- ansible.windows.win_user:
    name: olduser
    state: absent

user Module (removal params)

| Parameter | Description | |-----------|-------------| | name | Username | | state: absent | Remove the user | | remove: true | Delete home dir + mail spool | | force: true | Remove even if logged in | | password_lock: true | Lock (disable) instead | | shell: /sbin/nologin | Prevent login | | expires: 0 | Expire account immediately |

FAQ

What happens to user's files outside home?

Only remove: true deletes the home directory. Files owned by the user elsewhere remain. Find them with:

- command: "find / -user {{ username }} -not -path '/proc/*'"
  register: orphaned

Can I undo a user deletion?

No — once removed with remove: true, the home directory is gone. Always back up first if needed.

"user is currently logged in" error?

Use force: true or kill processes first with pkill -u username.

Remove User

- ansible.builtin.user:
    name: olduser
    state: absent
  become: true

Remove User and Home Directory

- user:
    name: olduser
    state: absent
    remove: true  # Removes home dir and mail spool
  become: true

Force Remove (Even If Logged In)

- user:
    name: olduser
    state: absent
    remove: true
    force: true  # Removes even if user is logged in
  become: true

Remove Multiple Users

- user:
    name: "{{ item }}"
    state: absent
    remove: true
  loop:
    - former_employee1
    - former_employee2
    - contractor_temp
  become: true

Offboarding Playbook

- hosts: all
  become: true
  vars:
    departing_users:
      - alice
      - bob
  tasks:
    - name: Kill user processes
      command: "pkill -u {{ item }}"
      loop: "{{ departing_users }}"
      ignore_errors: true

- name: Backup home directories archive: path: "/home/{{ item }}" dest: "/backup/users/{{ item }}-{{ ansible_date_time.date }}.tar.gz" loop: "{{ departing_users }}" ignore_errors: true

- name: Remove user accounts user: name: "{{ item }}" state: absent remove: true loop: "{{ departing_users }}"

- name: Remove sudoers entries file: path: "/etc/sudoers.d/{{ item }}" state: absent loop: "{{ departing_users }}"

- name: Remove from authorized_keys file: path: "/home/{{ item }}/.ssh" state: absent loop: "{{ departing_users }}"

Check Before Removing

- getent:
    database: passwd
    key: "{{ username }}"
  register: user_check
  ignore_errors: true

- user: name: "{{ username }}" state: absent remove: true when: user_check is success become: true

FAQ

What does remove: true delete?

The user's home directory and mail spool (/var/mail/username). Files owned by the user outside home are NOT removed.

How to find orphaned files after removal?

find / -nouser -o -nogroup 2>/dev/null

Can I disable instead of delete?

- user:
    name: olduser
    shell: /usr/sbin/nologin
    password_lock: true

Related Articles

Ansible become methods comparedWindows users and groups via Ansible

Category: troubleshooting

Watch the video: Ansible Remove User Account: Delete Users with user Module — Video Tutorial

Browse all Ansible tutorials · AnsiblePilot Home