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 Create User Account: user Module Complete Guide

By Luca Berton · Published 2024-01-01 · Category: windows-automation

How to create user accounts with Ansible user module. Set passwords, SSH keys, groups, shells, home directories, and manage users with examples.

Ansible Create User Account: user Module Complete Guide

How to create 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 Password Expiration: Manage User Account Aging & Policies

Ansible create a user account

Today we're talking about 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 useradd tool to create, on FreeBSD, this module uses pw useradd, On macOS, this module uses dscl create. For Windows, use the ansible.windows.win_user module instead.

Main Parameters

• name _string_ - username • state _string_ - present/absent • password _string_ – {{ 'password' | password_hash('sha512', 'salt') }} • uid _string_ • comment _string_ • shell _string_ • expires _string_ • password_expire_min _string_ • password_expire_max _string_ • group/groups _string_ - primary/membership group(s) • create_home _boolean_ - yes/no • generate_ssh_key _string_ • ssh_key_bits _string_ • ssh_key_file _string_ • ssh_key_type _string_ • ssh_key_passphrase _string_

This module has some parameters to perform some tasks. The only required is "name", which is the username. The "state" parameter allows us to create or delete a user, in our use case the default it's already set to "present" to create a user. "password" is very often used in conjunction with the passhword_hash filter to generate a password. Please note that you could specify the encryption algorithm as well as the salt to make your password more robust. We could specify all the usual Unix properties such as like uid, comment, shell, expires, password_expire_min, password_expire_max. Other important parameters are "group" and "groups". The first (without the "s" ending) indicate the primary group of the user, the second (with the "s" ending) set the other group members. So be very careful with the "s" ending, it could end up in a very different setup. Usually, we would like to create a user home directory so the "create_home" parameter defaults to yes, but we could override if we don't need a home directory. Let me also highlight that we could also generate an SSH key with a lot of options. The fingerprint and the public key are available in the long list of returned values.

## Playbook Let's jump in a real-life Ansible Playbook to create a user. • user.yml

---
- name: user module Playbook
  hosts: all
  become: true
  tasks:
    - name: user example present
      ansible.builtin.user:
        name: example
        password: "{{ 'password' | password_hash('sha512', 'mysecretsalt') }}"
        groups:
          - wheel
          - adm
        state: "present"
        shell: "/bin/bash"
        system: false
        create_home: true
        home: "/home/example"
        comment: "Ansible example"
        generate_ssh_key: true

code with ❤️ in GitHub

See also: Ansible group Module: Create & Manage Linux Groups (ansible.builtin.group)

Conclusion

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

Create Basic User

- name: Create user
  ansible.builtin.user:
    name: deploy
    comment: "Deploy User"
    shell: /bin/bash
    create_home: true
  become: true

See also: Ansible Manage Groups: Create, Delete & Modify with group Module

Create with Password

- ansible.builtin.user:
    name: john
    password: "{{ 'SecurePass123!' | password_hash('sha512') }}"
    update_password: on_create
  become: true

Create with SSH Key

- ansible.builtin.user:
    name: deploy
    shell: /bin/bash
  become: true

- ansible.posix.authorized_key: user: deploy key: "{{ lookup('file', '~/.ssh/deploy_key.pub') }}" become: true

Generate SSH Key for User

- ansible.builtin.user:
    name: deploy
    generate_ssh_key: true
    ssh_key_type: ed25519
    ssh_key_comment: "deploy@{{ inventory_hostname }}"
  become: true

Create with Groups

- ansible.builtin.user:
    name: deploy
    groups: [docker, sudo, developers]
    append: true  # Don't remove from existing groups
  become: true

System User (No Login)

- ansible.builtin.user:
    name: appservice
    system: true
    shell: /usr/sbin/nologin
    home: /opt/myapp
    create_home: false
  become: true

Full User Setup Playbook

---
- name: Create team users
  hosts: all
  become: true
  vars:
    users:
      - { name: alice, groups: [sudo, docker], key: "ssh-ed25519 AAAA..." }
      - { name: bob, groups: [docker], key: "ssh-ed25519 BBBB..." }
      - { name: charlie, groups: [developers], key: "ssh-ed25519 CCCC..." }
  tasks:
    - name: Create users
      ansible.builtin.user:
        name: "{{ item.name }}"
        groups: "{{ item.groups }}"
        append: true
        shell: /bin/bash
      loop: "{{ users }}"

