Windows – Ansible for Windows: test group membership

ansiblewindows

Using Ansible 2.2.1, I need to test group membership for a given user.

  - name : get users details
    win_user:
      name: "{{ myUser }}"
      state: query
    register: userData

  - debug:
      msg: "userData.groups : {{ userData.groups }}"

Now I'd like to test whether or not myUser belongs to "myGroup" (with myGroup="Administrators" for instance) within a when condition.
The userData.groups is:

ok: [test-machine] => { "msg": "userData.groups : [{u'path': u'WinNT://WORKGROUP/TEST-MACHINE/Administrators', u'name': u'Administrators'}, {u'path': u'WinNT://WORKGROUP/TEST-MACHINE/Performance Monitor Users', u'name': u'Performance Monitor Users'}]"}

So here we see that my user belongs to two groups: "Administrators" and "Performance Monitor Users".

How to write a when statement to test if the user belongs to a particular group?

I've tried some combinations of with_elements, with_dict without success so far.

Best Answer

You can use map filter to extract a list of groups for the account and test the membership with in operator:

- debug:
    msg: "membership confirmed"
  when: "'Administrators' in (userData.groups | map(attribute='name') | list)"

If you replace the string Administrators with the myGroup variable, there is no need for the wrapping quotes:

- debug:
    msg: "membership confirmed"
  when: myGroup in (userData.groups | map(attribute='name') | list)
  vars:
    myGroup: Administrators

An alternative way (a bit less clear than the above), would be to use selectattr with search or match filters and check if the resulting list was not empty. The filters would allow for partial matches (search) or regular expressions (match). For example:

- debug:
    msg: "membership confirmed"
  when: userData.groups | selectattr('name', 'matches', 'Dom.*Adm.*') | list | length > 0