Lab 007 - Create user with Ansible¶
- In this section we will understand how to use the
Create User Playbook. - We will have hands-on experience in writing it ourselves using a sample playbook.
- We will review the playbook’s
vars,become,changed_whensections. - We will edit the script to create another user with different name and password.
01. Ansible’s user module¶
- Ansible’s
usermodule is a powerful tool for managing user accounts on remote systems. It allows you to create, update, and remove users, set passwords, manage groups, and configure SSH keys. This is essential in automating system administration tasks. - See the Ansible
user moduledocumentation.
02. Create a user¶
- See the below basic example for creating a user named
usernamewith a hashed password, adding them to thewheelgroup, and generating an SSH key.
- name: Create a new user
ansible.builtin.user:
name: "username"
password: "{{ 'password' | password_hash('sha512') }}"
groups: "wheel"
shell: /bin/bash
state: present
create_home: true
generate_ssh_key: true
- See the below advanced example, including
custom home,expiry, andcomment
- name: Create a user with custom options
ansible.builtin.user:
name: "devops"
comment: "DevOps Engineer"
home: "/opt/devops"
expires: 1751328000 # Unix timestamp for expiry
password: "{{ 'SuperSecret123' | password_hash('sha512') }}"
groups: "sudo"
shell: /bin/zsh
state: present
create_home: true
03. Password management¶
- Always hash passwords using the
password_hashfilter for security. - Example:
- You can generate a hash in Python:
- See the
password hashin Ansible documentation.
04. SSH key setup¶
- Use
generate_ssh_key: trueto automatically create an SSH key for the user. - You can specify key type and file:
05. Troubleshooting & verification¶
- Use the
commandmodule to verify user creation: - See
/etc/passwdand/etc/groupfor user and group info.
06. Best practices¶
- Use
become: truefor privilege escalation. - Use variables for usernames and passwords to avoid hardcoding.
- Document your playbooks for clarity.
- Clean up users with
state: absentwhen needed.