Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # (c) 2018-2026, NetApp, Inc
4 # GNU General Public License v3.0+
5 # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 '''
8 na_ontap_svm
9 '''
10
11 from __future__ import absolute_import, division, print_function
12 __metaclass__ = type
13
14
15 DOCUMENTATION = '''
16
17 module: na_ontap_svm
18
19 short_description: NetApp ONTAP SVM
20 extends_documentation_fragment:
21 - netapp.ontap.netapp.na_ontap
22 version_added: 2.6.0
23 author: NetApp Ansible Team (@carchi8py) <[email protected]>
24
25 description:
26 - Create, modify or delete SVM on NetApp ONTAP
27
28 options:
29
30 state:
31 description:
32 - Whether the specified SVM should exist or not.
33 choices: ['present', 'absent']
34 default: 'present'
35 type: str
36
37 name:
38 description:
39 - The name of the SVM to manage.
40 - vserver is a convenient alias when using module_defaults.
41 type: str
42 required: true
43 aliases:
44 - vserver
45
46 from_name:
47 description:
48 - Name of the SVM to be renamed
49 type: str
50 version_added: 2.7.0
51
52 admin_state:
53 description:
54 - when the SVM is created, it will be in the running state, unless specified otherwise.
55 - This is ignored with ZAPI.
56 choices: ['running', 'stopped']
57 type: str
58 version_added: 21.15.0
59
60 root_volume:
61 description:
62 - Root volume of the SVM.
63 - Cannot be modified after creation.
64 type: str
65
66 root_volume_aggregate:
67 description:
68 - The aggregate on which the root volume will be created.
69 - Cannot be modified after creation.
70 type: str
71
72 root_volume_security_style:
73 description:
74 - Security Style of the root volume.
75 - When specified as part of the vserver-create,
76 this field represents the security style for the Vserver root volume.
77 - When specified as part of vserver-get-iter call,
78 this will return the list of matching Vservers.
79 - The 'unified' security style, which applies only to Infinite Volumes,
80 cannot be applied to a Vserver's root volume.
81 - Cannot be modified after creation.
82 choices: ['unix', 'ntfs', 'mixed', 'unified']
83 type: str
84
85 allowed_protocols:
86 description:
87 - This field represents the list of protocols allowed on the Vserver.
88 - When part of modify,
89 this field should include the existing list
90 along with new protocol list to be added to prevent data disruptions.
91 - Mutually exclusive with C(services).
92 - Possible values
93 - nfs NFS protocol,
94 - cifs CIFS protocol,
95 - fcp FCP protocol,
96 - iscsi iSCSI protocol,
97 - ndmp NDMP protocol,
98 - s3 S3 protocol,
99 - http HTTP protocol - ZAPI only,
100 - nvme NVMe protocol
101 type: list
102 elements: str
103
104 services:
105 description:
106 - Enabled Protocols, only available with REST.
107 - The service will be started if needed. A valid license may be required.
108 - C(enabled) is not supported for CIFS, to enable it use na_ontap_cifs_server.
109 - C(enabled) is not supported for s3, to enable it use na_ontap_s3_services.
110 - If a service is not present, it is left unchanged.
111 - Mutually exclusive with C(allowed_protocols).
112 type: dict
113 version_added: 21.10.0
114 suboptions:
115 cifs:
116 description:
117 - CIFS protocol service
118 type: dict
119 suboptions:
120 allowed:
121 description: If true, an SVM administrator can manage the CIFS service. If false, only the cluster administrator can manage the service.
122 type: bool
123 iscsi:
124 description:
125 - iSCSI protocol service
126 type: dict
127 suboptions:
128 allowed:
129 description: If true, an SVM administrator can manage the iSCSI service. If false, only the cluster administrator can manage the service.
130 type: bool
131 enabled:
132 description: If allowed, setting to true enables the iSCSI service.
133 type: bool
134 fcp:
135 description:
136 - FCP protocol service
137 type: dict
138 suboptions:
139 allowed:
140 description: If true, an SVM administrator can manage the FCP service. If false, only the cluster administrator can manage the service.
141 type: bool
142 enabled:
143 description: If allowed, setting to true enables the FCP service.
144 type: bool
145 nfs:
146 description:
147 - NFS protocol service
148 type: dict
149 suboptions:
150 allowed:
151 description: If true, an SVM administrator can manage the NFS service. If false, only the cluster administrator can manage the service.
152 type: bool
153 enabled:
154 description: If allowed, setting to true enables the NFS service.
155 type: bool
156 nvme:
157 description:
158 - nvme protocol service
159 type: dict
160 suboptions:
161 allowed:
162 description: If true, an SVM administrator can manage the NVMe service. If false, only the cluster administrator can manage the service.
163 type: bool
164 enabled:
165 description: If allowed, setting to true enables the NVMe service.
166 type: bool
167 ndmp:
168 description:
169 - Network Data Management Protocol service
170 type: dict
171 suboptions:
172 allowed:
173 description:
174 - If this is set to true, an SVM administrator can manage the NDMP service
175 - If it is false, only the cluster administrator can manage the service.
176 - Requires ONTAP 9.10.1 or later.
177 type: bool
178 version_added: 21.24.0
179 s3:
180 description:
181 - s3 service
182 type: dict
183 suboptions:
184 allowed:
185 description:
186 - If true, an SVM administrator can manage the s3 service. If false, only the cluster administrator can manage the service.
187 - Requires ONTAP 9.7.0 or later.
188 type: bool
189 aggr_list:
190 description:
191 - List of aggregates assigned for volume operations.
192 - These aggregates could be shared for use with other Vservers.
193 - When specified as part of a vserver-create,
194 this field represents the list of aggregates
195 that are assigned to the Vserver for volume operations.
196 - When part of vserver-get-iter call,
197 this will return the list of Vservers
198 which have any of the aggregates specified as part of the aggr list.
199 type: list
200 elements: str
201
202 ipspace:
203 description:
204 - IPSpace name
205 - Cannot be modified after creation.
206 type: str
207 version_added: 2.7.0
208
209 snapshot_policy:
210 description:
211 - Default snapshot policy setting for all volumes of the Vserver.
212 This policy will be assigned to all volumes created in this
213 Vserver unless the volume create request explicitly provides a
214 snapshot policy or volume is modified later with a specific
215 snapshot policy. A volume-level snapshot policy always overrides
216 the default Vserver-wide snapshot policy.
217 version_added: 2.7.0
218 type: str
219
220 language:
221 description:
222 - Language to use for the SVM
223 - Default to C.UTF-8
224 - Possible values Language
225 - c POSIX
226 - ar Arabic
227 - cs Czech
228 - da Danish
229 - de German
230 - en English
231 - en_us English (US)
232 - es Spanish
233 - fi Finnish
234 - fr French
235 - he Hebrew
236 - hr Croatian
237 - hu Hungarian
238 - it Italian
239 - ja Japanese euc-j
240 - ja_v1 Japanese euc-j
241 - ja_jp.pck Japanese PCK (sjis)
242 - ja_jp.932 Japanese cp932
243 - ja_jp.pck_v2 Japanese PCK (sjis)
244 - ko Korean
245 - no Norwegian
246 - nl Dutch
247 - pl Polish
248 - pt Portuguese
249 - ro Romanian
250 - ru Russian
251 - sk Slovak
252 - sl Slovenian
253 - sv Swedish
254 - tr Turkish
255 - zh Simplified Chinese
256 - zh.gbk Simplified Chinese (GBK)
257 - zh_tw Traditional Chinese euc-tw
258 - zh_tw.big5 Traditional Chinese Big 5
259 - utf8mb4
260 - Most of the values accept a .utf_8 suffix, e.g. fr.utf_8
261 type: str
262 version_added: 2.7.0
263
264 subtype:
265 description:
266 - The subtype for vserver to be created.
267 - Cannot be modified after creation.
268 choices: ['default', 'dp_destination', 'sync_source', 'sync_destination']
269 type: str
270 version_added: 2.7.0
271
272 comment:
273 description:
274 - When specified as part of a vserver-create, this field represents the comment associated with the Vserver.
275 - When part of vserver-get-iter call, this will return the list of matching Vservers.
276 type: str
277 version_added: 2.8.0
278
279 ignore_rest_unsupported_options:
280 description:
281 - When true, ignore C(root_volume), C(root_volume_aggregate), C(root_volume_security_style) options if target supports REST.
282 - Ignored when C(use_rest) is set to never.
283 type: bool
284 default: false
285 version_added: 21.10.0
286
287 max_volumes:
288 description:
289 - Maximum number of volumes that can be created on the vserver.
290 - Expects an integer or C(unlimited).
291 type: str
292 version_added: 21.12.0
293
294 web:
295 description:
296 - web services security configuration.
297 - requires ONTAP 9.8 or later for certificate name.
298 - requires ONTAP 9.10.1 or later for the other options.
299 type: dict
300 suboptions:
301 certificate:
302 description:
303 - name of certificate used by cluster and node management interfaces for TLS connection requests.
304 - The certificate must be of type "server".
305 type: str
306 client_enabled:
307 description: whether client authentication is enabled.
308 type: bool
309 ocsp_enabled:
310 description: whether online certificate status protocol verification is enabled.
311 type: bool
312
313 storage_limit:
314 description:
315 - Specifies the maximum storage permitted on a single SVM, in bytes.
316 - This parameter can be set to zero to disable storage-limit enforcement.
317 - Only supported with REST, requires ONTAP 9.13.1 or later.
318 type: int
319 version_added: 23.1.0
320
321 storage_limit_threshold_alert:
322 description:
323 - Specifies at what percentage of storage capacity an alert message is sent.
324 - The default value is 90.
325 - Only supported with REST, requires ONTAP 9.13.1 or later.
326 type: int
327 version_added: 23.2.0
328
329 auto_enable_analytics:
330 description:
331 - Specifies whether file system analytics is automatically enabled on volumes that are created in the SVM.
332 - Only supported with REST, requires ONTAP 9.12.1 or later.
333 type: bool
334 version_added: 23.2.0
335
336 auto_enable_activity_tracking:
337 description:
338 - Specifies whether volume activity tracking is automatically enabled on volumes that are created in the SVM.
339 - Only supported with REST, requires ONTAP 9.12.1 or later.
340 type: bool
341 version_added: 23.2.0
342
343 anti_ransomware_default_volume_state:
344 description:
345 - Specifies the default anti-ransomware state of the volumes in the SVM.
346 - When the anti-ransomware license is not present, this property is ignored and volumes will be created with the "disabled" state.
347 - Only supported with REST, requires ONTAP 9.10.1 or later.
348 type: str
349 choices: ['disabled', 'dry_run']
350 version_added: 23.5.0
351
352 lambda_config:
353 description:
354 - Configuration parameters for AWS Lambda proxy functionality.
355 - These option and suboptions are only supported with REST.
356 type: dict
357 version_added: 23.3.0
358 suboptions:
359 function_name:
360 description:
361 - The name of the AWS Lambda function to invoke.
362 type: str
363 required: true
364 aws_region:
365 description:
366 - The name of the AWS region.
367 type: str
368 required: true
369 aws_profile:
370 description:
371 - The name of the AWS profile to use for authentication.
372 type: str
373
374 notes:
375 - Supports AWS Lambda proxy functionality when using REST. See the README file for examples.
376 '''
377
378 EXAMPLES = """
379 - name: Create SVM
380 netapp.ontap.na_ontap_svm:
381 state: present
382 name: ansibleVServer
383 root_volume: vol1
384 root_volume_aggregate: aggr1
385 root_volume_security_style: mixed
386 hostname: "{{ netapp_hostname }}"
387 username: "{{ netapp_username }}"
388 password: "{{ netapp_password }}"
389
390 - name: Create SVM
391 netapp.ontap.na_ontap_svm:
392 state: present
393 services:
394 cifs:
395 allowed: true
396 fcp:
397 allowed: true
398 nfs:
399 allowed: true
400 enabled: true
401 s3:
402 allowed: true
403 hostname: "{{ netapp_hostname }}"
404 username: "{{ netapp_username }}"
405 password: "{{ netapp_password }}"
406 https: true
407 validate_certs: false
408
409 - name: Stop SVM REST
410 netapp.ontap.na_ontap_svm:
411 state: present
412 name: ansibleVServer
413 admin_state: stopped
414 use_rest: always
415 hostname: "{{ netapp_hostname }}"
416 username: "{{ netapp_username }}"
417 password: "{{ netapp_password }}"
418 """
419
420 RETURN = """
421 """
422 import copy
423 import traceback
424
425 from ansible.module_utils.basic import AnsibleModule
426 from ansible.module_utils._text import to_native
427 import ansible_collections.netapp.ontap.plugins.module_utils.netapp as netapp_utils
428 from ansible_collections.netapp.ontap.plugins.module_utils.netapp import OntapRestAPI
429 from ansible_collections.netapp.ontap.plugins.module_utils.netapp_module import NetAppModule
430 from ansible_collections.netapp.ontap.plugins.module_utils import rest_generic, rest_vserver, zapis_svm
431
432
433 class NetAppOntapSVM():
434 ''' create, delete, modify, rename SVM (aka vserver) '''
435
436 def __init__(self):
437 self.use_rest = False
438 self.argument_spec = netapp_utils.na_ontap_host_argument_spec()
439 self.argument_spec.update(dict(
440 state=dict(required=False, type='str', choices=['present', 'absent'], default='present'),
441 name=dict(required=True, type='str', aliases=['vserver']),
442 from_name=dict(required=False, type='str'),
443 admin_state=dict(required=False, type='str', choices=['running', 'stopped']),
444 root_volume=dict(type='str'),
445 root_volume_aggregate=dict(type='str'),
446 root_volume_security_style=dict(type='str', choices=['unix',
447 'ntfs',
448 'mixed',
449 'unified'
450 ]),
451 allowed_protocols=dict(type='list', elements='str'),
452 aggr_list=dict(type='list', elements='str'),
453 ipspace=dict(type='str', required=False),
454 snapshot_policy=dict(type='str', required=False),
455 language=dict(type='str', required=False),
456 subtype=dict(type='str', choices=['default', 'dp_destination', 'sync_source', 'sync_destination']),
457 comment=dict(type='str', required=False),
458 ignore_rest_unsupported_options=dict(type='bool', default=False),
459 max_volumes=dict(type='str'),
460 # TODO: add CIFS options, and S3
461 services=dict(type='dict', options=dict(
462 cifs=dict(type='dict', options=dict(allowed=dict(type='bool'))),
463 iscsi=dict(type='dict', options=dict(allowed=dict(type='bool'), enabled=dict(type='bool'))),
464 fcp=dict(type='dict', options=dict(allowed=dict(type='bool'), enabled=dict(type='bool'))),
465 nfs=dict(type='dict', options=dict(allowed=dict(type='bool'), enabled=dict(type='bool'))),
466 nvme=dict(type='dict', options=dict(allowed=dict(type='bool'), enabled=dict(type='bool'))),
467 ndmp=dict(type='dict', options=dict(allowed=dict(type='bool'))),
468 s3=dict(type='dict', options=dict(allowed=dict(type='bool')))
469 )),
470 web=dict(type='dict', options=dict(
471 certificate=dict(type='str'),
472 client_enabled=dict(type='bool'),
473 ocsp_enabled=dict(type='bool'),
474 )),
475 storage_limit=dict(type='int', required=False),
476 storage_limit_threshold_alert=dict(type='int', required=False),
477 auto_enable_analytics=dict(type='bool', required=False),
478 auto_enable_activity_tracking=dict(type='bool', required=False),
479 anti_ransomware_default_volume_state=dict(type='str', choices=['disabled', 'dry_run'], required=False),
480 ))
481
482 self.argument_spec.update(netapp_utils.na_ontap_lambda_argument_spec())
483
484 self.module = AnsibleModule(
485 argument_spec=self.argument_spec,
486 supports_check_mode=True,
487 mutually_exclusive=[('allowed_protocols', 'services'),
488 ('services', 'root_volume'),
489 ('services', 'root_volume_aggregate'),
490 ('services', 'root_volume_security_style')],
491 required_if=[
492 ['use_lambda', True, ('lambda_config',)]
493 ],
494 )
495 self.na_helper = NetAppModule()
496 self.parameters = self.na_helper.set_parameters(self.module.params)
497 # Ontap documentation uses C.UTF-8, but actually stores as c.utf_8.
498 if 'language' in self.parameters and self.parameters['language'].lower() == 'c.utf-8':
499 self.parameters['language'] = 'c.utf_8'
500
501 self.rest_api = OntapRestAPI(self.module)
502 # with REST, to force synchronous operations
503 self.timeout = self.rest_api.timeout
504 # with REST, to know which protocols to look for
505 self.allowable_protocols_rest = netapp_utils.get_feature(self.module, 'svm_allowable_protocols_rest')
506 self.allowable_protocols_zapi = netapp_utils.get_feature(self.module, 'svm_allowable_protocols_zapi')
507 self.use_rest = self.validate_options()
508 if not self.use_rest:
509 if self.parameters.get('use_lambda'):
510 self.module.fail_json(msg="Error: AWS Lambda proxy for ONTAP APIs is only supported with REST.")
511 if not netapp_utils.has_netapp_lib():
512 self.module.fail_json(msg=netapp_utils.netapp_lib_is_required())
513 self.server = netapp_utils.setup_na_ontap_zapi(module=self.module)
514 if self.parameters.get('admin_state') is not None:
515 self.parameters.pop('admin_state')
516 self.module.warn('admin_state is ignored when ZAPI is used.')
517
518 def validate_int_or_string(self, value, astring):
519 if value is None or value == astring:
520 return
521 try:
522 int_value = int(value)
523 except ValueError:
524 int_value = None
525 if int_value is None or str(int_value) != value:
526 self.module.fail_json(msg="Error: expecting int value or '%s', got: %s - %s" % (astring, value, int_value))
527
528 def validate_options(self):
529
530 # root volume not supported with rest api
531 unsupported_rest_properties = ['root_volume', 'root_volume_aggregate', 'root_volume_security_style']
532 required_unsupported_rest_properties = [] if self.parameters['ignore_rest_unsupported_options'] else unsupported_rest_properties
533 ignored_unsupported_rest_properties = unsupported_rest_properties if self.parameters['ignore_rest_unsupported_options'] else []
534 used_required_unsupported_rest_properties = [x for x in required_unsupported_rest_properties if x in self.parameters]
535 used_ignored_unsupported_rest_properties = [x for x in ignored_unsupported_rest_properties if x in self.parameters]
536 use_rest, error = self.rest_api.is_rest(used_required_unsupported_rest_properties)
537 if error is not None:
538 self.module.fail_json(msg=error)
539 if use_rest and used_ignored_unsupported_rest_properties:
540 self.module.warn('Using REST and ignoring: %s' % used_ignored_unsupported_rest_properties)
541 for attr in used_ignored_unsupported_rest_properties:
542 del self.parameters[attr]
543 if use_rest and 'aggr_list' in self.parameters and self.parameters['aggr_list'] == ['*']:
544 self.module.warn("Using REST and ignoring aggr_list: '*'")
545 del self.parameters['aggr_list']
546 if use_rest and self.parameters.get('allowed_protocols') is not None:
547 # python 2.6 does not support dict comprehension with k: v
548 self.parameters['services'] = dict(
549 # using old semantics, anything not present is disallowed
550 (protocol, {'allowed': protocol in self.parameters['allowed_protocols']})
551 for protocol in self.allowable_protocols_rest
552 )
553
554 if self.parameters.get('allowed_protocols'):
555 allowable = self.allowable_protocols_rest if use_rest else self.allowable_protocols_zapi
556 errors = [
557 'Unexpected value %s in allowed_protocols.' % protocol
558 for protocol in self.parameters['allowed_protocols']
559 if protocol not in allowable
560 ]
561 if errors:
562 self.module.fail_json(msg='Error - %s' % ' '.join(errors))
563 if use_rest and self.parameters.get('services') and not self.parameters.get('allowed_protocols'):
564 if self.parameters['services'].get('ndmp') and not self.rest_api.meets_rest_minimum_version(use_rest, 9, 10, 1):
565 self.module.fail_json(msg=self.rest_api.options_require_ontap_version('ndmp', '9.10.1', use_rest=use_rest))
566 if self.parameters['services'].get('s3') and not self.rest_api.meets_rest_minimum_version(use_rest, 9, 7, 0):
567 self.module.fail_json(msg=self.rest_api.options_require_ontap_version('s3', '9.7.0', use_rest=use_rest))
568 if self.parameters.get('services') and not use_rest:
569 self.module.fail_json(msg=self.rest_api.options_require_ontap_version('services', use_rest=use_rest))
570 if self.parameters.get('web'):
571 if not use_rest or not self.rest_api.meets_rest_minimum_version(use_rest, 9, 8, 0):
572 self.module.fail_json(msg=self.rest_api.options_require_ontap_version('web', '9.8', use_rest=use_rest))
573 if not self.rest_api.meets_rest_minimum_version(use_rest, 9, 10, 1):
574 suboptions = ('client_enabled', 'ocsp_enabled')
575 for suboption in suboptions:
576 if self.parameters['web'].get(suboption) is not None:
577 self.module.fail_json(msg=self.rest_api.options_require_ontap_version(suboptions, '9.10.1', use_rest=use_rest))
578 if self.parameters['web'].get('certificate'):
579 # so that we can compare UUIDs while using a more friendly name in the user interface
580 self.parameters['web']['certificate'] = {'name': self.parameters['web']['certificate']}
581 self.set_certificate_uuid()
582 if use_rest and self.parameters.get('auto_enable_analytics') is not None and \
583 not self.rest_api.meets_rest_minimum_version(use_rest, 9, 12, 1):
584 self.module.fail_json(msg=self.rest_api.options_require_ontap_version('auto_enable_analytics', '9.12.1', use_rest=use_rest))
585 if use_rest and self.parameters.get('auto_enable_activity_tracking') is not None and \
586 not self.rest_api.meets_rest_minimum_version(use_rest, 9, 12, 1):
587 self.module.fail_json(msg=self.rest_api.options_require_ontap_version('auto_enable_activity_tracking', '9.12.1', use_rest=use_rest))
588 if use_rest and self.parameters.get('storage_limit') is not None and \
589 not self.rest_api.meets_rest_minimum_version(use_rest, 9, 13, 1):
590 self.module.fail_json(msg=self.rest_api.options_require_ontap_version('storage_limit', '9.13.1', use_rest=use_rest))
591 if use_rest and self.parameters.get('storage_limit_threshold_alert') is not None and \
592 not self.rest_api.meets_rest_minimum_version(use_rest, 9, 13, 1):
593 self.module.fail_json(msg=self.rest_api.options_require_ontap_version('storage_limit_threshold_alert', '9.13.1', use_rest=use_rest))
594 if use_rest and self.parameters.get('anti_ransomware_default_volume_state') is not None and \
595 not self.rest_api.meets_rest_minimum_version(use_rest, 9, 10, 1):
596 self.module.fail_json(msg=self.rest_api.options_require_ontap_version('anti_ransomware_default_volume_state', '9.10.1', use_rest=use_rest))
597 self.validate_int_or_string(self.parameters.get('max_volumes'), 'unlimited')
598 return use_rest
599
600 def clean_up_output(self, vserver_details):
601 vserver_details['root_volume'] = None
602 vserver_details['root_volume_aggregate'] = None
603 vserver_details['root_volume_security_style'] = None
604 vserver_details['aggr_list'] = [aggr['name'] for aggr in vserver_details['aggregates']]
605 vserver_details.pop('aggregates')
606 vserver_details['ipspace'] = vserver_details['ipspace']['name']
607 vserver_details['snapshot_policy'] = vserver_details['snapshot_policy']['name']
608 vserver_details['admin_state'] = vserver_details.pop('state')
609 if 'max_volumes' in vserver_details:
610 vserver_details['max_volumes'] = str(vserver_details['max_volumes'])
611 if vserver_details.get('web') is None and self.parameters.get('web'):
612 # force an entry to enable modify
613 vserver_details['web'] = {
614 'certificate': {
615 # ignore name, as only certificate UUID is supported in svm/svms/uuid/web
616 'uuid': vserver_details['certificate']['uuid'] if 'certificate' in vserver_details else None,
617 },
618 'client_enabled': None,
619 'ocsp_enabled': None
620 }
621
622 services = {}
623 # REST returns allowed: True/False with recent versions, and a list of protocols in allowed_protocols for older versions
624 allowed_protocols = (None if self.rest_api.meets_rest_minimum_version(self.use_rest, 9, 9, 1)
625 else vserver_details.get('allowed_protocols'))
626
627 for protocol in self.allowable_protocols_rest:
628 # protocols are not present when the vserver is stopped
629 allowed = self.na_helper.safe_get(vserver_details, [protocol, 'allowed'])
630 if allowed is None and allowed_protocols is not None:
631 # earlier ONTAP versions
632 allowed = protocol in allowed_protocols
633 enabled = self.na_helper.safe_get(vserver_details, [protocol, 'enabled'])
634 if allowed is not None or enabled is not None:
635 services[protocol] = {}
636 if allowed is not None:
637 services[protocol]['allowed'] = allowed
638 if enabled is not None:
639 services[protocol]['enabled'] = enabled
640
641 if services:
642 vserver_details['services'] = services
643
644 if 'storage' in vserver_details:
645 vserver_details['storage_limit'] = int(self.na_helper.safe_get(vserver_details, ['storage', 'limit']))
646 vserver_details['storage_limit_threshold_alert'] = int(self.na_helper.safe_get(vserver_details, ['storage', 'limit_threshold_alert']))
647
648 vserver_details['auto_enable_analytics'] = self.na_helper.safe_get(vserver_details, ['auto_enable_analytics'])
649 vserver_details['auto_enable_activity_tracking'] = self.na_helper.safe_get(vserver_details, ['auto_enable_activity_tracking'])
650 vserver_details['anti_ransomware_default_volume_state'] = self.na_helper.safe_get(vserver_details, ['anti_ransomware_default_volume_state'])
651
652 return vserver_details
653
654 def get_certificates(self, cert_type):
655 """Retrieve list of certificates"""
656 api = 'security/certificates'
657 query = {
658 'svm.name': self.parameters['name'],
659 'type': cert_type
660 }
661 records, error = rest_generic.get_0_or_more_records(self.rest_api, api, query)
662 if error:
663 self.module.fail_json(msg='Error retrieving certificates: %s' % error)
664 return [record['name'] for record in records] if records else []
665
666 def set_certificate_uuid(self):
667 """Retrieve certicate uuid for 9.8 or later"""
668 api = 'security/certificates'
669 query = {
670 'name': self.parameters['web']['certificate']['name'],
671 'svm.name': self.parameters['name'],
672 'type': 'server'
673 }
674 record, error = rest_generic.get_one_record(self.rest_api, api, query)
675 if error:
676 self.module.fail_json(msg='Error retrieving certificate %s: %s' % (self.parameters['web']['certificate'], error))
677 if not record:
678 self.module.fail_json(msg='Error certificate not found: %s. Current certificates with type=server: %s'
679 % (self.parameters['web']['certificate'], self.get_certificates('server')))
680 self.parameters['web']['certificate']['uuid'] = record['uuid']
681
682 def get_web_service(self, uuid):
683 """Retrieve web service info for 9.10.1 or later"""
684 api = 'svm/svms/%s/web' % uuid
685 record, error = rest_generic.get_one_record(self.rest_api, api)
686 if error:
687 self.module.fail_json(msg='Error retrieving web info: %s' % error)
688 return record
689
690 def get_vserver(self, vserver_name=None):
691 """
692 Checks if vserver exists.
693
694 :return:
695 vserver object if vserver found
696 None if vserver is not found
697 :rtype: object/None
698 """
699 if vserver_name is None:
700 vserver_name = self.parameters['name']
701
702 if self.use_rest:
703 fields = 'subtype,aggregates,language,snapshot_policy,ipspace,comment,nfs,cifs,fcp,iscsi,nvme,state,s3'
704 if self.rest_api.meets_rest_minimum_version(self.use_rest, 9, 9, 1):
705 fields += ',max_volumes'
706 if self.rest_api.meets_rest_minimum_version(self.use_rest, 9, 8, 0) and not self.rest_api.meets_rest_minimum_version(self.use_rest, 9, 10, 1):
707 # certificate is available starting with 9.7 and is deprecated with 9.10.1.
708 # we don't use certificate with 9.7 as name is only supported with 9.8 in /security/certificates
709 fields += ',certificate'
710 if self.rest_api.meets_rest_minimum_version(self.use_rest, 9, 10, 1):
711 fields += ',ndmp,anti_ransomware_default_volume_state'
712 if self.rest_api.meets_rest_minimum_version(self.use_rest, 9, 7, 0):
713 fields += ',s3'
714 if self.rest_api.meets_rest_minimum_version(self.use_rest, 9, 12, 1):
715 fields += ',auto_enable_analytics,auto_enable_activity_tracking'
716 if self.rest_api.meets_rest_minimum_version(self.use_rest, 9, 13, 1):
717 fields += ',storage'
718
719 record, error = rest_vserver.get_vserver(self.rest_api, vserver_name, fields)
720 if error:
721 self.module.fail_json(msg=error)
722 if record:
723 if self.parameters.get('web') and self.rest_api.meets_rest_minimum_version(self.use_rest, 9, 9, 1):
724 # only collect the info if the user wants to configure the web service, and ONTAP supports it
725 record['web'] = self.get_web_service(record['uuid'])
726 if not self.rest_api.meets_rest_minimum_version(self.use_rest, 9, 9, 1):
727 # 9.6 to 9.8 do not support max_volumes for svm/svms, using private/cli
728 record['allowed_protocols'], max_volumes = self.get_allowed_protocols_and_max_volumes()
729 if self.parameters.get('max_volumes') is not None:
730 record['max_volumes'] = max_volumes
731 return self.clean_up_output(copy.deepcopy(record))
732 return None
733
734 return zapis_svm.get_vserver(self.server, vserver_name)
735
736 def create_vserver(self):
737 if self.use_rest:
738 self.create_vserver_rest()
739 else:
740 options = {'vserver-name': self.parameters['name']}
741 self.add_parameter_to_dict(options, 'root_volume', 'root-volume')
742 self.add_parameter_to_dict(options, 'root_volume_aggregate', 'root-volume-aggregate')
743 self.add_parameter_to_dict(options, 'root_volume_security_style', 'root-volume-security-style')
744 self.add_parameter_to_dict(options, 'language', 'language')
745 self.add_parameter_to_dict(options, 'ipspace', 'ipspace')
746 self.add_parameter_to_dict(options, 'snapshot_policy', 'snapshot-policy')
747 self.add_parameter_to_dict(options, 'subtype', 'vserver-subtype')
748 self.add_parameter_to_dict(options, 'comment', 'comment')
749 vserver_create = netapp_utils.zapi.NaElement.create_node_with_children('vserver-create', **options)
750 try:
751 self.server.invoke_successfully(vserver_create,
752 enable_tunneling=False)
753 except netapp_utils.zapi.NaApiError as exc:
754 self.module.fail_json(msg='Error provisioning SVM %s: %s'
755 % (self.parameters['name'], to_native(exc)),
756 exception=traceback.format_exc())
757 # add allowed-protocols, aggr-list, max_volume after creation
758 # since vserver-create doesn't allow these attributes during creation
759 # python 2.6 does not support dict comprehension {k: v for ...}
760 options = dict(
761 (key, self.parameters[key])
762 for key in ('allowed_protocols', 'aggr_list', 'max_volumes')
763 if self.parameters.get(key)
764 )
765 if options:
766 self.modify_vserver(options)
767
768 def create_body_contents(self, modify=None):
769 keys_to_modify = self.parameters.keys() if modify is None else modify.keys()
770 protocols_to_modify = self.parameters.get('services', {}) if modify is None else modify.get('services', {})
771 simple_keys = ['name', 'language', 'ipspace', 'snapshot_policy', 'subtype', 'comment']
772 if self.rest_api.meets_rest_minimum_version(self.use_rest, 9, 9, 1):
773 simple_keys.append('max_volumes')
774 if self.rest_api.meets_rest_minimum_version(self.use_rest, 9, 10, 1):
775 simple_keys.append('anti_ransomware_default_volume_state')
776 body = dict(
777 (key, self.parameters[key])
778 for key in simple_keys
779 if self.parameters.get(key) and key in keys_to_modify
780 )
781 # admin_state is only supported in modify
782 if modify and 'admin_state' in keys_to_modify:
783 body['state'] = self.parameters['admin_state']
784 if 'aggr_list' in keys_to_modify:
785 body['aggregates'] = [{'name': aggr} for aggr in self.parameters['aggr_list']]
786 if 'certificate' in keys_to_modify:
787 body['certificate'] = modify['certificate']
788 allowed_protocols = {}
789 for protocol, config in protocols_to_modify.items():
790 # Ansible sets unset suboptions to None
791 if not config:
792 continue
793 # Ansible sets unset suboptions to None
794 acopy = self.na_helper.filter_out_none_entries(config)
795 if modify is not None:
796 # REST does not allow to modify this directly
797 acopy.pop('enabled', None)
798 if not self.rest_api.meets_rest_minimum_version(self.use_rest, 9, 9, 1):
799 # allowed is not supported in earlier REST versions
800 allowed = acopy.pop('allowed', None)
801 # if allowed is not set, retrieve current value
802 if allowed is not None:
803 allowed_protocols[protocol] = allowed
804 if acopy:
805 body[protocol] = acopy
806 if 'auto_enable_analytics' in keys_to_modify:
807 body['auto_enable_analytics'] = self.parameters['auto_enable_analytics']
808 if 'auto_enable_activity_tracking' in keys_to_modify:
809 body['auto_enable_activity_tracking'] = self.parameters['auto_enable_activity_tracking']
810 if 'storage_limit' in keys_to_modify:
811 body['storage.limit'] = self.parameters['storage_limit']
812 if 'storage_limit_threshold_alert' in keys_to_modify:
813 body['storage.limit_threshold_alert'] = self.parameters['storage_limit_threshold_alert']
814 return body, allowed_protocols
815
816 def get_allowed_protocols_and_max_volumes(self):
817 # use REST CLI for older versions of ONTAP
818 query = {'vserver': self.parameters['name']}
819 fields = 'allowed_protocols'
820 if self.parameters.get('max_volumes') is not None:
821 fields += ',max_volumes'
822 response, error = rest_generic.get_one_record(self.rest_api, 'private/cli/vserver', query, fields)
823 if error:
824 self.module.fail_json(msg='Error getting vserver info: %s - %s' % (error, response))
825 if response and 'max_volumes' in response:
826 max_volumes = str(response['max_volumes'])
827 allowed_protocols, max_volumes = [], None
828 if response and 'allowed_protocols' in response:
829 allowed_protocols = response['allowed_protocols']
830 if response and 'max_volumes' in response:
831 max_volumes = str(response['max_volumes'])
832 return allowed_protocols, max_volumes
833
834 def rest_cli_set_max_volumes(self):
835 # use REST CLI for older versions of ONTAP
836 query = {'vserver': self.parameters['name']}
837 body = {'max_volumes': self.parameters['max_volumes']}
838 response, error = rest_generic.patch_async(self.rest_api, 'private/cli/vserver', None, body, query)
839 if error:
840 self.module.fail_json(msg='Error updating max_volumes: %s - %s' % (error, response))
841
842 def rest_cli_add_remove_protocols(self, protocols):
843 protocols_to_add = [protocol for protocol, value in protocols.items() if value]
844 if protocols_to_add:
845 self.rest_cli_add_protocols(protocols_to_add)
846 protocols_to_delete = [protocol for protocol, value in protocols.items() if not value]
847 if protocols_to_delete:
848 self.rest_cli_remove_protocols(protocols_to_delete)
849
850 def rest_cli_add_protocols(self, protocols):
851 # use REST CLI for older versions of ONTAP
852 query = {'vserver': self.parameters['name']}
853 body = {'protocols': protocols}
854 response, error = rest_generic.patch_async(self.rest_api, 'private/cli/vserver/add-protocols', None, body, query)
855 if error:
856 self.module.fail_json(msg='Error adding protocols: %s - %s' % (error, response))
857
858 def rest_cli_remove_protocols(self, protocols):
859 # use REST CLI for older versions of ONTAP
860 query = {'vserver': self.parameters['name']}
861 body = {'protocols': protocols}
862 response, error = rest_generic.patch_async(self.rest_api, 'private/cli/vserver/remove-protocols', None, body, query)
863 if error:
864 self.module.fail_json(msg='Error removing protocols: %s - %s' % (error, response))
865
866 def create_vserver_rest(self):
867 # python 2.6 does not support dict comprehension {k: v for ...}
868 body, allowed_protocols = self.create_body_contents()
869 dummy, error = rest_generic.post_async(self.rest_api, 'svm/svms', body, timeout=self.timeout)
870 if error:
871 self.module.fail_json(msg='Error in create: %s' % error)
872 # add max_volumes and update allowed protocols after creation for older ONTAP versions
873 if self.parameters.get('max_volumes') is not None and not self.rest_api.meets_rest_minimum_version(self.use_rest, 9, 9, 1):
874 self.rest_cli_set_max_volumes()
875 if allowed_protocols:
876 self.rest_cli_add_remove_protocols(allowed_protocols)
877
878 def delete_vserver(self, current=None):
879 if self.use_rest:
880 if current is None:
881 self.module.fail_json(msg='Internal error, expecting SVM object in delete')
882 dummy, error = rest_generic.delete_async(self.rest_api, 'svm/svms', current['uuid'], timeout=self.timeout)
883 if error:
884 self.module.fail_json(msg='Error in delete: %s' % error)
885 else:
886 vserver_delete = netapp_utils.zapi.NaElement.create_node_with_children(
887 'vserver-destroy', **{'vserver-name': self.parameters['name']})
888
889 try:
890 self.server.invoke_successfully(vserver_delete,
891 enable_tunneling=False)
892 except netapp_utils.zapi.NaApiError as exc:
893 self.module.fail_json(msg='Error deleting SVM %s: %s'
894 % (self.parameters['name'], to_native(exc)),
895 exception=traceback.format_exc())
896
897 def rename_vserver(self):
898 ''' ZAPI only, for REST it is handled as a modify'''
899 vserver_rename = netapp_utils.zapi.NaElement.create_node_with_children(
900 'vserver-rename', **{'vserver-name': self.parameters['from_name'],
901 'new-name': self.parameters['name']})
902
903 try:
904 self.server.invoke_successfully(vserver_rename,
905 enable_tunneling=False)
906 except netapp_utils.zapi.NaApiError as exc:
907 self.module.fail_json(msg='Error renaming SVM %s: %s'
908 % (self.parameters['from_name'], to_native(exc)),
909 exception=traceback.format_exc())
910
911 def modify_vserver(self, modify, current=None):
912 '''
913 Modify vserver.
914 :param modify: list of modify attributes
915 :param current: with rest, SVM object to modify
916 '''
917 if self.use_rest:
918 if current is None:
919 self.module.fail_json(msg='Internal error, expecting SVM object in modify.')
920 if not modify:
921 self.module.fail_json(msg='Internal error, expecting something to modify in modify.')
922 # REST reports an error if we modify the name and something else at the same time
923 if 'name' in modify:
924 body = {'name': modify['name']}
925 dummy, error = rest_generic.patch_async(self.rest_api, 'svm/svms', current['uuid'], body, timeout=self.timeout)
926 if error:
927 self.module.fail_json(msg='Error in rename: %s' % error, modify=modify)
928 del modify['name']
929 if 'web' in modify and not self.rest_api.meets_rest_minimum_version(self.use_rest, 9, 10, 1):
930 # certificate is a deprecated field for 9.10.1, only use it for 9.8 and 9.9
931 uuid = self.na_helper.safe_get(modify, ['web', 'certificate', 'uuid'])
932 if uuid:
933 modify['certificate'] = {'uuid': uuid}
934 modify.pop('web')
935 body, allowed_protocols = self.create_body_contents(modify)
936 if body:
937 dummy, error = rest_generic.patch_async(self.rest_api, 'svm/svms', current['uuid'], body, timeout=self.timeout)
938 if error:
939 self.module.fail_json(msg='Error in modify: %s' % error, modify=modify)
940 # use REST CLI for max_volumes and allowed protocols with older ONTAP versions
941 if 'max_volumes' in modify and not self.rest_api.meets_rest_minimum_version(self.use_rest, 9, 9, 1):
942 self.rest_cli_set_max_volumes()
943 if allowed_protocols:
944 self.rest_cli_add_remove_protocols(allowed_protocols)
945 if 'services' in modify:
946 self.modify_services(modify, current)
947 if 'web' in modify and self.rest_api.meets_rest_minimum_version(self.use_rest, 9, 10, 1):
948 self.modify_web_services(modify['web'], current)
949 else:
950 zapis_svm.modify_vserver(self.server, self.module, self.parameters['name'], modify, self.parameters)
951
952 def modify_services(self, modify, current):
953 apis = {
954 'fcp': 'protocols/san/fcp/services',
955 'iscsi': 'protocols/san/iscsi/services',
956 'nfs': 'protocols/nfs/services',
957 'nvme': 'protocols/nvme/services',
958 'ndmp': 'protocols/ndmp/svms'
959 }
960 for protocol, config in modify['services'].items():
961 enabled = config.get('enabled')
962 if enabled is None:
963 # nothing to do
964 continue
965 api = apis.get(protocol)
966 if not api:
967 self.module.fail_json(msg='Internal error, unexpecting service: %s.' % protocol)
968 if enabled:
969 # we don't know if the service is already started or not, link will tell us
970 link = self.na_helper.safe_get(current, [protocol, '_links', 'self', 'href'])
971 body = {'enabled': enabled}
972 if enabled and not link:
973 body['svm.name'] = self.parameters['name']
974 dummy, error = rest_generic.post_async(self.rest_api, api, body)
975 else:
976 dummy, error = rest_generic.patch_async(self.rest_api, api, current['uuid'], body)
977 if error:
978 self.module.fail_json(msg='Error in modify service for %s: %s' % (protocol, error))
979
980 def modify_web_services(self, record, current):
981 """Patch web service for 9.10.1 or later"""
982 api = 'svm/svms/%s/web' % current['uuid']
983 if 'certificate' in record:
984 # API only accepts a UUID
985 record['certificate'].pop('name', None)
986 body = self.na_helper.filter_out_none_entries(copy.deepcopy(record))
987 if not body:
988 self.module.warn('Nothing to change: %s' % record)
989 return
990 dummy, error = rest_generic.patch_async(self.rest_api, api, None, body)
991 if error:
992 self.module.fail_json(msg='Error in modify web service for %s: %s' % (body, error))
993
994 def add_parameter_to_dict(self, adict, name, key=None, tostr=False):
995 '''
996 add defined parameter (not None) to adict using key.
997 :param adict: a dictionary.
998 :param name: name in self.parameters.
999 :param key: key in adict.
1000 :param tostr: boolean.
1001 '''
1002 if key is None:
1003 key = name
1004 if self.parameters.get(name) is not None:
1005 if tostr:
1006 adict[key] = str(self.parameters.get(name))
1007 else:
1008 adict[key] = self.parameters.get(name)
1009
1010 def warn_when_possible_language_match(self, desired, current):
1011 transformed = desired.lower().replace('-', '_')
1012 if transformed == current:
1013 self.module.warn("Attempting to change language from ONTAP value %s to %s. Use %s to suppress this warning and maintain idempotency."
1014 % (current, desired, current))
1015
1016 def apply(self):
1017 '''Call create/modify/delete operations.'''
1018 current = self.get_vserver()
1019 cd_action, rename = None, None
1020 cd_action = self.na_helper.get_cd_action(current, self.parameters)
1021 if cd_action == 'create' and self.parameters.get('from_name'):
1022 # create by renaming existing SVM
1023 old_svm = self.get_vserver(self.parameters['from_name'])
1024 rename = self.na_helper.is_rename_action(old_svm, current)
1025 if rename is None:
1026 self.module.fail_json(msg='Error renaming SVM %s: no SVM with from_name %s.' % (self.parameters['name'], self.parameters['from_name']))
1027 if rename:
1028 current = old_svm
1029 cd_action = None
1030 modify = self.na_helper.get_modified_attributes(current, self.parameters) if cd_action is None else {}
1031 if 'language' in modify:
1032 self.warn_when_possible_language_match(modify['language'], current['language'])
1033 fixed_attributes = ['root_volume', 'root_volume_aggregate', 'root_volume_security_style', 'subtype', 'ipspace']
1034 msgs = ['%s - current: %s - desired: %s' % (attribute, current[attribute], self.parameters[attribute])
1035 for attribute in fixed_attributes
1036 if attribute in modify]
1037 if msgs:
1038 self.module.fail_json(msg='Error modifying SVM %s: cannot modify %s.' % (self.parameters['name'], ', '.join(msgs)))
1039
1040 if self.na_helper.changed and not self.module.check_mode:
1041 if rename:
1042 if self.use_rest:
1043 modify['name'] = self.parameters['name']
1044 else:
1045 self.rename_vserver()
1046 modify.pop('name', None)
1047 # If rename is True, cd_action is None, but modify could be true or false.
1048 if cd_action == 'create':
1049 self.create_vserver()
1050 if self.parameters.get('admin_state') == 'stopped':
1051 current = self.get_vserver()
1052 modify = {'admin_state': 'stopped'}
1053 elif cd_action == 'delete':
1054 self.delete_vserver(current)
1055 if modify:
1056 self.modify_vserver(modify, current)
1057 if modify and 'aggr_list' in modify and '*' in modify['aggr_list']:
1058 self.module.warn("na_ontap_svm: changed always 'True' when aggr_list is '*'.")
1059 results = netapp_utils.generate_result(self.na_helper.changed, cd_action, modify)
1060 self.module.exit_json(**results)
1061
1062
1063 def main():
1064 '''Apply vserver operations from playbook'''
1065 svm = NetAppOntapSVM()
1066 svm.apply()
1067
1068
1069 if __name__ == '__main__':
1070 main()