Ansible example: Filter user groups, only keep groups which exist
When creating users in Ansible, you may want to assign them to a list of groups, but not all groups may exist on every system. To avoid errors, you can filter the group list to only include groups that actually exist.
Here’s a minimal example playbook that demonstrates how to do this:
---
- name: Create user with filtered groups
hosts: all
become: true
vars:
# Some groups may not exist on all systems!
user_groups: "adm,sudo,sambashare,tss,docker,realtime,versatile,libvirt,libvirt-qemu,libvirt-dnsmasq,boinc,kvm,video,plugdev,users,render,video"
tasks:
- name: Get existing groups
ansible.builtin.getent:
database: group
register: existing_groups
- name: Filter user_groups to only existing groups
set_fact:
filtered_user_groups: >-
{{
user_groups.split(',') | select('in', (existing_groups.ansible_facts.getent_group.keys() | list)) | list
}}
- name: Create user deleteme
user:
name: "deleteme"
password: "abc123"
comment: "Please delete me"
shell: /bin/bash
createhome: no
state: present
groups: "{{ filtered_user_groups }}"
How it works:
- The
getent
module collects all groups on the system. - The
set_fact
task splits the comma-separateduser_groups
string into a list and filters it to only include groups present in the system’s group database. - The
user
module then creates the user with only the valid groups.
This approach prevents Ansible from failing if a group in your list does not exist on the target system.
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow