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.
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
```yaml
---
- 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: "An