Debian Codegraph @

ansible_collections/cisco/intersight/plugins/modules/intersight_local_user_policy.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 from __future__ import absolute_import, division, print_function
7 __metaclass__ = type
8
9 ANSIBLE_METADATA = {'metadata_version': '1.1',
10 'status': ['preview'],
11 'supported_by': 'community'}
12
13 DOCUMENTATION = r'''
14 ---
15 module: intersight_local_user_policy
16 short_description: Local User Policy configuration for Cisco Intersight
17 description:
18 - Local User Policy configuration for Cisco Intersight.
19 - Used to configure local users on endpoint devices.
20 - For more information see L(Cisco Intersight,https://intersight.com/apidocs).
21 extends_documentation_fragment: intersight
22 options:
23 state:
24 description:
25 - If C(present), will verify the resource is present and will create if needed.
26 - If C(absent), will verify the resource is absent and will delete if needed.
27 type: str
28 choices: [present, absent]
29 default: present
30 organization:
31 description:
32 - The name of the Organization this resource is assigned to.
33 - Profiles and Policies that are created within a Custom Organization are applicable only to devices in the same Organization.
34 type: str
35 default: default
36 name:
37 description:
38 - The name assigned to the Local User Policy.
39 - The name must be between 1 and 62 alphanumeric characters, allowing special characters :-_.
40 type: str
41 required: true
42 tags:
43 description:
44 - List of tags in Key:<user-defined key> Value:<user-defined value> format.
45 type: list
46 elements: dict
47 description:
48 description:
49 - The user-defined description of the Local User policy.
50 - Description can contain letters(a-z, A-Z), numbers(0-9), hyphen(-), period(.), colon(:), or an underscore(_).
51 type: str
52 aliases: [descr]
53 enforce_strong_password:
54 description:
55 - If true, enables a strong password policy.
56 - Strong password requirements:.
57 - A. The password must have a minimum of 8 and a maximum of 20 characters.
58 - B. The password must not contain the User's Name.
59 - C. The password must contain characters from three of the following four categories.
60 - 1) English uppercase characters (A through Z).
61 - 2) English lowercase characters (a through z).
62 - 3) Base 10 digits (0 through 9).
63 - 4) Non-alphabetic characters (! , @, '#', $, %, ^, &, *, -, _, +, =).
64 type: bool
65 default: true
66 enable_password_expiry:
67 description:
68 - Enables password expiry on the endpoint.
69 type: bool
70 default: false
71 password_history:
72 description:
73 - Specifies number of times a password cannot repeat when changed (value between 0 and 5).
74 - Entering 0 disables this option.
75 type: int
76 default: 5
77 local_users:
78 description:
79 - List of local users on the endpoint.
80 - An admin user already exists on the endpoint.
81 - Add the admin user here only if you want to change the password, or enable or disable the user.
82 - To add admin user, provide a username as 'admin', select the admin user role, and then proceed.
83 type: list
84 elements: dict
85 suboptions:
86 username:
87 description:
88 - Name of the user created on the endpoint.
89 - Cisco Intersight currently limits endpoint usernames to 16 characters.
90 type: str
91 required: true
92 enable:
93 description:
94 - Enable or disable the user.
95 type: bool
96 default: true
97 role:
98 description:
99 - Roles associated with the user on the endpoint.
100 type: str
101 choices: [admin, readonly, user]
102 required: true
103 password:
104 description:
105 - Valid login password of the user.
106 type: str
107 required: true
108 endpoint_role_type:
109 description:
110 - The type of endpoint role to assign to the user.
111 - IMC is the supported server management role type for local user roles.
112 - IPMI access should be expressed through C(account_types) such as C(IPMI).
113 - Supplying C(IPMI) here is rejected by the Intersight API for C(iam.EndPointUserRole).
114 type: str
115 choices: [IMC, IPMI]
116 default: IMC
117 account_types:
118 description:
119 - List of account types to assign to the user.
120 - Supported values are C(IPMI) and C(Local).
121 - For backward compatibility, dictionary entries with C(ObjectType) are still accepted.
122 - When provided, the module maps these values to the corresponding Intersight API object types and does not set any separate
123 - account-type toggle field.
124 - Use this to request IPMI or combined local plus IPMI account access while keeping the endpoint role type at C(IMC).
125 type: list
126 elements: raw
127 purge:
128 description:
129 - The purge argument instructs the module to consider the resource definition absolute.
130 - If true, any previously configured usernames will be removed from the policy with the exception of the `admin` user which cannot be deleted.
131 type: bool
132 default: false
133 always_update_password:
134 description:
135 - Since passwords are not returned by the API and are encrypted on the endpoint, this option will instruct the module when to change the password.
136 - If true, the password for each user will always be updated in the policy.
137 - If false, the password will be updated only if the user is created.
138 type: bool
139 default: false
140 author:
141 - David Soper (@dsoper2)
142 '''
143
144 EXAMPLES = r'''
145 - name: Configure Local User policy
146 intersight_local_user_policy:
147 api_private_key: "{{ api_private_key }}"
148 api_key_id: "{{ api_key_id }}"
149 name: guest-admin
150 tags:
151 - Key: username
152 Value: guest
153 description: User named guest with admin role
154 local_users:
155 - username: guest
156 role: admin
157 password: vault_guest_password
158 - username: reader
159 role: readonly
160 password: vault_reader_password
161
162 - name: Configure Local User policy with IPMI user
163 intersight_local_user_policy:
164 api_private_key: "{{ api_private_key }}"
165 api_key_id: "{{ api_key_id }}"
166 name: ipmi-admin
167 description: User with IPMI account type
168 local_users:
169 - username: ipmi-user
170 role: admin
171 password: vault_ipmi_password
172 account_types:
173 - IPMI
174
175 - name: Configure Local User policy with local and IPMI access
176 intersight_local_user_policy:
177 api_private_key: "{{ api_private_key }}"
178 api_key_id: "{{ api_key_id }}"
179 name: local-ipmi-admin
180 description: User with local and IPMI account types
181 local_users:
182 - username: local-ipmi
183 role: admin
184 password: vault_local_ipmi_password
185 account_types:
186 - Local
187 - IPMI
188
189 - name: Delete Local User policy
190 intersight_local_user_policy:
191 api_private_key: "{{ api_private_key }}"
192 api_key_id: "{{ api_key_id }}"
193 name: guest-admin
194 state: absent
195 '''
196
197 RETURN = r'''
198 api_response:
199 description: The API response output returned by the specified resource.
200 returned: always
201 type: dict
202 sample:
203 "api_response": {
204 "Description": "User named guest with admin role",
205 "EndPointUserRoles": [
206 {
207 "ChangePassword": true,
208 "Enabled": true
209 }
210 ]
211 }
212 '''
213
214
215 from ansible.module_utils.basic import AnsibleModule
216 from ansible_collections.cisco.intersight.plugins.module_utils.intersight import IntersightModule, intersight_argument_spec, compare_values
217
218
219 ACCOUNT_TYPE_MAP = {
220 'IPMI': 'iam.AccountTypeIpmi',
221 'LOCAL': 'iam.AccountTypeLocal',
222 }
223
224
225 def normalize_account_types(module, account_types):
226 normalized_account_types = []
227
228 for account_type in account_types:
229 if isinstance(account_type, str):
230 object_type = ACCOUNT_TYPE_MAP.get(account_type.upper())
231 if not object_type:
232 module.fail_json(
233 msg=(
234 "Unsupported account_type '{0}'. Supported values are: {1}."
235 ).format(account_type, ', '.join(sorted(ACCOUNT_TYPE_MAP.keys())))
236 )
237 normalized_account_types.append({
238 'ObjectType': object_type,
239 'ClassId': object_type,
240 })
241 elif isinstance(account_type, dict):
242 account_type_ref = account_type.copy()
243 object_type = account_type_ref.get('ObjectType')
244 if not object_type:
245 module.fail_json(msg="account_types dict entries must include ObjectType.")
246 if 'ClassId' not in account_type_ref:
247 account_type_ref['ClassId'] = object_type
248 normalized_account_types.append(account_type_ref)
249 else:
250 module.fail_json(msg="account_types entries must be strings like IPMI or Local.")
251
252 return normalized_account_types
253
254
255 def main():
256 local_user = dict(
257 username=dict(type='str', required=True),
258 enable=dict(type='bool', default=True),
259 role=dict(type='str', choices=['admin', 'readonly', 'user'], required=True),
260 password=dict(type='str', required=True, no_log=True),
261 endpoint_role_type=dict(type='str', choices=['IMC', 'IPMI'], default='IMC'),
262 account_types=dict(type='list', elements='raw'),
263 )
264 argument_spec = intersight_argument_spec.copy()
265 argument_spec.update(
266 state=dict(type='str', choices=['present', 'absent'], default='present'),
267 organization=dict(type='str', default='default'),
268 name=dict(type='str', required=True),
269 description=dict(type='str', aliases=['descr']),
270 tags=dict(type='list', elements='dict'),
271 enforce_strong_password=dict(type='bool', default=True, no_log=False),
272 enable_password_expiry=dict(type='bool', default=False, no_log=False),
273 password_history=dict(type='int', default=5, no_log=False),
274 local_users=dict(type='list', elements='dict', options=local_user),
275 purge=dict(type='bool', default=False),
276 always_update_password=dict(type='bool', default=False, no_log=False),
277 )
278
279 module = AnsibleModule(
280 argument_spec,
281 supports_check_mode=True,
282 )
283
284 intersight = IntersightModule(module)
285 organization_moid = None
286 # get Organization Moid
287 intersight.get_resource(
288 resource_path='/organization/Organizations',
289 query_params={
290 '$filter': "Name eq '" + intersight.module.params['organization'] + "'",
291 '$select': 'Moid',
292 },
293 )
294 if intersight.result['api_response'].get('Moid'):
295 # resource exists and moid was returned
296 organization_moid = intersight.result['api_response']['Moid']
297 intersight.result['api_response'] = {}
298 intersight.result['trace_id'] = ''
299
300 # get the current state of the resource
301 filter_str = "Name eq '" + intersight.module.params['name'] + "'"
302 filter_str += "and Organization.Moid eq '" + organization_moid + "'"
303 intersight.get_resource(
304 resource_path='/iam/EndPointUserPolicies',
305 query_params={
306 '$filter': filter_str,
307 '$expand': 'EndPointUserRoles($expand=EndPointRole,EndPointUser),Organization',
308 },
309 )
310
311 if module.params['state'] == 'present':
312 intersight.api_body = {
313 'Name': intersight.module.params['name'],
314 'PasswordProperties': {
315 'EnforceStrongPassword': intersight.module.params['enforce_strong_password'],
316 'EnablePasswordExpiry': intersight.module.params['enable_password_expiry'],
317 'PasswordHistory': intersight.module.params['password_history'],
318 },
319 }
320 intersight.set_tags_and_description()
321
322 user_policy_moid = None
323 resource_values_match = False
324 if intersight.result['api_response'].get('Moid'):
325 # resource exists and moid was returned
326 user_policy_moid = intersight.result['api_response']['Moid']
327 #
328 # always_update_password
329 # false: compare expected vs. actual (won't check passwords)
330 # true: no compare
331 #
332 if module.params['state'] == 'present' and not module.params['always_update_password']:
333 # Create api body used to check current state
334 end_point_user_roles = []
335 for user in intersight.module.params['local_users']:
336 end_point_user_roles.append(
337 {
338 'Enabled': user['enable'],
339 'EndPointRole': [
340 {
341 'Name': user['role'],
342 'Type': user.get('endpoint_role_type', 'IMC'),
343 },
344 ],
345 'EndPointUser': {
346 'Name': user['username'],
347 },
348 }
349 )
350 intersight.api_body['EndPointUserRoles'] = end_point_user_roles
351 intersight.api_body['Organization'] = {
352 'Name': intersight.module.params['organization'],
353 }
354 resource_values_match = compare_values(intersight.api_body, intersight.result['api_response'])
355 elif module.params['state'] == 'absent':
356 intersight.delete_resource(
357 moid=user_policy_moid,
358 resource_path='/iam/EndPointUserPolicies',
359 )
360 user_policy_moid = None
361
362 if module.params['state'] == 'present' and not resource_values_match:
363 intersight.api_body['Organization'] = {
364 'Moid': organization_moid,
365 }
366
367 if module.params['purge']:
368 # update existing resource and purge any existing users
369 if intersight.result['api_response'].get('EndPointUserRoles'):
370 for end_point_user_role in intersight.result['api_response']['EndPointUserRoles']:
371 intersight.delete_resource(
372 moid=end_point_user_role['Moid'],
373 resource_path='/iam/EndPointUserRoles',
374 )
375 # configure the top-level policy resource
376 intersight.result['api_response'] = {}
377 intersight.configure_resource(
378 moid=user_policy_moid,
379 resource_path='/iam/EndPointUserPolicies',
380 body=intersight.api_body,
381 query_params={
382 '$filter': "Name eq '" + intersight.module.params['name'] + "'",
383 },
384 )
385 if intersight.result['api_response'].get('Moid'):
386 # resource exists and moid was returned
387 user_policy_moid = intersight.result['api_response']['Moid']
388
389 # EndPointUser local_users list config
390 for user in intersight.module.params['local_users']:
391 try:
392 if user.get('endpoint_role_type') == 'IPMI':
393 module.fail_json(
394 msg=(
395 "local_users endpoint_role_type=IPMI is not accepted by the Intersight "
396 "iam.EndPointUserRole API. Leave endpoint_role_type at IMC and use "
397 "account_types such as IPMI instead."
398 )
399 )
400 intersight.result['api_response'] = {}
401 # check for existing user in this organization
402 filter_str = "Name eq '" + user['username'] + "'"
403 filter_str += " and Organization.Moid eq '" + organization_moid + "'"
404 intersight.get_resource(
405 resource_path='/iam/EndPointUsers',
406 query_params={
407 '$filter': filter_str
408 },
409 )
410 user_moid = None
411 if intersight.result['api_response'].get('Moid'):
412 # resource exists and moid was returned
413 user_moid = intersight.result['api_response']['Moid']
414 else:
415 # create user if it doesn't exist
416 intersight.api_body = {
417 'Name': user['username'],
418 }
419 if organization_moid:
420 intersight.api_body['Organization'] = {
421 'Moid': organization_moid,
422 }
423 intersight.configure_resource(
424 moid=None,
425 resource_path='/iam/EndPointUsers',
426 body=intersight.api_body,
427 query_params={
428 '$filter': "Name eq '" + user['username'] + "'",
429 },
430 )
431 user_moid = None
432 if intersight.result['api_response'].get('Moid'):
433 # resource exists and moid was returned
434 user_moid = intersight.result['api_response']['Moid']
435 # GET EndPointRole Moid
436 intersight.get_resource(
437 resource_path='/iam/EndPointRoles',
438 query_params={
439 '$filter': "Name eq '" + user['role'] + "' and Type eq '" + user.get('endpoint_role_type', 'IMC') + "'",
440 },
441 )
442 end_point_role_moid = None
443 if intersight.result['api_response'].get('Moid'):
444 # resource exists and moid was returned
445 end_point_role_moid = intersight.result['api_response']['Moid']
446 # Check for any existing EndPointUserRole objects for this policy, then
447 # match by expanded username. Filtering on nested user Moid is not
448 # reliable for this endpoint.
449 filter_str = "EndPointUserPolicy.Moid eq '" + user_policy_moid + "'"
450 intersight.get_resource(
451 resource_path='/iam/EndPointUserRoles',
452 query_params={
453 '$filter': filter_str,
454 '$expand': 'EndPointRole,EndPointUser,EndPointUserPolicy',
455 },
456 return_list=True,
457 )
458 existing_user_roles = intersight.result['api_response']
459 if not isinstance(existing_user_roles, list):
460 existing_user_roles = []
461
462 # EndPointRole relationships are effectively immutable here, so replace any
463 # existing role for this username before creating the desired one.
464 for existing_user_role in existing_user_roles:
465 existing_user = existing_user_role.get('EndPointUser', {})
466 if existing_user.get('Name') == user['username']:
467 intersight.delete_resource(
468 moid=existing_user_role['Moid'],
469 resource_path='/iam/EndPointUserRoles',
470 )
471
472 # Create a new EndPointUserRole with the required relationships.
473 intersight.api_body = {
474 'EndPointUser': {
475 'Moid': user_moid,
476 'ObjectType': 'iam.EndPointUser',
477 },
478 'EndPointRole': [
479 {
480 'Moid': end_point_role_moid,
481 'ObjectType': 'iam.EndPointRole',
482 }
483 ],
484 'Password': user['password'],
485 'Enabled': user['enable'],
486 'EndPointUserPolicy': {
487 'Moid': user_policy_moid,
488 'ObjectType': 'iam.EndPointUserPolicy',
489 },
490 }
491 if user.get('account_types'):
492 intersight.api_body['AccountTypes'] = normalize_account_types(module, user['account_types'])
493 intersight.configure_resource(
494 moid=None,
495 resource_path='/iam/EndPointUserRoles',
496 body=intersight.api_body,
497 query_params={
498 '$filter': filter_str,
499 },
500 )
501 except Exception as exc:
502 module.fail_json(msg="Failed configuring local user '{0}': {1}".format(user['username'], exc))
503
504 module.exit_json(**intersight.result)
505
506
507 if __name__ == '__main__':
508 main()