How can I add a user to additional groups with Ansible? For example, I would like to add a user to the sudo
group without replacing the user's existing set of groups.
How can I add a user to additional groups with Ansible? For example, I would like to add a user to the sudo
group without replacing the user's existing set of groups.
If
{{ user }}
already exists in the system, you should use the following to just add it to a group:To add it to a set of groups, you can use a comma separated list, for example
groups: admin,sudo
.Just beware that if you omit
append: yes
, your user will be removed from all other groups, according to the usermod man page. That would useful if you want to use a specific list of groups a user should belong to.According to the User module you can use this:
You can just add the
groups=groupname
andappend=yes
to add them to an existing user when you're creating themPlease note that
{{ user }}
was changed to{{ ansible_user }}
in recent Ansible versions (https://github.com/ansible/ansible/blob/c600ab81ee/lib/ansible/playbook/play_context.py#L46-L55). Alternatively, you can also useansible_ssh_user
- it's the same. So, the updated code from admirabilis looks like:More fixes:
become: yes
since it needs administrative privileges to change the groups file