Debian Codegraph @

ansible_collections/netapp/ontap/plugins/modules/na_ontap_user.py

raw
1 #!/usr/bin/python
2
3 # (c) 2018-2025, NetApp, Inc
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 '''
7 na_ontap_user
8 '''
9
10 from __future__ import absolute_import, division, print_function
11 __metaclass__ = type
12
13
14 DOCUMENTATION = '''
15
16 module: na_ontap_user
17
18 short_description: NetApp ONTAP user configuration and management
19 extends_documentation_fragment:
20 - netapp.ontap.netapp.na_ontap
21 version_added: 2.6.0
22 author: NetApp Ansible Team (@carchi8py) <[email protected]>
23
24 description:
25 - Create or destroy users.
26
27 options:
28 state:
29 description:
30 - Whether the specified user should exist or not.
31 choices: ['present', 'absent']
32 type: str
33 default: 'present'
34 name:
35 description:
36 - The name of the user to manage.
37 required: true
38 type: str
39 application_strs:
40 version_added: 21.6.0
41 description:
42 - List of applications to grant access to.
43 - This option maintains backward compatibility with the existing C(applications) option, but is limited.
44 - It is recommended to use the new C(application_dicts) option which provides more flexibility.
45 - Creating a login with application console, telnet, rsh, and service-processor for a data vserver is not supported.
46 - Module supports both service-processor and service_processor choices.
47 - ZAPI requires service-processor, while REST requires service_processor, except for an issue with ONTAP 9.6 and 9.7.
48 - snmp is not supported in REST.
49 - Either C(application_dicts) or C(application_strs) is required.
50 type: list
51 elements: str
52 choices: ['console', 'http','ontapi','rsh','snmp','service_processor','service-processor','sp','ssh','telnet']
53 aliases:
54 - application
55 - applications
56 application_dicts:
57 version_added: 21.6.0
58 description:
59 - List of applications to grant access to. Provides better control on applications and authentication methods.
60 - Creating a login with application console, telnet, rsh, and service-processor for a data vserver is not supported.
61 - Module supports both service-processor and service_processor choices.
62 - ZAPI requires service-processor, while REST requires service_processor, except for an issue with ONTAP 9.6 and 9.7.
63 - snmp is not supported in REST.
64 - Either C(application_dicts) or C(application_strs) is required.
65 type: list
66 elements: dict
67 suboptions:
68 application:
69 description: name of the application.
70 type: str
71 choices: ['console', 'http','ontapi','rsh','snmp','service_processor','service-processor','sp','ssh','telnet']
72 required: true
73 authentication_methods:
74 description: list of authentication methods for the application (see C(authentication_method)).
75 type: list
76 elements: str
77 choices: ['community', 'password', 'publickey', 'domain', 'nsswitch', 'usm', 'cert', 'saml']
78 required: true
79 second_authentication_method:
80 description: when using ssh, optional additional authentication method for MFA.
81 type: str
82 choices: ['none', 'password', 'publickey', 'nsswitch', 'totp']
83 authentication_method:
84 description:
85 - Authentication method for the application. If you need more than one method, use C(application_dicts).
86 - Not all authentication methods are valid for an application.
87 - Valid authentication methods for each application are as denoted in I(authentication_choices_description).
88 - Password for console application
89 - Password, domain, nsswitch, cert, saml for http application.
90 - Password, domain, nsswitch, cert, saml for ontapi application.
91 - SAML is only supported with REST, but seems to work with ZAPI as well.
92 - Community for snmp application (when creating SNMPv1 and SNMPv2 users).
93 - The usm and community for snmp application (when creating SNMPv3 users).
94 - Password for sp application.
95 - Password for rsh application.
96 - Password for telnet application.
97 - Password, publickey, domain, nsswitch for ssh application.
98 - Required when C(application_strs) is present.
99 type: str
100 choices: ['community', 'password', 'publickey', 'domain', 'nsswitch', 'usm', 'cert', 'saml']
101 set_password:
102 description:
103 - Password for the user account.
104 - It is ignored for creating snmp users, but is required for creating non-snmp users.
105 - For an existing user, this value will be used as the new password.
106 type: str
107 role_name:
108 description:
109 - The name of the role. Required when C(state=present)
110 type: str
111 lock_user:
112 description:
113 - Whether the specified user account is locked.
114 type: bool
115 vserver:
116 description:
117 - The name of the vserver to use.
118 - Required with ZAPI.
119 - With REST, ignore this option for creating cluster scoped user account.
120 aliases:
121 - svm
122 type: str
123 authentication_protocol:
124 description:
125 - Authentication protocol for the snmp user.
126 - When cluster FIPS mode is on, 'sha' and 'sha2-256' are the only possible and valid values.
127 - When cluster FIPS mode is off, the default value is 'none'.
128 - When cluster FIPS mode is on, the default value is 'sha'.
129 - Only available for 'usm' authentication method and non modifiable.
130 choices: ['none', 'md5', 'sha', 'sha2-256']
131 type: str
132 version_added: '20.6.0'
133 authentication_password:
134 description:
135 - Password for the authentication protocol. This should be minimum 8 characters long.
136 - This is required for 'md5', 'sha' and 'sha2-256' authentication protocols and not required for 'none'.
137 - Only available for 'usm' authentication method and non modifiable.
138 type: str
139 version_added: '20.6.0'
140 engine_id:
141 description:
142 - Authoritative entity's EngineID for the SNMPv3 user.
143 - This should be specified as a hexadecimal string.
144 - Engine ID with first bit set to 1 in first octet should have a minimum of 5 or maximum of 32 octets.
145 - Engine Id with first bit set to 0 in the first octet should be 12 octets in length.
146 - Engine Id cannot have all zeros in its address.
147 - Only available for 'usm' authentication method and non modifiable.
148 type: str
149 version_added: '20.6.0'
150 privacy_protocol:
151 description:
152 - Privacy protocol for the snmp user.
153 - When cluster FIPS mode is on, 'aes128' is the only possible and valid value.
154 - When cluster FIPS mode is off, the default value is 'none'. When cluster FIPS mode is on, the default value is 'aes128'.
155 - Only available for 'usm' authentication method and non modifiable.
156 choices: ['none', 'des', 'aes128']
157 type: str
158 version_added: '20.6.0'
159 privacy_password:
160 description:
161 - Password for the privacy protocol. This should be minimum 8 characters long.
162 - This is required for 'des' and 'aes128' privacy protocols and not required for 'none'.
163 - Only available for 'usm' authentication method and non modifiable.
164 type: str
165 version_added: '20.6.0'
166 remote_switch_ipaddress:
167 description:
168 - This optionally specifies the IP Address of the remote switch.
169 - The remote switch could be a cluster switch monitored by Cluster Switch Health Monitor (CSHM)
170 or a Fiber Channel (FC) switch monitored by Metro Cluster Health Monitor (MCC-HM).
171 - This is applicable only for a remote SNMPv3 user i.e. only if user is a remote (non-local) user,
172 application is snmp and authentication method is usm.
173 type: str
174 version_added: '20.6.0'
175 replace_existing_apps_and_methods:
176 description:
177 - If the user already exists, the current applications and authentications methods are replaced when state=present.
178 - If the user already exists, the current applications and authentications methods are removed when state=absent.
179 - When using application_dicts or REST, this the only supported behavior.
180 - When using application_strs and ZAPI, this is the behavior when this option is set to always.
181 - When using application_strs and ZAPI, if the option is set to auto, applications that are not listed are not removed.
182 - When using application_strs and ZAPI, if the option is set to auto, authentication mehods that are not listed are not removed.
183 - C(auto) preserve the existing behavior for backward compatibility, but note that REST and ZAPI have inconsistent behavior.
184 - This is another reason to recommend to use C(application_dicts).
185 type: str
186 choices: ['always', 'auto']
187 default: 'auto'
188 version_added: '20.6.0'
189 '''
190
191 EXAMPLES = """
192 - name: Create User
193 netapp.ontap.na_ontap_user:
194 state: present
195 name: SampleUser
196 applications: ssh,console
197 authentication_method: password
198 set_password: apn1242183u1298u41
199 lock_user: true
200 role_name: vsadmin
201 vserver: ansibleVServer
202 hostname: "{{ netapp_hostname }}"
203 username: "{{ netapp_username }}"
204 password: "{{ netapp_password }}"
205
206 - name: Create cluster scoped user in REST.
207 netapp.ontap.na_ontap_user:
208 state: present
209 name: SampleUser
210 applications: ssh,console
211 authentication_method: password
212 set_password: apn1242183u1298u41
213 lock_user: true
214 role_name: admin
215 hostname: "{{ netapp_hostname }}"
216 username: "{{ netapp_username }}"
217 password: "{{ netapp_password }}"
218
219 - name: Delete User
220 netapp.ontap.na_ontap_user:
221 state: absent
222 name: SampleUser
223 applications: ssh
224 authentication_method: password
225 vserver: ansibleVServer
226 hostname: "{{ netapp_hostname }}"
227 username: "{{ netapp_username }}"
228 password: "{{ netapp_password }}"
229
230 - name: Create user with snmp application (ZAPI)
231 netapp.ontap.na_ontap_user:
232 state: present
233 name: test_cert_snmp
234 applications: snmp
235 authentication_method: usm
236 role_name: admin
237 authentication_protocol: md5
238 authentication_password: '12345678'
239 privacy_protocol: 'aes128'
240 privacy_password: '12345678'
241 engine_id: '7063514941000000000000'
242 remote_switch_ipaddress: 10.0.0.0
243 vserver: "{{ vserver }}"
244 hostname: "{{ netapp_hostname }}"
245 username: "{{ netapp_username }}"
246 password: "{{ netapp_password }}"
247
248 - name: Create user
249 netapp.ontap.na_ontap_user:
250 state: present
251 name: test123
252 application_dicts:
253 - application: http
254 authentication_methods: password
255 - application: ssh
256 authentication_methods: password,publickey
257 role_name: vsadmin
258 set_password: bobdole1234566
259 vserver: "{{ vserver }}"
260 hostname: "{{ netapp_hostname }}"
261 username: "{{ netapp_username }}"
262 password: "{{ netapp_password }}"
263 """
264
265 RETURN = """
266
267 """
268 import traceback
269
270 from ansible.module_utils.basic import AnsibleModule
271 from ansible.module_utils._text import to_native
272 import ansible_collections.netapp.ontap.plugins.module_utils.netapp as netapp_utils
273 from ansible_collections.netapp.ontap.plugins.module_utils.netapp_module import NetAppModule
274
275
276 class NetAppOntapUser:
277 """
278 Common operations to manage users and roles.
279 """
280
281 def __init__(self):
282 self.use_rest = False
283 self.argument_spec = netapp_utils.na_ontap_host_argument_spec()
284 self.argument_spec.update(dict(
285 state=dict(type='str', choices=['present', 'absent'], default='present'),
286 name=dict(required=True, type='str'),
287
288 application_strs=dict(type='list', elements='str', aliases=['application', 'applications'],
289 choices=['console', 'http', 'ontapi', 'rsh', 'snmp',
290 'sp', 'service-processor', 'service_processor', 'ssh', 'telnet'],),
291 application_dicts=dict(type='list', elements='dict',
292 options=dict(
293 application=dict(required=True, type='str',
294 choices=['console', 'http', 'ontapi', 'rsh', 'snmp',
295 'sp', 'service-processor', 'service_processor', 'ssh', 'telnet'],),
296 authentication_methods=dict(required=True, type='list', elements='str',
297 choices=['community', 'password', 'publickey', 'domain', 'nsswitch', 'usm', 'cert', 'saml']),
298 second_authentication_method=dict(type='str', choices=['none', 'password', 'publickey', 'nsswitch', 'totp']))),
299 authentication_method=dict(type='str',
300 choices=['community', 'password', 'publickey', 'domain', 'nsswitch', 'usm', 'cert', 'saml']),
301 set_password=dict(type='str', no_log=True),
302 role_name=dict(type='str'),
303 lock_user=dict(type='bool'),
304 vserver=dict(type='str', aliases=['svm']),
305 authentication_protocol=dict(type='str', choices=['none', 'md5', 'sha', 'sha2-256']),
306 authentication_password=dict(type='str', no_log=True),
307 engine_id=dict(type='str'),
308 privacy_protocol=dict(type='str', choices=['none', 'des', 'aes128']),
309 privacy_password=dict(type='str', no_log=True),
310 remote_switch_ipaddress=dict(type='str'),
311 replace_existing_apps_and_methods=dict(type='str', choices=['always', 'auto'], default='auto')
312 ))
313
314 self.module = AnsibleModule(
315 argument_spec=self.argument_spec,
316 mutually_exclusive=[
317 ('application_strs', 'application_dicts')
318 ],
319 required_together=[
320 ('application_strs', 'authentication_method')
321 ],
322 supports_check_mode=True
323 )
324
325 self.na_helper = NetAppModule()
326 self.parameters = self.na_helper.set_parameters(self.module.params)
327 self.strs_to_dicts()
328
329 # REST API should be used for ONTAP 9.6 or higher
330 self.rest_api = netapp_utils.OntapRestAPI(self.module)
331 # some attributes are not supported in earlier REST implementation
332 unsupported_rest_properties = ['authentication_password', 'authentication_protocol', 'engine_id',
333 'privacy_password', 'privacy_protocol']
334 self.use_rest = self.rest_api.is_rest_supported_properties(self.parameters, unsupported_rest_properties)
335 if not self.use_rest:
336 if self.parameters.get('vserver') is None:
337 self.module.fail_json(msg="Error: vserver is required with ZAPI")
338 if not netapp_utils.has_netapp_lib():
339 self.module.fail_json(msg=netapp_utils.netapp_lib_is_required())
340 self.server = netapp_utils.setup_na_ontap_zapi(module=self.module, vserver=self.parameters['vserver'])
341 self.validate_applications()
342
343 def validate_applications(self):
344 if not self.use_rest:
345 if self.parameters['applications'] is None:
346 self.module.fail_json(msg="application_dicts or application_strs is a required parameter with ZAPI")
347 for application in self.parameters['applications']:
348 if application['application'] == 'service_processor':
349 application['application'] = 'service-processor'
350 if self.parameters['applications'] is None:
351 return
352 application_keys = []
353 for application in self.parameters['applications']:
354 # make sure app entries are not duplicated
355 application_name = application['application']
356 if application_name in application_keys:
357 self.module.fail_json(msg='Error: repeated application name: %s. Group all authentication methods under a single entry.' % application_name)
358 application_keys.append(application_name)
359 if self.use_rest:
360 if application_name == 'snmp':
361 self.module.fail_json(msg="snmp as application is not supported in REST.")
362 # REST prefers certificate to cert
363 application['authentication_methods'] = ['certificate' if x == 'cert' else x for x in application['authentication_methods']]
364 # REST get always returns 'second_authentication_method'
365 if 'second_authentication_method' not in application:
366 application['second_authentication_method'] = None
367
368 def strs_to_dicts(self):
369 """transform applications list of strs to a list of dicts if application_strs in use"""
370 if 'application_dicts' in self.parameters:
371 for application in self.parameters['application_dicts']:
372 # keep them sorted for comparison with current
373 application['authentication_methods'].sort()
374 self.parameters['applications'] = self.parameters['application_dicts']
375 self.parameters['replace_existing_apps_and_methods'] = 'always'
376 elif 'application_strs' in self.parameters:
377 # actual conversion
378 self.parameters['applications'] = [
379 dict(application=application,
380 authentication_methods=[self.parameters['authentication_method']],
381 second_authentication_method=None
382 ) for application in self.parameters['application_strs']]
383 else:
384 self.parameters['applications'] = None
385
386 def get_user_rest(self):
387 api = 'security/accounts'
388 query = {
389 'name': self.parameters['name']
390 }
391 if self.parameters.get('vserver') is None:
392 # vserser is empty for cluster
393 query['scope'] = 'cluster'
394 else:
395 query['owner.name'] = self.parameters['vserver']
396
397 message, error = self.rest_api.get(api, query)
398 if error:
399 self.module.fail_json(msg='Error while fetching user info: %s' % error)
400 if message['num_records'] == 1:
401 return message['records'][0]['owner']['uuid'], message['records'][0]['name']
402 if message['num_records'] > 1:
403 self.module.fail_json(msg='Error while fetching user info, found multiple entries: %s' % repr(message))
404
405 return None
406
407 def get_user_details_rest(self, name, owner_uuid):
408 query = {
409 'fields': 'role,applications,locked'
410 }
411 api = "security/accounts/%s/%s" % (owner_uuid, name)
412 response, error = self.rest_api.get(api, query)
413 if error:
414 self.module.fail_json(msg='Error while fetching user details: %s' % error)
415 if response:
416 # replace "none" values with None for comparison
417 for application in response['applications']:
418 if application.get('second_authentication_method') == 'none':
419 application['second_authentication_method'] = None
420 # new read-only attributes in 9.14 onwards, breaks idempotency when present
421 application.pop('is_ldap_fastbind', None)
422 application.pop('is_ns_switch_group', None)
423 return_value = {
424 'role_name': response['role']['name'],
425 'applications': response['applications']
426 }
427 if "locked" in response:
428 return_value['lock_user'] = response['locked']
429 return return_value
430
431 def get_user(self):
432 """
433 Checks if the user exists.
434 :param: application: application to grant access to, a dict
435 :return:
436 Dictionary if user found
437 None if user is not found
438 """
439 desired_applications = [application['application'] for application in self.parameters['applications']]
440 desired_method = self.parameters.get('authentication_method')
441 security_login_get_iter = netapp_utils.zapi.NaElement('security-login-get-iter')
442 query_details = netapp_utils.zapi.NaElement.create_node_with_children(
443 'security-login-account-info', **{'vserver': self.parameters['vserver'],
444 'user-name': self.parameters['name']})
445
446 query = netapp_utils.zapi.NaElement('query')
447 query.add_child_elem(query_details)
448 security_login_get_iter.add_child_elem(query)
449 try:
450 result = self.server.invoke_successfully(security_login_get_iter,
451 enable_tunneling=False)
452 except netapp_utils.zapi.NaApiError as error:
453 if to_native(error.code) in ['16034', '16043']:
454 # Error 16034 denotes a user not being found.
455 # Error 16043 denotes the user existing, but the application missing.
456 return None
457 self.module.fail_json(msg='Error getting user %s: %s' % (self.parameters['name'], to_native(error)),
458 exception=traceback.format_exc())
459
460 if not result.get_child_by_name('num-records') or not int(result.get_child_content('num-records')):
461 return None
462
463 applications = {}
464 attr = result.get_child_by_name('attributes-list')
465 locks = []
466 for info in attr.get_children():
467 lock_user = self.na_helper.get_value_for_bool(True, info.get_child_content('is-locked'))
468 locks.append(lock_user)
469 role_name = info.get_child_content('role-name')
470 application = info.get_child_content('application')
471 auth_method = info.get_child_content('authentication-method')
472 sec_method = info.get_child_content('second-authentication-method')
473 if self.parameters['replace_existing_apps_and_methods'] == 'always' and application in applications:
474 applications[application][0].append(auth_method)
475 if sec_method != 'none':
476 # we can't change sec_method in place, a tuple is not mutable
477 applications[application] = (applications[application][0], sec_method)
478 elif (self.parameters['replace_existing_apps_and_methods'] == 'always'
479 or (application in desired_applications and auth_method == desired_method)):
480 # with 'auto' we ignore existing apps that were not asked for
481 # with auto, only a single method is supported
482 applications[application] = ([auth_method], sec_method if sec_method != 'none' else None)
483 apps = [dict(application=application, authentication_methods=sorted(methods), second_authentication_method=sec_method)
484 for application, (methods, sec_method) in applications.items()]
485 return dict(
486 lock_user=any(locks),
487 role_name=role_name,
488 applications=apps
489 )
490
491 def create_user_rest(self, apps):
492 api = 'security/accounts'
493 body = {
494 'name': self.parameters['name'],
495 'role.name': self.parameters['role_name'],
496 'applications': self.na_helper.filter_out_none_entries(apps)
497 }
498 if self.parameters.get('vserver') is not None:
499 # vserser is empty for cluster
500 body['owner.name'] = self.parameters['vserver']
501 if 'set_password' in self.parameters:
502 body['password'] = self.parameters['set_password']
503 if 'lock_user' in self.parameters:
504 body['locked'] = self.parameters['lock_user']
505 dummy, error = self.rest_api.post(api, body)
506 if (
507 error
508 and 'invalid value' in error['message']
509 and any(x in error['message'] for x in ['service-processor', 'service_processor'])
510 ):
511 # find if there is an error for service processor application value
512 # update value as per ONTAP version support
513 app_list_sp = body['applications']
514 for app_item in app_list_sp:
515 if app_item['application'] == 'service-processor':
516 app_item['application'] = 'service_processor'
517 elif app_item['application'] == 'service_processor':
518 app_item['application'] = 'service-processor'
519 body['applications'] = app_list_sp
520 # post again and throw first error in case of an error
521 dummy, error_sp = self.rest_api.post(api, body)
522 if not error_sp:
523 return
524
525 # non-sp errors thrown or initial sp errors
526 if error:
527 self.module.fail_json(msg='Error while creating user: %s' % error)
528
529 def create_user(self, application):
530 for index in range(len(application['authentication_methods'])):
531 self.create_user_with_auth(application, index)
532
533 def create_user_with_auth(self, application, index):
534 """
535 creates the user for the given application and authentication_method
536 application is now a directory
537 :param: application: application to grant access to
538 """
539 user_create = netapp_utils.zapi.NaElement.create_node_with_children(
540 'security-login-create', **{'vserver': self.parameters['vserver'],
541 'user-name': self.parameters['name'],
542 'application': application['application'],
543 'authentication-method': application['authentication_methods'][index],
544 'role-name': self.parameters.get('role_name')})
545 if application.get('second_authentication_method') is not None:
546 user_create.add_new_child('second-authentication-method', application['second_authentication_method'])
547 if self.parameters.get('set_password') is not None:
548 user_create.add_new_child('password', self.parameters.get('set_password'))
549 if application['authentication_methods'][0] == 'usm':
550 if self.parameters.get('remote_switch_ipaddress') is not None:
551 user_create.add_new_child('remote-switch-ipaddress', self.parameters.get('remote_switch_ipaddress'))
552 snmpv3_login_info = netapp_utils.zapi.NaElement('snmpv3-login-info')
553 if self.parameters.get('authentication_password') is not None:
554 snmpv3_login_info.add_new_child('authentication-password', self.parameters['authentication_password'])
555 if self.parameters.get('authentication_protocol') is not None:
556 snmpv3_login_info.add_new_child('authentication-protocol', self.parameters['authentication_protocol'])
557 if self.parameters.get('engine_id') is not None:
558 snmpv3_login_info.add_new_child('engine-id', self.parameters['engine_id'])
559 if self.parameters.get('privacy_password') is not None:
560 snmpv3_login_info.add_new_child('privacy-password', self.parameters['privacy_password'])
561 if self.parameters.get('privacy_protocol') is not None:
562 snmpv3_login_info.add_new_child('privacy-protocol', self.parameters['privacy_protocol'])
563 user_create.add_child_elem(snmpv3_login_info)
564
565 try:
566 self.server.invoke_successfully(user_create,
567 enable_tunneling=False)
568 except netapp_utils.zapi.NaApiError as error:
569 self.module.fail_json(msg='Error creating user %s: %s' % (self.parameters['name'], to_native(error)),
570 exception=traceback.format_exc())
571
572 def lock_unlock_user_rest(self, owner_uuid, username, value=None):
573 body = {
574 'locked': value
575 }
576 error = self.patch_account(owner_uuid, username, body)
577 if error:
578 self.module.fail_json(msg='Error while locking/unlocking user: %s' % error)
579
580 def lock_given_user(self):
581 """
582 locks the user
583 """
584 user_lock = netapp_utils.zapi.NaElement.create_node_with_children(
585 'security-login-lock', **{'vserver': self.parameters['vserver'],
586 'user-name': self.parameters['name']})
587
588 try:
589 self.server.invoke_successfully(user_lock,
590 enable_tunneling=False)
591 except netapp_utils.zapi.NaApiError as error:
592 self.module.fail_json(msg='Error locking user %s: %s' % (self.parameters['name'], to_native(error)),
593 exception=traceback.format_exc())
594
595 def unlock_given_user(self):
596 """
597 unlocks the user
598 """
599 user_unlock = netapp_utils.zapi.NaElement.create_node_with_children(
600 'security-login-unlock', **{'vserver': self.parameters['vserver'],
601 'user-name': self.parameters['name']})
602
603 try:
604 self.server.invoke_successfully(user_unlock,
605 enable_tunneling=False)
606 except netapp_utils.zapi.NaApiError as error:
607 if to_native(error.code) != '13114':
608 self.module.fail_json(msg='Error unlocking user %s: %s' % (self.parameters['name'], to_native(error)),
609 exception=traceback.format_exc())
610 return
611
612 def delete_user_rest(self, owner_uuid, username):
613 api = "security/accounts/%s/%s" % (owner_uuid, username)
614 dummy, error = self.rest_api.delete(api)
615 if error:
616 self.module.fail_json(msg='Error while deleting user: %s' % error)
617
618 def delete_user(self, application, methods_to_keep=None):
619 for index, method in enumerate(application['authentication_methods']):
620 if methods_to_keep is None or method not in methods_to_keep:
621 self.delete_user_with_auth(application, index)
622
623 def delete_user_with_auth(self, application, index):
624 """
625 deletes the user for the given application and authentication_method
626 application is now a dict
627 :param: application: application to grant access to
628 """
629 user_delete = netapp_utils.zapi.NaElement.create_node_with_children(
630 'security-login-delete', **{'vserver': self.parameters['vserver'],
631 'user-name': self.parameters['name'],
632 'application': application['application'],
633 'authentication-method': application['authentication_methods'][index]})
634
635 try:
636 self.server.invoke_successfully(user_delete,
637 enable_tunneling=False)
638 except netapp_utils.zapi.NaApiError as error:
639 self.module.fail_json(msg='Error removing user %s: %s - application: %s'
640 % (self.parameters['name'], to_native(error), application),
641 exception=traceback.format_exc())
642
643 @staticmethod
644 def is_repeated_password(message):
645 return message.startswith('New password must be different than last 6 passwords.') \
646 or message.startswith('New password must be different from last 6 passwords.') \
647 or message.startswith('New password must be different than the old password.') \
648 or message.startswith('New password must be different from the old password.')
649
650 def change_password_rest(self, owner_uuid, username):
651 body = {
652 'password': self.parameters['set_password'],
653 }
654 error = self.patch_account(owner_uuid, username, body)
655 if error:
656 if 'message' in error and self.is_repeated_password(error['message']):
657 # if the password is reused, assume idempotency but show a warning
658 self.module.warn('Password was not changed: %s' % error['message'])
659 return False
660 self.module.fail_json(msg='Error while updating user password: %s' % error)
661 return True
662
663 def change_password(self):
664 """
665 Changes the password
666
667 :return:
668 True if password updated
669 False if password is not updated
670 :rtype: bool
671 """
672 # self.server.set_vserver(self.parameters['vserver'])
673 modify_password = netapp_utils.zapi.NaElement.create_node_with_children(
674 'security-login-modify-password', **{
675 'new-password': str(self.parameters.get('set_password')),
676 'user-name': self.parameters['name']})
677 try:
678 self.server.invoke_successfully(modify_password,
679 enable_tunneling=True)
680 except netapp_utils.zapi.NaApiError as error:
681 if to_native(error.code) == '13114':
682 return False
683 # if the user give the same password, instead of returning an error, return ok
684 if to_native(error.code) == '13214' and self.is_repeated_password(error.message):
685 return False
686 self.module.fail_json(msg='Error setting password for user %s: %s' % (self.parameters['name'], to_native(error)),
687 exception=traceback.format_exc())
688
689 self.server.set_vserver(None)
690 return True
691
692 def modify_apps_rest(self, owner_uuid, username, apps=None):
693 body = {
694 'role.name': self.parameters['role_name'],
695 'applications': self.na_helper.filter_out_none_entries(apps)
696 }
697 error = self.patch_account(owner_uuid, username, body)
698 if error:
699 self.module.fail_json(msg='Error while modifying user details: %s' % error)
700
701 def patch_account(self, owner_uuid, username, body):
702 query = {'name': self.parameters['name'], 'owner.uuid': owner_uuid}
703 api = "security/accounts/%s/%s" % (owner_uuid, username)
704 dummy, result = self.rest_api.patch(api, body, query)
705 return result
706
707 def modify_user(self, application, current_methods):
708 for index, method in enumerate(application['authentication_methods']):
709 if method in current_methods:
710 self.modify_user_with_auth(application, index)
711 else:
712 self.create_user_with_auth(application, index)
713
714 def modify_user_with_auth(self, application, index):
715 """
716 Modify user
717 application is now a dict
718 """
719 user_modify = netapp_utils.zapi.NaElement.create_node_with_children(
720 'security-login-modify', **{'vserver': self.parameters['vserver'],
721 'user-name': self.parameters['name'],
722 'application': application['application'],
723 'authentication-method': application['authentication_methods'][index],
724 'role-name': self.parameters.get('role_name')})
725
726 try:
727 self.server.invoke_successfully(user_modify,
728 enable_tunneling=False)
729 except netapp_utils.zapi.NaApiError as error:
730 self.module.fail_json(msg='Error modifying user %s: %s' % (self.parameters['name'], to_native(error)),
731 exception=traceback.format_exc())
732
733 def change_sp_application(self, current_apps):
734 """Adjust requested app name to match ONTAP convention"""
735 if not self.parameters['applications']:
736 return
737 app_list = [app['application'] for app in current_apps]
738 for application in self.parameters['applications']:
739 if application['application'] == 'service_processor' and 'service-processor' in app_list:
740 application['application'] = 'service-processor'
741 elif application['application'] == 'service-processor' and 'service_processor' in app_list:
742 application['application'] = 'service_processor'
743
744 def validate_action(self, action):
745 errors = []
746 if action == 'create':
747 if not self.parameters.get('role_name'):
748 errors.append('role_name')
749 if not self.parameters.get('applications'):
750 errors.append('application_dicts or application_strs')
751 if errors:
752 plural = 's' if len(errors) > 1 else ''
753 self.module.fail_json(msg='Error: missing required parameter%s for %s: %s.' %
754 (plural, action, ' and: '.join(errors)))
755
756 def modify_apps_zapi(self, current, modify_decision):
757 if 'applications' not in modify_decision:
758 # to change roles, we need at least one app
759 modify_decision['applications'] = self.parameters['applications']
760 current_apps = dict((application['application'], application['authentication_methods']) for application in current['applications'])
761 for application in modify_decision['applications']:
762 if application['application'] in current_apps:
763 self.modify_user(application, current_apps[application['application']])
764 else:
765 self.create_user(application)
766 desired_apps = dict((application['application'], application['authentication_methods'])
767 for application in self.parameters['applications'])
768 for application in current['applications']:
769 if application['application'] not in desired_apps:
770 self.delete_user(application)
771 else:
772 self.delete_user(application, desired_apps[application['application']])
773
774 def get_current(self):
775 owner_uuid, name = None, None
776 if self.use_rest:
777 current = self.get_user_rest()
778 if current is not None:
779 owner_uuid, name = current
780 current = self.get_user_details_rest(name, owner_uuid)
781 self.change_sp_application(current['applications'])
782 else:
783 current = self.get_user()
784 return current, owner_uuid, name
785
786 def define_actions(self, current):
787 cd_action = self.na_helper.get_cd_action(current, self.parameters)
788 modify = self.na_helper.get_modified_attributes(current, self.parameters) if cd_action is None else None
789 if self.use_rest and cd_action is None and current and 'lock_user' not in current and self.parameters.get('lock_user') is not None:
790 # REST does not return locked if password is not set
791 if self.parameters.get('set_password') is None:
792 self.module.fail_json(msg='Error: cannot modify lock state if password is not set.')
793 modify['lock_user'] = self.parameters['lock_user']
794 self.na_helper.changed = True
795 self.validate_action(cd_action)
796 return cd_action, modify
797
798 def take_action(self, cd_action, modify, current, owner_uuid, name):
799 if cd_action == 'create':
800 if self.use_rest:
801 self.create_user_rest(self.parameters['applications'])
802 else:
803 for application in self.parameters['applications']:
804 self.create_user(application)
805 elif cd_action == 'delete':
806 if self.use_rest:
807 self.delete_user_rest(owner_uuid, name)
808 else:
809 for application in current['applications']:
810 self.delete_user(application)
811 elif modify:
812 if 'role_name' in modify or 'applications' in modify:
813 if self.use_rest:
814 self.modify_apps_rest(owner_uuid, name, self.parameters['applications'])
815 else:
816 self.modify_apps_zapi(current, modify)
817 return modify and 'lock_user' in modify
818
819 def apply(self):
820 current, owner_uuid, name = self.get_current()
821 cd_action, modify = self.define_actions(current)
822 deferred_lock = False
823
824 if self.na_helper.changed and not self.module.check_mode:
825 # lock/unlock actions require password to be set
826 deferred_lock = self.take_action(cd_action, modify, current, owner_uuid, name)
827
828 password_changed = False
829 if cd_action is None and self.parameters.get('set_password') is not None and self.parameters['state'] == 'present':
830 # if check_mode, don't attempt to change the password, but assume it would be changed
831 if self.use_rest:
832 password_changed = self.module.check_mode or self.change_password_rest(owner_uuid, name)
833 else:
834 password_changed = self.module.check_mode or self.change_password()
835 if self.module.check_mode:
836 self.module.warn('Module is not idempotent with check_mode when set_password is present.')
837
838 if deferred_lock:
839 if self.use_rest:
840 self.lock_unlock_user_rest(owner_uuid, name, self.parameters['lock_user'])
841 elif self.parameters.get('lock_user'):
842 self.lock_given_user()
843 else:
844 self.unlock_given_user()
845
846 self.module.exit_json(changed=self.na_helper.changed | password_changed, current=current, modify=modify)
847
848
849 def main():
850 obj = NetAppOntapUser()
851 obj.apply()
852
853
854 if __name__ == '__main__':
855 main()