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

Viewed 25465

I'm using Ansible to add a user to a variety of servers. Some of the servers have different UNIX groups defined. I'd like to find a way for Ansible to check for the existence of a group that I specify, and if that group exists, add it to a User's secondary groups list (but ignore the statement it if the group does not exist).

Any thoughts on how I might do this with Ansible?

Here is my starting point.

Command

ansible-playbook -i 'localhost,' -c local ansible_user.yml

ansible_user.yml

---

- hosts: all
  user: root
  become: yes
  vars:
    password: "!"
    user: testa
  tasks:
    - name: add user
      user: name="{{user}}"
            state=present
            password="{{password}}"
            shell=/bin/bash
            append=yes
            comment="test User"

Updated: based on the solution suggested by @udondan, I was able to get this working with the following additional tasks.

    - name: Check if user exists
      shell: /usr/bin/getent group | awk -F":" '{print $1}'
      register: etc_groups

    - name: Add secondary Groups to user
      user: name="{{user}}" groups="{{item}}" append=yes
      when: '"{{item}}" in etc_groups.stdout_lines'
      with_items: 
          - sudo
          - wheel
3 Answers

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

I had the similar requirement, then I did the followings,

ansible [core 2.12.2]

---
- hosts: all
  become: yes
  become_user: root
  tasks:
     - ansible.builtin.user:
         name: test1
         password: "&&**%%^^"
         uid: 1234
         shell: /bin/bash

     - ansible.builtin.shell:
         "cat /etc/group| grep -o sysadmin"
       register: output

#you can omit the debug part
     - debug:
         var: output

     - name: assign user the group
       ansible.builtin.shell:
          "usermod -G sysadmin test1"
       when: "'sysadmin' in output.stdout_lines"

Update: Thanks for the suggestion @Jeter-work

- hosts: localhost
  tasks: 
     - name: Get all groups
       ansible.builtin.getent:
         database: group
         split: ':'
     - debug:
         var: ansible_facts.getent_group  
Related