Debian Codegraph @

ansible_collections/azure/azcollection/plugins/modules/azure_rm_adgroup_info.py

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2021 Cole Neubauer, (@coleneubauer), xuzhang3 (@xuzhang3)
4 #
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8
9 __metaclass__ = type
10
11 DOCUMENTATION = '''
12 module: azure_rm_adgroup_info
13 version_added: "1.6.0"
14 short_description: Get Azure Active Directory group info
15 description:
16 - Get Azure Active Directory group info.
17 options:
18 object_id:
19 description:
20 - The object id for the ad group.
21 - returns the group which has this object ID.
22 type: str
23 attribute_name:
24 description:
25 - The name of an attribute that you want to match to I(attribute_value).
26 - If I(attribute_name) is not a collection type it will return groups where I(attribute_name) is equal to I(attribute_value).
27 - If I(attribute_name) is a collection type it will return groups where I(attribute_value) is in I(attribute_name).
28 type: str
29 attribute_value:
30 description:
31 - The value to match attribute_name to.
32 - If I(attribute_name) is not a collection type it will return groups where I(attribute_name) is equal to I(attribute_value).
33 - If I(attribute_name) is a collection type it will groups users where I(attribute_value) is in I(attribute_name).
34 type: str
35 odata_filter:
36 description:
37 - returns groups based on the the OData filter passed into this parameter.
38 type: str
39 check_membership:
40 description:
41 - The object ID of the contact, group, user, or service principal to check for membership against returned groups.
42 type: str
43 return_owners:
44 description:
45 - Indicate whether the owners of a group should be returned with the returned groups.
46 default: False
47 type: bool
48 return_group_members:
49 description:
50 - Indicate whether the members of a group should be returned with the returned groups.
51 default: False
52 type: bool
53 return_member_groups:
54 description:
55 - Indicate whether the groups in which a groups is a member should be returned with the returned groups.
56 default: False
57 type: bool
58 raw_membership:
59 description:
60 - By default the group_members return property is flattened and partially filtered of non-User objects before return.\
61 This argument disables those transformations.
62 default: false
63 type: bool
64 all:
65 description:
66 - If True, will return all groups in tenant.
67 - If False will return no users.
68 - It is recommended that you instead identify a subset of groups and use filter.
69 default: False
70 type: bool
71 extends_documentation_fragment:
72 - azure.azcollection.azure
73 author:
74 - Cole Neubauer(@coleneubauer)
75 - Xu Zhang(@xuzhang)
76 '''
77
78 EXAMPLES = '''
79 - name: Return a specific group using object_id
80 azure_rm_adgroup_info:
81 object_id: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
82
83 - name: Return a specific group using object_id and return the owners of the group
84 azure_rm_adgroup_info:
85 object_id: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
86 return_owners: true
87
88 - name: Return a specific group using object_id and return the owners and members of the group
89 azure_rm_adgroup_info:
90 object_id: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
91 return_owners: true
92 return_group_members: true
93 - name: Return a specific group using object_id and return the owners and members of the group. Return service principals and nested groups.
94 azure_rm_adgroup_info:
95 object_id: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
96 return_owners: true
97 return_group_members: true
98 raw_membership: true
99
100 - name: Return a specific group using object_id and return the groups the group is a member of
101 azure_rm_adgroup_info:
102 object_id: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
103 return_member_groups: true
104
105 - name: Return a specific group using object_id and check an ID for membership
106 azure_rm_adgroup_info:
107 object_id: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
108 check_membership: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
109
110 - name: Return a specific group using displayName for attribute_name
111 azure_rm_adgroup_info:
112 attribute_name: "displayName"
113 attribute_value: "Display-Name-Of-AD-Group"
114
115 - name: Return groups matching odata_filter
116 azure_rm_adgroup_info:
117 odata_filter: "mailNickname eq 'Mail-Nickname-Of-AD-Group'"
118
119 - name: Return all groups
120 azure_rm_adgroup_info:
121 all: true
122 '''
123
124 RETURN = '''
125 object_id:
126 description:
127 - The object_id for the group.
128 type: str
129 returned: always
130 sample: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
131 display_name:
132 description:
133 - The display name of the group.
134 returned: always
135 type: str
136 sample: GroupName
137 mail_nickname:
138 description:
139 - The mail alias for the group.
140 returned: always
141 type: str
142 sample: groupname
143 mail_enabled:
144 description:
145 - Whether the group is mail-enabled. Must be false. This is because only pure security groups can be created using the Graph API.
146 returned: always
147 type: bool
148 sample: False
149 security_enabled:
150 description:
151 - Whether the group is security-enable.
152 returned: always
153 type: bool
154 sample: False
155 mail:
156 description:
157 - The primary email address of the group.
158 returned: always
159 type: str
160 sample: [email protected]
161 group_owners:
162 description:
163 - The owners of the group.
164 returned: always
165 type: list
166 group_members:
167 description:
168 - The members of the group. If raw_membership is set, this field may contain non-user objects (groups, service principals, etc)
169 returned: always
170 type: list
171 description:
172 description:
173 - An optional description for the group.
174 type: str
175 returned: always
176 sample: 'fortest'
177 '''
178
179 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common_ext import AzureRMModuleBase
180
181 try:
182 import asyncio
183 from msgraph.generated.groups.groups_request_builder import GroupsRequestBuilder
184 from msgraph.generated.groups.item.transitive_members.transitive_members_request_builder import \
185 TransitiveMembersRequestBuilder
186 from msgraph.generated.groups.item.get_member_groups.get_member_groups_post_request_body import \
187 GetMemberGroupsPostRequestBody
188 from msgraph.generated.groups.item.group_item_request_builder import GroupItemRequestBuilder
189 except ImportError:
190 # This is handled in azure_rm_common
191 pass
192
193
194 class AzureRMADGroupInfo(AzureRMModuleBase):
195 def __init__(self):
196
197 self.module_arg_spec = dict(
198 object_id=dict(type='str'),
199 attribute_name=dict(type='str'),
200 attribute_value=dict(type='str'),
201 odata_filter=dict(type='str'),
202 check_membership=dict(type='str'),
203 return_owners=dict(type='bool', default=False),
204 return_group_members=dict(type='bool', default=False),
205 return_member_groups=dict(type='bool', default=False),
206 raw_membership=dict(type='bool', default=False),
207 all=dict(type='bool', default=False),
208 )
209
210 self.object_id = None
211 self.attribute_name = None
212 self.attribute_value = None
213 self.odata_filter = None
214 self.check_membership = None
215 self.return_owners = False
216 self.return_group_members = False
217 self.return_member_groups = False
218 self.raw_membership = False
219 self.all = False
220
221 self.results = dict(changed=False)
222 self._client = None
223
224 mutually_exclusive = [['odata_filter', 'attribute_name', 'object_id', 'all']]
225 required_together = [['attribute_name', 'attribute_value']]
226 required_one_of = [['odata_filter', 'attribute_name', 'object_id', 'all']]
227
228 super(AzureRMADGroupInfo, self).__init__(derived_arg_spec=self.module_arg_spec,
229 supports_check_mode=True,
230 supports_tags=False,
231 mutually_exclusive=mutually_exclusive,
232 required_together=required_together,
233 required_one_of=required_one_of,
234 is_ad_resource=True)
235
236 def exec_module(self, **kwargs):
237
238 for key in list(self.module_arg_spec.keys()):
239 setattr(self, key, kwargs[key])
240
241 ad_groups = []
242
243 try:
244 self._client = self.get_msgraph_client()
245
246 if self.object_id is not None:
247 ad_groups = [asyncio.get_event_loop().run_until_complete(self.get_group(self.object_id))]
248 elif self.attribute_name is not None and self.attribute_value is not None:
249 ad_groups = asyncio.get_event_loop().run_until_complete(
250 self.get_group_list(filter="{0} eq '{1}'".format(self.attribute_name, self.attribute_value)))
251 elif self.odata_filter is not None: # run a filter based on user input
252 ad_groups = asyncio.get_event_loop().run_until_complete(self.get_group_list(filter=self.odata_filter))
253 elif self.all:
254 ad_groups = asyncio.get_event_loop().run_until_complete(self.get_group_list())
255 self.results['ad_groups'] = [self.set_results(group) for group in ad_groups]
256 except Exception as e:
257 self.fail("failed to get ad group info {0}".format(str(e)))
258
259 return self.results
260
261 def application_to_dict(self, object):
262 return dict(
263 app_id=object.app_id,
264 object_id=object.object_id,
265 display_name=object.display_name,
266 )
267
268 def serviceprincipal_to_dict(self, object):
269 return dict(
270 app_id=object.app_id,
271 object_id=object.id,
272 app_display_name=object.display_name,
273 app_role_assignment_required=object.app_role_assignment_required
274 )
275
276 def group_to_dict(self, object):
277 return dict(
278 object_id=object.id,
279 display_name=object.display_name,
280 mail_nickname=object.mail_nickname,
281 mail_enabled=object.mail_enabled,
282 security_enabled=object.security_enabled,
283 mail=object.mail,
284 description=object.description
285 )
286
287 def user_to_dict(self, object):
288 return dict(
289 object_id=object.id,
290 display_name=object.display_name,
291 user_principal_name=object.user_principal_name,
292 mail_nickname=object.mail_nickname,
293 mail=object.mail,
294 account_enabled=object.account_enabled,
295 user_type=object.user_type
296 )
297
298 def result_to_dict(self, object):
299 if object.odata_type == "#microsoft.graph.group":
300 return self.group_to_dict(object)
301 elif object.odata_type == "#microsoft.graph.user":
302 return self.user_to_dict(object)
303 elif object.odata_type == "#microsoft.graph.application":
304 return self.application_to_dict(object)
305 elif object.odata_type == "#microsoft.graph.servicePrincipal":
306 return self.serviceprincipal_to_dict(object)
307 else:
308 return object.odata_type
309
310 def set_results(self, object):
311 results = self.group_to_dict(object)
312
313 if results["object_id"] and self.return_owners:
314 ret = asyncio.get_event_loop().run_until_complete(self.get_group_owners(results["object_id"]))
315 results["group_owners"] = [self.result_to_dict(object) for object in ret]
316
317 if results["object_id"] and self.return_group_members:
318 ret = asyncio.get_event_loop().run_until_complete(self.get_group_members(results["object_id"]))
319 results["group_members"] = [self.result_to_dict(object) for object in ret]
320
321 if results["object_id"] and self.return_member_groups:
322 ret = asyncio.get_event_loop().run_until_complete(self.get_member_groups(results["object_id"]))
323 results["member_groups"] = [self.result_to_dict(object) for object in ret]
324
325 if results["object_id"] and self.check_membership:
326 filter = "id eq '{0}' ".format(self.check_membership)
327 ret = asyncio.get_event_loop().run_until_complete(self.get_group_members(results["object_id"], filter))
328 results["is_member_of"] = True if ret and len(ret) != 0 else False
329
330 return results
331
332 async def get_group(self, group_id):
333 return await self._client.groups.by_group_id(group_id).get()
334
335 async def get_group_list(self, filter=None):
336 kwargs = {}
337 if filter:
338 request_configuration = GroupsRequestBuilder.GroupsRequestBuilderGetRequestConfiguration(
339 query_parameters=GroupsRequestBuilder.GroupsRequestBuilderGetQueryParameters(
340 count=True,
341 filter=filter,
342 ),
343 )
344 kwargs["request_configuration"] = request_configuration
345
346 groups = []
347 # paginated response can be quite large
348 response = await self._client.groups.get(**kwargs)
349 if response:
350 groups += response.value
351 while response is not None and response.odata_next_link is not None:
352 response = await self._client.groups.with_url(response.odata_next_link).get(**kwargs)
353 if response:
354 groups += response.value
355
356 return groups
357
358 async def get_group_owners(self, group_id):
359 request_configuration = GroupsRequestBuilder.GroupsRequestBuilderGetRequestConfiguration(
360 query_parameters=GroupsRequestBuilder.GroupsRequestBuilderGetQueryParameters(
361 count=True,
362 select=['id', 'displayName', 'userPrincipalName', 'mailNickname', 'mail', 'accountEnabled', 'userType',
363 'appId', 'appRoleAssignmentRequired']
364
365 ),
366 )
367 response = await self._client.groups.by_group_id(group_id).owners.get(request_configuration=request_configuration)
368 groups = []
369 if response:
370 groups += response.value
371 while response is not None and response.odata_next_link is not None:
372 response = await self._client.groups.by_group_id(group_id).owners.with_url(response.odata_next_link).get(
373 request_configuration=request_configuration)
374 if response:
375 groups += response.value
376 return groups
377
378 async def get_group_members(self, group_id, filters=None):
379 if self.raw_membership:
380 return await self.get_raw_group_members(group_id, filters)
381 else:
382 return await self.get_transitive_group_members(group_id, filters)
383
384 async def get_transitive_group_members(self, group_id, filters=None):
385 request_configuration = TransitiveMembersRequestBuilder.TransitiveMembersRequestBuilderGetRequestConfiguration(
386 query_parameters=TransitiveMembersRequestBuilder.TransitiveMembersRequestBuilderGetQueryParameters(
387 count=True,
388 ),
389 )
390 if filters:
391 request_configuration.query_parameters.filter = filters
392 try:
393 response = await self._client.groups.by_group_id(group_id).transitive_members.get(
394 request_configuration=request_configuration)
395 groups = []
396
397 if response:
398 groups += response.value
399 while response is not None and response.odata_next_link is not None:
400 response = await self._client.groups.by_group_id(group_id).transitive_members.with_url(response.odata_next_link).get(
401 request_configuration=request_configuration)
402 if response:
403 groups += response.value
404 return groups
405 except Exception:
406 return
407
408 async def get_raw_group_members(self, group_id, filters=None):
409 request_configuration = GroupItemRequestBuilder.GroupItemRequestBuilderGetRequestConfiguration(
410 query_parameters=GroupItemRequestBuilder.GroupItemRequestBuilderGetQueryParameters(
411 # this ensures service principals are returned
412 # see https://learn.microsoft.com/en-us/graph/api/group-list-members?view=graph-rest-1.0&tabs=http
413 # expand=["members"]
414 ),
415 )
416 if filters:
417 request_configuration.query_parameters.filter = filters
418 response = await self._client.groups.by_group_id(group_id).members.get(
419 request_configuration=request_configuration)
420 groups = []
421
422 if response:
423 groups += response.value
424 while response is not None and response.odata_next_link is not None:
425 response = await self._client.groups.by_group_id(group_id).members.with_url(response.odata_next_link).get(
426 request_configuration=request_configuration)
427 if response:
428 groups += response.value
429 return groups
430
431 async def get_member_groups(self, obj_id):
432 request_body = GetMemberGroupsPostRequestBody(security_enabled_only=False)
433 response = await self._client.groups.by_group_id(obj_id).get_member_groups.post(body=request_body)
434 groups = []
435 if response:
436 groups += response.value
437 while response is not None and response.odata_next_link is not None:
438 response = await self._client.groups.by_group_id(obj_id).get_member_groups.with_url(response.odata_next_link).post(
439 body=request_body)
440 if response:
441 groups += response.value
442 return groups
443
444
445 def main():
446 AzureRMADGroupInfo()
447
448
449 if __name__ == '__main__':
450 main()