Ansible: Add Unix group to user only if the group exists Ansible: Add Unix group to user only if the group exists unix unix

Ansible: Add Unix group to user only if the group exists


The getent module can be used to read /etc/group

- name: Determine available groups  getent:    database: group- name: Add additional groups to user  user: name="{{user}}" groups="{{item}}" append=yes  when: item in ansible_facts.getent_group  with_items:       - sudo      - wheel


Do you have anything to identify those different host types?

If not, you first need to check which groups exist on that host. You can do this with the command getent group | cut -d: -f1 which will output one group per line.

You can use this as separate task like so:

- shell: getent group | cut -d: -f1  register: unix_groups

The registered result then can be used later when you want to add the user group

- user: ...  when: "'some_group' in unix_groups.stdout_lines"