Managing Users
One of the most common automation tasks is managing user accounts. Ansible provides the
user module to create, modify, and remove users across many servers consistently.Creating a User
This task creates a user named
deployer with a home directory and adds it to the sudo group:- name: Create deployer user
user:
name: deployer
comment: "Deployment user"
group: sudo
shell: /bin/bash
create_home: yes
state: presentSetting Up SSH Keys
Add an SSH public key for passwordless login:
- name: Add SSH key for deployer
authorized_key:
user: deployer
state: present
key: "{{ lookup('file', 'files/deployer.pub') }}"Setting Password (Hashed)
To set a password, provide a hashed value. Generate a hash with
mkpasswd --method=sha-512 or using Python:python3 -c 'import crypt; print(crypt.crypt("mypassword", crypt.mksalt(crypt.METHOD_SHA512)))'Then in the playbook:- name: Set user password
user:
name: deployer
password: "$6$rounds=656000$..."
update_password: on_createRemoving a User
To delete a user and optionally remove home directory:
- name: Remove old user
user:
name: olduser
state: absent
remove: yesManaging Groups
Create a group and add users to it:
- name: Create developers group
group:
name: developers
state: present
- name: Add user to developers
user:
name: alice
groups: developers
append: yesTwo Minute Drill
- Use
usermodule to create, modify, or delete users. - Add SSH keys with
authorized_keymodule. - Passwords must be hashed; use
mkpasswdor Python crypt. - Manage groups with
groupmodule andusergroups parameter.
Need more clarification?
Drop us an email at career@quipoinfotech.com
