Debian Codegraph @

ansible_collections/azure/azcollection/plugins/modules/azure_rm_aduser.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
13
14 version_added: "1.5.0"
15
16 short_description: Modify an Azure Active Directory user
17
18 description:
19 - Create, delete, and update an Azure Active Directory user.
20
21 options:
22 state:
23 description:
24 - State of the ad user. Use C(present) to create or update an ad user and C(absent) to delete an ad user.
25 type: str
26 default: present
27 choices:
28 - absent
29 - present
30 object_id:
31 description:
32 - The object id for the user.
33 - Updates or deletes the user who has this object ID.
34 - Mutually exclusive with I(user_principal_name), I(attribute_name), and I(odata_filter).
35 type: str
36 account_enabled:
37 description:
38 - A boolean determing whether or not the user account is enabled.
39 - Used when either creating or updating a user account.
40 type: bool
41 display_name:
42 description:
43 - The display name of the user.
44 - Used when either creating or updating a user account.
45 type: str
46 given_name:
47 description:
48 - The given name for the user.
49 - Used when either creating or updating a user account.
50 type: str
51 surname:
52 description:
53 - The surname for the user.
54 - Used when either creating or updating a user account.
55 type: str
56 on_premises_immutable_id:
57 description:
58 - The on_premises_immutable_id of the user.
59 - Used when either creating or updating a user account.
60 type: str
61 aliases:
62 - immutable_id
63 mail:
64 description:
65 - The primary email address of the user.
66 - Used when either creating or updating a user account.
67 type: str
68 mobile_phone:
69 description:
70 - Mobile phone number of the user.
71 - Used when either creating or updating a user account.
72 type: str
73 mail_nickname:
74 description:
75 - The mail alias for the user.
76 - Used when either creating or updating a user account.
77 type: str
78 password_profile:
79 description:
80 - The password for the user.
81 - Used when either creating or updating a user account.
82 type: str
83 password_force_change:
84 description:
85 - Whether or not the user will be forced to change their password at next logon.
86 - If unspecified, Azure defaults this to true for new users.
87 - Used when either creating or updating a user account.
88 type: bool
89 password_force_change_mfa:
90 description:
91 - Identical behavior to password_force_change except multi-factor authentication (MFA) must be performed prior to changing the password.
92 - Used when either creating or updating a user account.
93 type: bool
94 usage_location:
95 description:
96 - A two letter country code, ISO standard 3166.
97 - Required for a user that will be assigned licenses due to legal requirement to check for availability of services in countries.
98 - Used when either creating or updating a user account.
99 type: str
100 user_type:
101 description:
102 - A string value that can be used to classify user types in your directory, such as Member and Guest.
103 - Used when either creating or updating a user account.
104 type: str
105 user_principal_name:
106 description:
107 - The principal name of the user.
108 - Creates, updates, or deletes the user who has this principal name.
109 - Mutually exclusive with I(object_id), I(attribute_name), and I(odata_filter).
110 type: str
111 attribute_name:
112 description:
113 - The name of an attribute that you want to match to I(attribute_value).
114 - If I(attribute_name) is not a collection type it will update or delete the user where I(attribute_name) is equal to I(attribute_value).
115 - If I(attribute_name) is a collection type it will update or delete the user where I(attribute_value) is in I(attribute_name).
116 - Mutually exclusive with I(object_id), I(user_principal_name), and I(odata_filter).
117 - Required together with I(attribute_value).
118 type: str
119 attribute_value:
120 description:
121 - The value to match I(attribute_name) to.
122 - If I(attribute_name) is not a collection type it will update or delete the user where I(attribute_name) is equal to I(attribute_value).
123 - If I(attribute_name) is a collection type it will update or delete the user where I(attribute_value) is in I(attribute_name).
124 - Required together with I(attribute_name).
125 type: str
126 odata_filter:
127 description:
128 - Filter that can be used to specify a user to update or delete.
129 - Mutually exclusive with I(object_id), I(attribute_name), and I(user_principal_name).
130 type: str
131 company_name:
132 description:
133 - The name of the company that the user is associated with.
134 - This property can be useful for describing the company that an external user comes from.
135 - The maximum length is 64 characters.Returned only on $select.
136 - Supports $filter (eq, ne, not, ge, le, in, startsWith, and eq on null values).
137 type: str
138 on_premises_extension_attributes:
139 description:
140 - Contains extensionAttributes1-15 for the user.
141 - These extension attributes are also known as Exchange custom attributes 1-15.
142 - For an onPremisesSyncEnabled user, the source of authority for this set of properties is the on-premises and is read-only.
143 - For a cloud-only user (where onPremisesSyncEnabled is false), these properties can be set during the creation or update of a user object.
144 - For a cloud-only user previously synced from on-premises Active Directory, these properties are read-only in Microsoft Graph\
145 but can be fully managed through the Exchange Admin Center or the Exchange Online V2 module in PowerShell.
146 type: dict
147 aliases:
148 - extension_attributes
149
150 extends_documentation_fragment:
151 - azure.azcollection.azure
152
153 author:
154 - Cole Neubauer(@coleneubauer)
155
156 '''
157
158 EXAMPLES = '''
159 - name: Create user
160 azure_rm_aduser:
161 user_principal_name: "{{ user_id }}"
162 state: "present"
163 account_enabled: "True"
164 display_name: "Test_{{ user_principal_name }}_Display_Name"
165 password_profile: "password"
166 mail_nickname: "Test_{{ user_principal_name }}_mail_nickname"
167 on_premises_immutable_id: "{{ object_id }}"
168 given_name: "First"
169 surname: "Last"
170 user_type: "Member"
171 usage_location: "US"
172 mail: "{{ user_principal_name }}@contoso.com"
173 mobile_phone: "+1234567890123"
174 company_name: 'Test Company'
175 on_premises_extension_attributes:
176 extension_attribute1: "test_extension_attribute1"
177 extension_attribute2: "test_extension_attribute2"
178 extension_attribute11: "test_extension_attribute11"
179
180 - name: Update user with new value for account_enabled
181 azure_rm_aduser:
182 user_principal_name: "{{ user_id }}"
183 state: "present"
184 account_enabled: "False"
185
186 - name: Delete user
187 azure_rm_aduser:
188 user_principal_name: "{{ user_id }}"
189 state: "absent"
190 '''
191
192 RETURN = '''
193 object_id:
194 description:
195 - The object_id for the user.
196 type: str
197 returned: always
198 sample: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
199 display_name:
200 description:
201 - The display name of the user.
202 returned: always
203 type: str
204 sample: John Smith
205 user_principal_name:
206 description:
207 - The principal name of the user.
208 returned: always
209 type: str
210 sample: [email protected]
211 mail_nickname:
212 description:
213 - The mail alias for the user.
214 returned: always
215 type: str
216 sample: jsmith
217 mail:
218 description:
219 - The primary email address of the user.
220 returned: always
221 type: str
222 sample: [email protected]
223 account_enabled:
224 description:
225 - Whether the account is enabled.
226 returned: always
227 type: bool
228 sample: False
229 user_type:
230 description:
231 - A string value that can be used to classify user types in your directory.
232 returned: always
233 type: str
234 sample: Member
235 mobile_phone:
236 description:
237 - The mobile phone number of the user.
238 type: str
239 returned: always
240 sample: '+1234567890123'
241 company_name:
242 description:
243 - The name of the company that the user is associated with.
244 type: str
245 returned: always
246 sample: 'Test Company'
247 on_premises_extension_attributes:
248 description:
249 - Contains extensionAttributes1-15 for the user.
250 - These extension attributes are also known as Exchange custom attributes 1-15.
251 - For an onPremisesSyncEnabled user, the source of authority for this set of properties is the on-premises and is read-only.
252 - For a cloud-only user (where onPremisesSyncEnabled is false), these properties can be set during the creation or update of a user object.
253 - For a cloud-only user previously synced from on-premises Active Directory, these properties are read-only in Microsoft Graph\
254 but can be fully managed through the Exchange Admin Center or the Exchange Online V2 module in PowerShell.
255 type: dict
256 returned: always
257 sample: {}
258 '''
259
260 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common_ext import AzureRMModuleBase
261
262 try:
263 import asyncio
264 from msgraph.generated.models.password_profile import PasswordProfile
265 from msgraph.generated.models.on_premises_extension_attributes import OnPremisesExtensionAttributes
266 from msgraph.generated.models.user import User
267 from msgraph.generated.users.users_request_builder import UsersRequestBuilder
268 except ImportError:
269 # This is handled in azure_rm_common
270 pass
271
272
273 class AzureRMADUser(AzureRMModuleBase):
274 def __init__(self):
275
276 self.module_arg_spec = dict(
277 user_principal_name=dict(type='str'),
278 state=dict(type='str', default='present', choices=['present', 'absent']),
279 object_id=dict(type='str'),
280 attribute_name=dict(type='str'),
281 attribute_value=dict(type='str'),
282 odata_filter=dict(type='str'),
283 account_enabled=dict(type='bool'),
284 display_name=dict(type='str'),
285 password_profile=dict(type='str', no_log=True),
286 password_force_change=dict(type='bool', no_log=False),
287 password_force_change_mfa=dict(type='bool', no_log=False),
288 mail_nickname=dict(type='str'),
289 on_premises_immutable_id=dict(type='str', aliases=['immutable_id']),
290 usage_location=dict(type='str'),
291 given_name=dict(type='str'),
292 surname=dict(type='str'),
293 user_type=dict(type='str'),
294 mail=dict(type='str'),
295 company_name=dict(type='str'),
296 mobile_phone=dict(type='str'),
297 on_premises_extension_attributes=dict(type='dict', aliases=['extension_attributes'])
298 )
299
300 self.user_principal_name = None
301 self.state = None
302 self.object_id = None
303 self.attribute_name = None
304 self.attribute_value = None
305 self.odata_filter = None
306 self.account_enabled = None
307 self.display_name = None
308 self.password_profile = None
309 self.password_force_change = None
310 self.password_force_change_mfa = None
311 self.mail_nickname = None
312 self.on_premises_immutable_id = None
313 self.usage_location = None
314 self.given_name = None
315 self.surname = None
316 self.user_type = None
317 self.mail = None
318 self.company_name = None
319 self.mobile_phone = None
320 self.on_premises_extension_attributes = None
321 self.log_path = None
322 self.log_mode = None
323
324 self.results = dict(changed=False)
325
326 mutually_exclusive = [['odata_filter', 'attribute_name', 'object_id', 'user_principal_name']]
327 required_together = [['attribute_name', 'attribute_value']]
328 required_one_of = [['odata_filter', 'attribute_name', 'object_id', 'user_principal_name']]
329
330 super(AzureRMADUser, self).__init__(derived_arg_spec=self.module_arg_spec,
331 supports_check_mode=False,
332 supports_tags=False,
333 mutually_exclusive=mutually_exclusive,
334 required_together=required_together,
335 required_one_of=required_one_of,
336 is_ad_resource=True)
337
338 def exec_module(self, **kwargs):
339
340 for key in list(self.module_arg_spec.keys()):
341 setattr(self, key, kwargs[key])
342
343 try:
344 self._client = self.get_msgraph_client()
345
346 ad_user = self.get_exisiting_user()
347
348 if self.state == 'present':
349
350 extension_attributes = None
351
352 if self.on_premises_extension_attributes:
353 extension_attributes = OnPremisesExtensionAttributes(
354 **self.on_premises_extension_attributes
355 )
356
357 if ad_user: # Update, changed
358
359 password_profile = PasswordProfile(
360 password=self.password_profile,
361 force_change_password_next_sign_in=self.password_force_change,
362 force_change_password_next_sign_in_with_mfa=self.password_force_change_mfa
363 )
364
365 should_update = False
366 if self.on_premises_immutable_id and ad_user.on_premises_immutable_id != self.on_premises_immutable_id:
367 should_update = True
368 if should_update or self.usage_location and ad_user.usage_location != self.usage_location:
369 should_update = True
370 if should_update or self.given_name and ad_user.given_name != self.given_name:
371 should_update = True
372 if should_update or self.surname and ad_user.surname != self.surname:
373 should_update = True
374 if should_update or self.user_type and ad_user.user_type != self.user_type:
375 should_update = True
376 if should_update or self.account_enabled is not None and ad_user.account_enabled != self.account_enabled:
377 should_update = True
378 if should_update or self.display_name and ad_user.display_name != self.display_name:
379 should_update = True
380 if should_update or self.password_profile is not None:
381 should_update = True
382 if should_update or self.password_force_change is not None:
383 should_update = True
384 if should_update or self.password_force_change_mfa is not None:
385 should_update = True
386 if should_update or self.user_principal_name and ad_user.user_principal_name != self.user_principal_name:
387 should_update = True
388 if should_update or self.mail_nickname and ad_user.mail_nickname != self.mail_nickname:
389 should_update = True
390 if should_update or self.mobile_phone and ad_user.mobile_phone != self.mobile_phone:
391 should_update = True
392 if should_update or self.company_name and ad_user.company_name != self.company_name:
393 should_update = True
394 if should_update or (
395 self.on_premises_extension_attributes and
396 self.on_premises_extension_attributes_to_dict(ad_user.on_premises_extension_attributes) != self.on_premises_extension_attributes):
397 should_update = True
398 if should_update:
399 asyncio.get_event_loop().run_until_complete(self.update_user(ad_user, password_profile, extension_attributes))
400
401 self.results['changed'] = True
402
403 # Get the updated versions of the users to return
404 # the update method, has no return value so it needs to be explicitely returned in a call
405 ad_user = self.get_exisiting_user()
406
407 else:
408 self.results['changed'] = False
409
410 else: # Create, changed
411 asyncio.get_event_loop().run_until_complete(self.create_user(extension_attributes))
412 self.results['changed'] = True
413 ad_user = self.get_exisiting_user()
414
415 self.results['ad_user'] = self.to_dict(ad_user)
416
417 elif self.state == 'absent':
418 if ad_user: # Delete, changed
419 asyncio.get_event_loop().run_until_complete(self.delete_user(ad_user))
420 self.results['changed'] = True
421 else: # Do nothing unchanged
422 self.results['changed'] = False
423
424 except Exception as e:
425 self.fail("failed to get ad user info {0}".format(str(e)))
426
427 return self.results
428
429 def get_exisiting_user(self):
430 ad_user = None
431
432 try:
433 if self.user_principal_name is not None:
434 ad_user = asyncio.get_event_loop().run_until_complete(self.get_user(self.user_principal_name))
435 elif self.object_id is not None:
436 ad_user = asyncio.get_event_loop().run_until_complete(self.get_user(self.object_id))
437 elif self.attribute_name is not None and self.attribute_value is not None:
438 try:
439 users = asyncio.get_event_loop().run_until_complete(
440 self.get_users_by_filter("{0} eq '{1}'".format(self.attribute_name, self.attribute_value)))
441 ad_users = list(users.value)
442 ad_user = ad_users[0]
443 except Exception as e:
444 # the type doesn't get more specific. Could check the error message but no guarantees that message doesn't change in the future
445 # more stable to try again assuming the first error came from the attribute being a list
446 try:
447 users = asyncio.get_event_loop().run_until_complete(self.get_users_by_filter(
448 "{0}/any(c:c eq '{1}')".format(self.attribute_name, self.attribute_value)))
449 ad_users = list(users.value)
450 ad_user = ad_users[0]
451 except Exception as sub_e:
452 raise
453 elif self.odata_filter is not None: # run a filter based on user input to return based on any given attribute/query
454 users = asyncio.get_event_loop().run_until_complete(self.get_users_by_filter(self.odata_filter))
455 ad_users = list(users.value)
456 ad_user = ad_users[0]
457 except Exception as e:
458 # User was not found
459 err_msg = str(e)
460 if "Resource '{0}' does not exist or one of its queried reference-property objects are not present.".format(
461 self.user_principal_name) in err_msg:
462 ad_user = None
463 else:
464 raise
465 return ad_user
466
467 def on_premises_extension_attributes_to_dict(self, on_premises_extension_attributes):
468 extension_attributes = {}
469 for index in range(1, 16 + 1):
470 attribute_name = f'extension_attribute{index}'
471 if hasattr(on_premises_extension_attributes, attribute_name):
472 attr_value = getattr(on_premises_extension_attributes, attribute_name)
473 if attr_value is not None:
474 extension_attributes[attribute_name] = attr_value
475 return extension_attributes
476
477 def to_dict(self, object):
478 return dict(
479 object_id=object.id,
480 display_name=object.display_name,
481 user_principal_name=object.user_principal_name,
482 mail_nickname=object.mail_nickname,
483 mail=object.mail,
484 account_enabled=object.account_enabled,
485 user_type=object.user_type,
486 company_name=object.company_name,
487 mobile_phone=object.mobile_phone,
488 on_premises_extension_attributes=self.on_premises_extension_attributes_to_dict(object.on_premises_extension_attributes)
489 )
490
491 async def update_user(self, ad_user, password_profile, extension_attributes):
492 request_body = User(
493 on_premises_immutable_id=self.on_premises_immutable_id,
494 usage_location=self.usage_location,
495 given_name=self.given_name,
496 surname=self.surname,
497 user_type=self.user_type,
498 account_enabled=self.account_enabled,
499 display_name=self.display_name,
500 password_profile=password_profile,
501 user_principal_name=self.user_principal_name,
502 mail_nickname=self.mail_nickname,
503 company_name=self.company_name,
504 mobile_phone=self.mobile_phone,
505 on_premises_extension_attributes=extension_attributes
506 )
507 return await self._client.users.by_user_id(ad_user.id).patch(body=request_body)
508
509 async def create_user(self, extension_attributes):
510 password_profile = PasswordProfile(
511 password=self.password_profile,
512 force_change_password_next_sign_in=self.password_force_change,
513 force_change_password_next_sign_in_with_mfa=self.password_force_change_mfa
514 )
515 request_body = User(
516 account_enabled=self.account_enabled,
517 display_name=self.display_name,
518 password_profile=password_profile,
519 user_principal_name=self.user_principal_name,
520 mail_nickname=self.mail_nickname,
521 on_premises_immutable_id=self.on_premises_immutable_id,
522 usage_location=self.usage_location,
523 given_name=self.given_name,
524 surname=self.surname,
525 user_type=self.user_type,
526 mail=self.mail,
527 company_name=self.company_name,
528 mobile_phone=self.mobile_phone,
529 on_premises_extension_attributes=extension_attributes
530 )
531 return await self._client.users.post(body=request_body)
532
533 async def delete_user(self, ad_user):
534 return await self._client.users.by_user_id(ad_user.id).delete()
535
536 async def get_user(self, object):
537 request_configuration = UsersRequestBuilder.UsersRequestBuilderGetRequestConfiguration(
538 query_parameters=UsersRequestBuilder.UsersRequestBuilderGetQueryParameters(
539 select=["accountEnabled", "displayName", "mail", "mailNickname", "id", "userPrincipalName", "userType",
540 "onPremisesImmutableId", "usageLocation", "givenName", "surname", "companyName", "mobilePhone",
541 "OnPremisesExtensionAttributes"]
542 ),
543 )
544 return await self._client.users.by_user_id(object).get(request_configuration=request_configuration)
545
546 async def get_users_by_filter(self, filter):
547 return await self._client.users.get(
548 request_configuration=UsersRequestBuilder.UsersRequestBuilderGetRequestConfiguration(
549 query_parameters=UsersRequestBuilder.UsersRequestBuilderGetQueryParameters(
550 filter=filter,
551 select=["accountEnabled", "displayName", "mail", "mailNickname", "id", "userPrincipalName",
552 "userType", "onPremisesImmutableId", "usageLocation", "givenName", "surname", "companyName", "mobilePhone",
553 "OnPremisesExtensionAttributes"],
554 count=True
555 ),
556 headers={'ConsistencyLevel': "eventual", }
557 )
558 )
559
560
561 def main():
562 AzureRMADUser()
563
564
565 if __name__ == '__main__':
566 main()