- name: Deploy SSH keys ansible.posix.authorized_key: user: "{{ item.name }}" key: "{{ item.key }}" loop: "{{ users }}"

- name: Configure sudoers ansible.builtin.copy: content: "{{ item.name }} ALL=(ALL) NOPASSWD: ALL" dest: "/etc/sudoers.d/{{ item.name }}" mode: '0440' validate: 'visudo -cf %s' loop: "{{ users | selectattr('groups', 'contains', 'sudo') }}"

Key Parameters

| Parameter | Description | |-----------|-------------| | name | Username | | password | Hashed password | | groups | List of groups | | append | Add to groups (don't replace) | | shell | Login shell | | home | Home directory path | | create_home | Create home directory | | system | System account | | uid | Specific UID | | state | present or absent | | remove | Remove home when absent | | expires | Account expiry (epoch) | | generate_ssh_key | Generate SSH keypair |

FAQ

How do I delete a user?

- ansible.builtin.user:
    name: olduser
    state: absent
    remove: true  # Also remove home directory
  become: true

Why does password change every run?

The hash includes a random salt. Use update_password: on_create to only set on creation, or pre-generate and store the hash.

How do I lock/unlock an account?

# Lock
- command: usermod -L {{ username }}

# Unlock - command: usermod -U {{ username }}

Create Basic User

- ansible.builtin.user:
    name: deploy
    state: present
  become: true

Full User Setup

- user:
    name: deploy
    comment: "Deploy User"
    uid: 1500
    group: deploy
    groups: [sudo, docker]
    shell: /bin/bash
    create_home: true
    home: /home/deploy
    password: "{{ vault_password | password_hash('sha512') }}"
  become: true
  no_log: true

Create Multiple Users

- user:
    name: "{{ item.name }}"
    groups: "{{ item.groups | default([]) }}"
    shell: "{{ item.shell | default('/bin/bash') }}"
    create_home: true
  loop:
    - { name: alice, groups: [sudo, developers] }
    - { name: bob, groups: [developers] }
    - { name: charlie, groups: [developers, docker] }
  become: true

Add SSH Key

- user:
    name: deploy
    state: present
  become: true

- authorized_key: user: deploy key: "{{ lookup('file', 'keys/' + item + '.pub') }}" loop: [alice, bob] become: true

System User (No Login)

- user:
    name: myapp
    system: true
    shell: /usr/sbin/nologin
    home: /opt/myapp
    create_home: false
  become: true

Generate SSH Key for User

- user:
    name: deploy
    generate_ssh_key: true
    ssh_key_bits: 4096
    ssh_key_file: /home/deploy/.ssh/id_rsa
  become: true

Remove User

- user:
    name: olduser
    state: absent
    remove: true  # Remove home directory too
  become: true

Lock/Unlock Account

# Lock (disable login)
- user:
    name: baduser
    password_lock: true
  become: true

# Unlock - user: name: baduser password_lock: false become: true

Set Password Expiry

- user:
    name: contractor
    password: "{{ pass | password_hash('sha512') }}"
    expires: "{{ ('2026-12-31' | to_datetime).strftime('%s') }}"
  become: true
  no_log: true

Key Parameters

| Parameter | Description | |-----------|-------------| | name | Username | | state | present / absent | | uid | User ID | | group | Primary group | | groups | Supplementary groups | | append | Append to groups (don't replace) | | shell | Login shell | | home | Home directory path | | create_home | Create home dir | | system | System account | | password | Hashed password | | password_lock | Lock account | | expires | Account expiry (epoch) | | remove | Remove home on delete | | generate_ssh_key | Create SSH keypair |

FAQ

groups replaces all groups?

By default, yes. Add append: true to add to existing groups without removing current ones.

How to set password without password_hash?

You can't — Ansible requires pre-hashed passwords. Use password_hash('sha512') filter.

How to create a group first?

- group: { name: developers, state: present }
- user: { name: alice, groups: [developers] }

Related Articles

how Ansible become works under the hoodbuilding reusable Ansible rolesWindows management with Ansible

See also

Ansible Rolling Update Debian/Ubuntu: apt Module Guide (Examples)

Category: windows-automation

Watch the video: Ansible Create User Account: user Module Complete Guide — Video Tutorial

Browse all Ansible tutorials · AnsiblePilot Home