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 within
operator:If you replace the string
Administrators
with themyGroup
variable, there is no need for the wrapping quotes:An alternative way (a bit less clear than the above), would be to use
selectattr
withsearch
ormatch
filters and check if the resulting list was not empty. The filters would allow for partial matches (search
) or regular expressions (match
). For example: