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 user Module: Create & Manage Users (Complete Guide)

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

How to create, modify, and delete users with the Ansible user module (ansible.builtin.user). Manage passwords, SSH keys, groups, home directories, and expiry.

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.

See also: Add Secondary Groups to Linux Users with Ansible Playbook

Create a User

---
- name: User management examples
  hosts: all
  become: true
  tasks:
    - name: Create a user
      ansible.builtin.user:
        name: deploy
        comment: "Deploy User"
        shell: /bin/bash
        create_home: true
        state: present

Key Parameters

ParameterDescriptionDefault
nameUsername (required)
statepresent or absentpresent
uidUser ID numberAuto-assigned
groupPrimary groupSame as username
groupsSupplementary groups
appendAppend to groups (don't replace)false
shellLogin shell/bin/bash
homeHome directory path/home/
create_homeCreate home directorytrue
passwordHashed password
commentGECOS field (full name)
expiresAccount expiry (epoch)
systemCreate system accountfalse
generate_ssh_keyGenerate SSH key pairfalse
removeRemove home dir on absentfalse

Set User Password

Passwords must be hashed — never pass plaintext:

- name: Create user with password
  ansible.builtin.user:
    name: webadmin
    password: "{{ 'MySecretPass123!' | password_hash('sha512', 'mysalt') }}"
    shell: /bin/bash
    update_password: on_create  # Only set password on first creation

- name: Create user with vault-encrypted password
  ansible.builtin.user:
    name: dbadmin
    password: "{{ vault_dbadmin_password | password_hash('sha512') }}"
    update_password: always

update_password Options

  • always — Update password every run (default)
  • on_create — Only set password when creating the user

Manage Groups

- name: Create user with primary and supplementary groups
  ansible.builtin.user:
    name: developer
    group: developers
    groups:
      - docker
      - sudo
      - www-data
    append: true  # Important! Without this, other groups are removed

- name: Add existing user to additional groups
  ansible.builtin.user:
    name: johndoe
    groups:
      - wheel
      - developers
    append: true

See also: Ansible Linux Users and Groups: Complete Management Guide (Examples)

Generate SSH Keys

- name: Create user with SSH key
  ansible.builtin.user:
    name: deploy
    generate_ssh_key: true
    ssh_key_bits: 4096
    ssh_key_type: rsa
    ssh_key_comment: "deploy@{{ inventory_hostname }}"
  register: user_info

- name: Display public key
  ansible.builtin.debug:
    msg: "{{ user_info.ssh_public_key }}"

Add Authorized SSH Key

Combine with ansible.posix.authorized_key:

- name: Create user and authorize SSH key
  ansible.builtin.user:
    name: deploy
    shell: /bin/bash

- name: Add authorized SSH key
  ansible.posix.authorized_key:
    user: deploy
    key: "{{ lookup('file', 'files/deploy_id_ed25519.pub') }}"
    state: present

See also: ansible.builtin.user Module: Create & Manage Linux Users (Complete Guide)

Create System Account

- name: Create application service account
  ansible.builtin.user:
    name: myapp
    system: true
    shell: /usr/sbin/nologin
    home: /opt/myapp
    create_home: true
    comment: "MyApp Service Account"

Set Account Expiry

- name: Create temporary contractor account (expires in 90 days)
  ansible.builtin.user:
    name: contractor
    expires: "{{ (ansible_date_time.epoch | int) + (90 * 86400) }}"
    shell: /bin/bash

- name: Create account with specific expiry date
  ansible.builtin.user:
    name: intern
    expires: "{{ ('2026-08-31' | to_datetime).strftime('%s') }}"
    comment: "Summer Intern 2026"

- name: Remove account expiry
  ansible.builtin.user:
    name: contractor
    expires: -1

Remove a User

- name: Remove user (keep home directory)
  ansible.builtin.user:
    name: oldemployee
    state: absent

- name: Remove user AND home directory
  ansible.builtin.user:
    name: oldemployee
    state: absent
    remove: true
    force: true  # Remove even if user is logged in

Manage Multiple Users with Loop

- name: Create multiple users
  ansible.builtin.user:
    name: "{{ item.name }}"
    groups: "{{ item.groups | default(omit) }}"
    shell: "{{ item.shell | default('/bin/bash') }}"
    state: "{{ item.state | default('present') }}"
    append: true
  loop:
    - { name: alice, groups: [sudo, developers] }
    - { name: bob, groups: [developers] }
    - { name: charlie, groups: [developers, docker] }
    - { name: olduser, state: absent }

Data-Driven User Management

# vars/users.yml
users:
  - name: alice
    groups: [sudo, developers]
    ssh_key: "ssh-ed25519 AAAA... alice@laptop"
  - name: bob
    groups: [developers]
    ssh_key: "ssh-ed25519 AAAA... bob@laptop"

# tasks
- name: Create users
  ansible.builtin.user:
    name: "{{ item.name }}"
    groups: "{{ item.groups }}"
    append: true
    shell: /bin/bash
  loop: "{{ users }}"

- name: Set SSH keys
  ansible.posix.authorized_key:
    user: "{{ item.name }}"
    key: "{{ item.ssh_key }}"
  loop: "{{ users }}"
  when: item.ssh_key is defined

Lock and Unlock Accounts

- name: Lock user account
  ansible.builtin.user:
    name: suspicious_user
    password_lock: true

- name: Unlock user account
  ansible.builtin.user:
    name: suspicious_user
    password_lock: false

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.

Category: installation

Browse all Ansible tutorials · AnsiblePilot Home