Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2020 Cole Neubauer, (@coleneubauer)
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_aduser_info
13
14 version_added: "1.4.0"
15
16 short_description: Get Azure Active Directory user info
17
18 description:
19 - Get Azure Active Directory user info.
20
21 options:
22 object_id:
23 description:
24 - The object id for the user.
25 - returns the user who has this object ID.
26 - Mutually exclusive with I(user_principal_name), I(attribute_name), I(odata_filter) and I(all).
27 type: str
28 user_principal_name:
29 description:
30 - The principal name of the user.
31 - returns the user who has this principal name.
32 - Mutually exclusive with I(object_id), I(attribute_name), I(odata_filter) and I(all).
33 type: str
34 attribute_name:
35 description:
36 - The name of an attribute that you want to match to attribute_value.
37 - If I(attribute_name) is not a collection type it will return users where I(attribute_name) is equal to I(attribute_value).
38 - If I(attribute_name) is a collection type it will return users where I(attribute_value) is in I(attribute_name).
39 - Mutually exclusive with I(object_id), I(user_principal_name), I(odata_filter) and I(all).
40 - Required together with I(attribute_value).
41 type: str
42 attribute_value:
43 description:
44 - The value to match attribute_name to.
45 - If I(attribute_name) is not a collection type it will return users where I(attribute_name) is equal to I(attribute_value).
46 - If I(attribute_name) is a collection type it will return users where I(attribute_value) is in I(attribute_name).
47 - Required together with I(attribute_name).
48 type: str
49 odata_filter:
50 description:
51 - Returns users based on the the OData filter passed into this parameter.
52 - Mutually exclusive with I(object_id), I(attribute_name), I(user_principal_name) and I(all).
53 type: str
54 all:
55 description:
56 - If C(True), will return all users in tenant.
57 - If C(False) will return no users.
58 - It is recommended that you instead identify a subset of users and use filter.
59 - Mutually exclusive with I(object_id), I(attribute_name), I(odata_filter) and I(user_principal_name).
60 type: bool
61 extends_documentation_fragment:
62 - azure.azcollection.azure
63
64 author:
65 - Cole Neubauer(@coleneubauer)
66
67 '''
68
69 EXAMPLES = '''
70 - name: Using user_principal_name
71 azure.azcollection.azure_rm_aduser_info:
72 user_principal_name: [email protected]
73
74 - name: Using object_id
75 azure.azcollection.azure_rm_aduser_info:
76 object_id: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
77
78 - name: Using attribute mailNickname - not a collection
79 azure.azcollection.azure_rm_aduser_info:
80 attribute_name: mailNickname
81 attribute_value: users_mailNickname
82
83 - name: Using attribute proxyAddresses - a collection
84 azure.azcollection.azure_rm_aduser_info:
85 attribute_name: proxyAddresses
86 attribute_value: SMTP:[email protected]
87
88 - name: Using Filter mailNickname
89 azure.azcollection.azure_rm_aduser_info:
90 odata_filter: mailNickname eq '[email protected]'
91
92 - name: Using Filter proxyAddresses
93 azure.azcollection.azure_rm_aduser_info:
94 odata_filter: proxyAddresses/any(c:c eq 'SMTP:[email protected]')
95 '''
96
97 RETURN = '''
98 object_id:
99 description:
100 - The object_id for the user.
101 type: str
102 returned: always
103 sample: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
104 display_name:
105 description:
106 - The display name of the user.
107 returned: always
108 type: str
109 sample: John Smith
110 given_name:
111 description:
112 - The given name of the user.
113 returned: always
114 type: str
115 sample: John
116 surname:
117 description:
118 - The surname of the user.
119 returned: always
120 type: str
121 sample: Smith
122 user_principal_name:
123 description:
124 - The principal name of the user.
125 returned: always
126 type: str
127 sample: [email protected]
128 mail_nickname:
129 description:
130 - The mail alias for the user.
131 returned: always
132 type: str
133 sample: jsmith
134 mail:
135 description:
136 - The primary email address of the user.
137 returned: always
138 type: str
139 sample: [email protected]
140 account_enabled:
141 description:
142 - Whether the account is enabled.
143 returned: always
144 type: bool
145 sample: False
146 user_type:
147 description:
148 - A string value that can be used to classify user types in your directory.
149 returned: always
150 type: str
151 sample: Member
152 mobile_phone:
153 description:
154 - The mobile phone number of the user.
155 type: str
156 returned: always
157 sample: '+1234567890123'
158 company_name:
159 description:
160 - The name of the company that the user is associated with.
161 type: str
162 returned: always
163 sample: "Test Company"
164 on_premises_extension_attributes:
165 description:
166 - Contains extensionAttributes1-15 for the user.
167 - These extension attributes are also known as Exchange custom attributes 1-15.
168 - For an onPremisesSyncEnabled user, the source of authority for this set of properties is the on-premises and is read-only.
169 - For a cloud-only user (where onPremisesSyncEnabled is false), these properties can be set during the creation or update of a user object.
170 - For a cloud-only user previously synced from on-premises Active Directory, these properties are read-only in Microsoft Graph/
171 but can be fully managed through the Exchange Admin Center or the Exchange Online V2 module in PowerShell.
172 type: dict
173 returned: always
174 sample: {}
175 '''
176
177 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common_ext import AzureRMModuleBase
178
179 try:
180 import asyncio
181 from msgraph.generated.users.users_request_builder import UsersRequestBuilder
182 except ImportError:
183 # This is handled in azure_rm_common
184 pass
185
186
187 class AzureRMADUserInfo(AzureRMModuleBase):
188 def __init__(self):
189
190 self.module_arg_spec = dict(
191 user_principal_name=dict(type='str'),
192 object_id=dict(type='str'),
193 attribute_name=dict(type='str'),
194 attribute_value=dict(type='str'),
195 odata_filter=dict(type='str'),
196 all=dict(type='bool'),
197 )
198
199 self.user_principal_name = None
200 self.object_id = None
201 self.attribute_name = None
202 self.attribute_value = None
203 self.odata_filter = None
204 self.all = None
205 self.log_path = None
206 self.log_mode = None
207
208 self.results = dict(changed=False)
209
210 mutually_exclusive = [['odata_filter', 'attribute_name', 'object_id', 'user_principal_name', 'all']]
211 required_together = [['attribute_name', 'attribute_value']]
212 required_one_of = [['odata_filter', 'attribute_name', 'object_id', 'user_principal_name', 'all']]
213
214 super(AzureRMADUserInfo, self).__init__(derived_arg_spec=self.module_arg_spec,
215 supports_check_mode=True,
216 supports_tags=False,
217 mutually_exclusive=mutually_exclusive,
218 required_together=required_together,
219 required_one_of=required_one_of,
220 is_ad_resource=True)
221
222 def exec_module(self, **kwargs):
223
224 for key in list(self.module_arg_spec.keys()):
225 setattr(self, key, kwargs[key])
226
227 ad_users = []
228
229 try:
230 self._client = self.get_msgraph_client()
231
232 if self.user_principal_name is not None:
233 ad_users = [asyncio.get_event_loop().run_until_complete(self.get_user(self.user_principal_name))]
234 elif self.object_id is not None:
235 ad_users = [asyncio.get_event_loop().run_until_complete(self.get_user(self.object_id))]
236 elif self.attribute_name is not None and self.attribute_value is not None:
237 try:
238 ad_users = asyncio.get_event_loop().run_until_complete(
239 self.get_users_by_filter("{0} eq '{1}'".format(self.attribute_name, self.attribute_value)))
240 except Exception:
241 # the type doesn't get more specific. Could check the error message but no guarantees that message doesn't change in the future
242 # more stable to try again assuming the first error came from the attribute being a list
243 try:
244 ad_users = asyncio.get_event_loop().run_until_complete(self.get_users_by_filter(
245 "{0}/any(c:c eq '{1}')".format(self.attribute_name, self.attribute_value)))
246 except Exception:
247 raise
248 elif self.odata_filter is not None: # run a filter based on user input to return based on any given attribute/query
249 ad_users = asyncio.get_event_loop().run_until_complete(self.get_users_by_filter(self.odata_filter))
250 elif self.all:
251 # this returns as a list, since we parse multiple pages
252 ad_users = asyncio.get_event_loop().run_until_complete(self.get_users())
253 self.results['ad_users'] = [self.to_dict(user) for user in ad_users]
254
255 except Exception as e:
256 self.fail("failed to get ad user info {0}".format(str(e)))
257
258 return self.results
259
260 def on_premises_extension_attributes_to_dict(self, on_premises_extension_attributes):
261 extension_attributes = {}
262 for index in range(1, 16 + 1):
263 attribute_name = f'extension_attribute{index}'
264 if hasattr(on_premises_extension_attributes, attribute_name):
265 attr_value = getattr(on_premises_extension_attributes, attribute_name)
266 if attr_value is not None:
267 extension_attributes[attribute_name] = attr_value
268 return extension_attributes
269
270 def to_dict(self, object):
271 return dict(
272 object_id=object.id,
273 display_name=object.display_name,
274 user_principal_name=object.user_principal_name,
275 mail_nickname=object.mail_nickname,
276 mail=object.mail,
277 account_enabled=object.account_enabled,
278 user_type=object.user_type,
279 company_name=object.company_name,
280 mobile_phone=object.mobile_phone,
281 surname=object.surname,
282 given_name=object.given_name,
283 on_premises_extension_attributes=self.on_premises_extension_attributes_to_dict(object.on_premises_extension_attributes)
284 )
285
286 async def get_user(self, object):
287 request_configuration = UsersRequestBuilder.UsersRequestBuilderGetRequestConfiguration(
288 query_parameters=UsersRequestBuilder.UsersRequestBuilderGetQueryParameters(
289 select=["accountEnabled", "displayName", "mail", "mailNickname", "id", "userPrincipalName",
290 "userType", "companyName", "mobilePhone", "onPremisesExtensionAttributes", "surname",
291 "givenName"]
292 ),
293 )
294 return await self._client.users.by_user_id(object).get(request_configuration=request_configuration)
295
296 async def get_users(self):
297 request_configuration = UsersRequestBuilder.UsersRequestBuilderGetRequestConfiguration(
298 query_parameters=UsersRequestBuilder.UsersRequestBuilderGetQueryParameters(
299 select=["accountEnabled", "displayName", "mail", "mailNickname", "id", "userPrincipalName",
300 "userType", "companyName", "mobilePhone", "onPremisesExtensionAttributes", "surname",
301 "givenName"]
302 ),
303 )
304 users = []
305 # paginated response can be quite large
306 response = await self._client.users.get(request_configuration=request_configuration)
307 if response:
308 users += response.value
309 while response is not None and response.odata_next_link is not None:
310 response = await self._client.users.with_url(response.odata_next_link).get(request_configuration=request_configuration)
311 if response:
312 users += response.value
313
314 return users
315
316 async def get_users_by_filter(self, filter):
317 request_configuration = UsersRequestBuilder.UsersRequestBuilderGetRequestConfiguration(
318 query_parameters=UsersRequestBuilder.UsersRequestBuilderGetQueryParameters(
319 filter=filter,
320 select=["accountEnabled", "displayName", "mail", "mailNickname", "id", "userPrincipalName",
321 "userType", "companyName", "onPremisesExtensionAttributes", "surname", "givenName"],
322 count=True
323 ),
324 )
325 users = []
326 response = await self._client.users.get(request_configuration=request_configuration)
327
328 if response:
329 users += response.value
330 while response is not None and response.odata_next_link is not None:
331 response = await self._client.users.with_url(response.odata_next_link).get(request_configuration=request_configuration)
332 if response:
333 users += response.value
334
335 return users
336
337
338 def main():
339 AzureRMADUserInfo()
340
341
342 if __name__ == '__main__':
343 main()