Debian Codegraph @

ansible_collections/netapp/ontap/plugins/modules/na_ontap_snapshot_policy.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 from __future__ import absolute_import, division, print_function
8 __metaclass__ = type
9
10
11 ANSIBLE_METADATA = {'metadata_version': '1.1',
12 'status': ['preview'],
13 'supported_by': 'community'}
14
15 DOCUMENTATION = '''
16 module: na_ontap_snapshot_policy
17 short_description: NetApp ONTAP manage Snapshot Policy
18 extends_documentation_fragment:
19 - netapp.ontap.netapp.na_ontap
20 version_added: 2.8.0
21 author: NetApp Ansible Team (@carchi8py) <[email protected]>
22 description:
23 - Create/Modify/Delete ONTAP snapshot policies
24 options:
25 state:
26 description:
27 - If you want to create, modify or delete a snapshot policy.
28 choices: ['present', 'absent']
29 type: str
30 default: present
31 name:
32 description:
33 Name of the snapshot policy to be managed.
34 The maximum string length is 256 characters.
35 required: true
36 type: str
37 enabled:
38 description:
39 - Status of the snapshot policy indicating whether the policy will be enabled or disabled.
40 type: bool
41 comment:
42 description:
43 A human readable comment attached with the snapshot.
44 The size of the comment can be at most 255 characters.
45 type: str
46 count:
47 description:
48 Retention count for the snapshots created by the schedule.
49 type: list
50 elements: int
51 schedule:
52 description:
53 - Schedule to be added inside the policy.
54 type: list
55 elements: str
56 prefix:
57 description:
58 - Snapshot name prefix for the schedule.
59 - Prefix name should be unique within the policy.
60 - Cannot set a different prefix to a schedule that has already been assigned to a snapshot policy.
61 - Prefix cannot be modifed after schedule has been added.
62 type: list
63 elements: str
64 required: false
65 version_added: '19.11.0'
66 snapmirror_label:
67 description:
68 - SnapMirror label assigned to each schedule inside the policy. Use an empty
69 string ('') for no label.
70 type: list
71 elements: str
72 required: false
73 version_added: 2.9.0
74 retention_period:
75 description:
76 - The retention period of Snapshot copies for the schedule.
77 - Valid values are "infinite" or the duration specified in ISO 8601 format.
78 - The value when specified in ISO 8061 format for retention period must be in
79 seconds (PT0S - PT65535S), minutes (PT0M - PT60M), hours (PT0H - PT24H),
80 days (P0D - P36500D), months (P0M - P1200M), years (P0Y - P100Y).
81 - Supported only with REST and requires ONTAP 9.12 or later.
82 type: list
83 elements: str
84 required: false
85 version_added: '22.12.0'
86 vserver:
87 description:
88 - The name of the vserver to use. In a multi-tenanted environment, assigning a
89 Snapshot Policy to a vserver will restrict its use to that vserver.
90 required: false
91 type: str
92 version_added: 2.9.0
93 lambda_config:
94 description:
95 - Configuration parameters for AWS Lambda proxy functionality.
96 - These option and suboptions are only supported with REST.
97 type: dict
98 version_added: 23.5.0
99 suboptions:
100 function_name:
101 description:
102 - The name of the AWS Lambda function to invoke.
103 type: str
104 required: true
105 aws_region:
106 description:
107 - The name of the AWS region.
108 type: str
109 required: true
110 aws_profile:
111 description:
112 - The name of the AWS profile to use for authentication.
113 type: str
114
115 notes:
116 - Supports AWS Lambda proxy functionality when using REST. See the README file for examples.
117 '''
118 EXAMPLES = """
119 - name: Create Snapshot policy
120 netapp.ontap.na_ontap_snapshot_policy:
121 state: present
122 name: ansible2
123 schedule: hourly
124 prefix: hourly
125 count: 150
126 enabled: true
127 username: "{{ netapp_username }}"
128 password: "{{ netapp_password }}"
129 hostname: "{{ netapp_hostname }}"
130 https: false
131
132 - name: Create Snapshot policy with multiple schedules
133 netapp.ontap.na_ontap_snapshot_policy:
134 state: present
135 name: ansible2
136 schedule: ['hourly', 'daily', 'weekly', 'monthly', '5min']
137 prefix: ['hourly', 'daily', 'weekly', 'monthly', '5min']
138 count: [1, 2, 3, 4, 5]
139 enabled: true
140 username: "{{ netapp_username }}"
141 password: "{{ netapp_password }}"
142 hostname: "{{ netapp_hostname }}"
143 https: false
144
145 - name: Create Snapshot policy owned by a vserver
146 netapp.ontap.na_ontap_snapshot_policy:
147 state: present
148 name: ansible3
149 vserver: ansible
150 schedule: ['hourly', 'daily', 'weekly', 'monthly', '5min']
151 prefix: ['hourly', 'daily', 'weekly', 'monthly', '5min']
152 count: [1, 2, 3, 4, 5]
153 snapmirror_label: ['hourly', 'daily', 'weekly', 'monthly', '']
154 enabled: true
155 username: "{{ netapp_username }}"
156 password: "{{ netapp_password }}"
157 hostname: "{{ netapp_hostname }}"
158 https: false
159
160 - name: Modify Snapshot policy with multiple schedules
161 netapp.ontap.na_ontap_snapshot_policy:
162 state: present
163 name: ansible2
164 schedule: ['daily', 'weekly']
165 count: [20, 30]
166 snapmirror_label: ['daily', 'weekly']
167 enabled: true
168 username: "{{ netapp_username }}"
169 password: "{{ netapp_password }}"
170 hostname: "{{ netapp_hostname }}"
171 https: false
172
173 - name: Delete Snapshot policy
174 netapp.ontap.na_ontap_snapshot_policy:
175 state: absent
176 name: ansible2
177 username: "{{ netapp_username }}"
178 password: "{{ netapp_password }}"
179 hostname: "{{ netapp_hostname }}"
180 https: false
181 """
182
183 RETURN = """
184 """
185 import traceback
186
187 from ansible.module_utils.basic import AnsibleModule
188 from ansible.module_utils._text import to_native
189 import ansible_collections.netapp.ontap.plugins.module_utils.netapp as netapp_utils
190 from ansible_collections.netapp.ontap.plugins.module_utils.netapp_module import NetAppModule
191 from ansible_collections.netapp.ontap.plugins.module_utils.netapp import OntapRestAPI
192 from ansible_collections.netapp.ontap.plugins.module_utils import rest_generic
193
194
195 class NetAppOntapSnapshotPolicy(object):
196 """
197 Creates and deletes a Snapshot Policy
198 """
199
200 def __init__(self):
201 self.argument_spec = netapp_utils.na_ontap_host_argument_spec()
202 self.argument_spec.update(dict(
203 state=dict(required=False, type='str', choices=['present', 'absent'], default='present'),
204 name=dict(required=True, type="str"),
205 enabled=dict(required=False, type="bool"),
206 # count is a list of integers
207 count=dict(required=False, type="list", elements="int"),
208 comment=dict(required=False, type="str"),
209 schedule=dict(required=False, type="list", elements="str"),
210 prefix=dict(required=False, type="list", elements="str"),
211 snapmirror_label=dict(required=False, type="list", elements="str"),
212 retention_period=dict(required=False, type="list", elements="str"),
213 vserver=dict(required=False, type="str")
214 ))
215 self.argument_spec.update(netapp_utils.na_ontap_lambda_argument_spec())
216 self.module = AnsibleModule(
217 argument_spec=self.argument_spec,
218 required_if=[
219 ('state', 'present', ['enabled', 'count', 'schedule']),
220 ('use_lambda', True, ['lambda_config']),
221 ],
222 supports_check_mode=True
223 )
224
225 self.na_helper = NetAppModule()
226 self.parameters = self.na_helper.set_parameters(self.module.params)
227 # Set up Rest API
228 self.rest_api = OntapRestAPI(self.module)
229 partially_supported_rest_properties = [['retention_period', (9, 12, 1)]]
230 unsupported_zapi_properties = ['retention_period']
231 self.use_rest = self.rest_api.is_rest_supported_properties(self.parameters, partially_supported_rest_properties=partially_supported_rest_properties)
232 if self.use_rest and not self.rest_api.meets_rest_minimum_version(self.use_rest, 9, 8, 0):
233 msg = 'REST requires ONTAP 9.8 or later for snapshot schedules.'
234 self.use_rest = self.na_helper.fall_back_to_zapi(self.module, msg, self.parameters)
235 if not self.use_rest:
236 if self.parameters.get('use_lambda'):
237 self.module.fail_json(msg="Error: AWS Lambda proxy for ONTAP APIs is only supported with REST.")
238 if not netapp_utils.has_netapp_lib():
239 self.module.fail_json(msg=netapp_utils.netapp_lib_is_required())
240 used_unsupported_zapi_properties = [option for option in unsupported_zapi_properties if option in self.parameters]
241 if used_unsupported_zapi_properties:
242 self.module.fail_json(msg="Error: %s options supported only with REST." % " ,".join(used_unsupported_zapi_properties))
243 if 'vserver' in self.parameters:
244 self.server = netapp_utils.setup_na_ontap_zapi(module=self.module, vserver=self.parameters['vserver'])
245 else:
246 self.server = netapp_utils.setup_na_ontap_zapi(module=self.module)
247
248 def safe_strip(self, option):
249 """ strip the given string """
250 return option.strip() if option is not None else None
251
252 def get_snapshot_policy(self):
253 """
254 Checks to see if a snapshot policy exists or not
255 :return: Return policy details if a snapshot policy exists, None if it doesn't
256 """
257 snapshot_obj = netapp_utils.zapi.NaElement("snapshot-policy-get-iter")
258 # compose query
259 query = netapp_utils.zapi.NaElement("query")
260 snapshot_info_obj = netapp_utils.zapi.NaElement("snapshot-policy-info")
261 snapshot_info_obj.add_new_child("policy", self.parameters['name'])
262 if 'vserver' in self.parameters:
263 snapshot_info_obj.add_new_child("vserver-name", self.parameters['vserver'])
264 query.add_child_elem(snapshot_info_obj)
265 snapshot_obj.add_child_elem(query)
266 try:
267 result = self.server.invoke_successfully(snapshot_obj, True)
268 if result.get_child_by_name('num-records') and \
269 int(result.get_child_content('num-records')) == 1:
270 snapshot_policy = result.get_child_by_name('attributes-list').get_child_by_name('snapshot-policy-info')
271 current = {'name': snapshot_policy.get_child_content('policy')}
272 current['vserver'] = snapshot_policy.get_child_content('vserver-name')
273 current['enabled'] = snapshot_policy.get_child_content('enabled').lower() != 'false'
274 current['comment'] = snapshot_policy.get_child_content('comment') or ''
275 current['schedule'], current['count'], current['snapmirror_label'], current['prefix'] = [], [], [], []
276 if snapshot_policy.get_child_by_name('snapshot-policy-schedules'):
277 for schedule in snapshot_policy['snapshot-policy-schedules'].get_children():
278 current['schedule'].append(schedule.get_child_content('schedule'))
279 current['count'].append(int(schedule.get_child_content('count')))
280
281 snapmirror_label = schedule.get_child_content('snapmirror-label')
282 if snapmirror_label is None or snapmirror_label == '-':
283 snapmirror_label = ''
284 current['snapmirror_label'].append(snapmirror_label)
285
286 prefix = schedule.get_child_content('prefix')
287 if prefix is None or prefix == '-':
288 prefix = ''
289 current['prefix'].append(prefix)
290 return current
291 except netapp_utils.zapi.NaApiError as error:
292 self.module.fail_json(msg=to_native(error), exception=traceback.format_exc())
293 return None
294
295 def validate_parameters(self):
296 """
297 Validate if each schedule has a count associated
298 :return: None
299 """
300 if 'count' not in self.parameters or 'schedule' not in self.parameters or \
301 len(self.parameters['count']) > 5 or len(self.parameters['schedule']) > 5 or \
302 len(self.parameters['count']) < 1 or len(self.parameters['schedule']) < 1 or \
303 len(self.parameters['count']) != len(self.parameters['schedule']):
304 self.module.fail_json(msg="Error: A Snapshot policy must have at least 1 "
305 "schedule and can have up to a maximum of 5 schedules, with a count "
306 "representing the maximum number of Snapshot copies for each schedule")
307
308 if 'snapmirror_label' in self.parameters and len(self.parameters['snapmirror_label']) != len(self.parameters['schedule']):
309 self.module.fail_json(msg="Error: Each Snapshot Policy schedule must have an accompanying SnapMirror Label")
310
311 if 'prefix' in self.parameters and len(self.parameters['prefix']) != len(self.parameters['schedule']):
312 self.module.fail_json(msg="Error: Each Snapshot Policy schedule must have an accompanying prefix")
313
314 def modify_snapshot_policy(self, current):
315 """
316 Modifies an existing snapshot policy
317 """
318 # Set up required variables to modify snapshot policy
319 options = {'policy': self.parameters['name']}
320 modify = False
321
322 # Set up optional variables to modify snapshot policy
323 if 'enabled' in self.parameters and self.parameters['enabled'] != current['enabled']:
324 options['enabled'] = str(self.parameters['enabled'])
325 modify = True
326 if 'comment' in self.parameters and self.parameters['comment'] != current['comment']:
327 options['comment'] = self.parameters['comment']
328 modify = True
329
330 if modify:
331 snapshot_obj = netapp_utils.zapi.NaElement.create_node_with_children('snapshot-policy-modify', **options)
332 try:
333 self.server.invoke_successfully(snapshot_obj, True)
334 except netapp_utils.zapi.NaApiError as error:
335 self.module.fail_json(msg='Error modifying snapshot policy %s: %s' %
336 (self.parameters['name'], to_native(error)),
337 exception=traceback.format_exc())
338
339 def modify_snapshot_policy_schedules(self, current):
340 """
341 Modify existing schedules in snapshot policy
342 :return: None
343 """
344 self.validate_parameters()
345 delete_schedules, modify_schedules, add_schedules = [], [], []
346
347 if 'snapmirror_label' in self.parameters:
348 snapmirror_labels = self.parameters['snapmirror_label']
349 else:
350 # User hasn't supplied any snapmirror labels.
351 snapmirror_labels = [None] * len(self.parameters['schedule'])
352
353 # Identify schedules for deletion
354 for schedule in current['schedule']:
355 schedule = self.safe_strip(schedule)
356 if schedule not in [item.strip() for item in self.parameters['schedule']]:
357 options = {'policy': current['name'],
358 'schedule': schedule}
359 delete_schedules.append(options)
360
361 # Identify schedules to be modified or added
362 for schedule, count, snapmirror_label in zip(self.parameters['schedule'], self.parameters['count'], snapmirror_labels):
363 schedule = self.safe_strip(schedule)
364 snapmirror_label = self.safe_strip(snapmirror_label)
365
366 options = {'policy': current['name'],
367 'schedule': schedule}
368
369 if schedule in current['schedule']:
370 # Schedule exists. Only modify if it has changed.
371 modify = False
372 schedule_index = current['schedule'].index(schedule)
373
374 if count != current['count'][schedule_index]:
375 options['new-count'] = str(count)
376 modify = True
377
378 if snapmirror_label is not None and snapmirror_label != current['snapmirror_label'][schedule_index]:
379 options['new-snapmirror-label'] = snapmirror_label
380 modify = True
381
382 if modify:
383 modify_schedules.append(options)
384 else:
385 # New schedule
386 options['count'] = str(count)
387 if snapmirror_label is not None and snapmirror_label != '':
388 options['snapmirror-label'] = snapmirror_label
389 add_schedules.append(options)
390
391 # Delete N-1 schedules no longer required. Must leave 1 schedule in policy
392 # at any one time. Delete last one afterwards.
393 while len(delete_schedules) > 1:
394 options = delete_schedules.pop()
395 self.modify_snapshot_policy_schedule(options, 'snapshot-policy-remove-schedule')
396
397 # Modify schedules.
398 while modify_schedules:
399 options = modify_schedules.pop()
400 self.modify_snapshot_policy_schedule(options, 'snapshot-policy-modify-schedule')
401
402 # Add 1 new schedule. Add other ones after last schedule has been deleted.
403 if add_schedules:
404 options = add_schedules.pop()
405 self.modify_snapshot_policy_schedule(options, 'snapshot-policy-add-schedule')
406
407 # Delete last schedule no longer required.
408 while delete_schedules:
409 options = delete_schedules.pop()
410 self.modify_snapshot_policy_schedule(options, 'snapshot-policy-remove-schedule')
411
412 # Add remaining new schedules.
413 while add_schedules:
414 options = add_schedules.pop()
415 self.modify_snapshot_policy_schedule(options, 'snapshot-policy-add-schedule')
416
417 def modify_snapshot_policy_schedule(self, options, zapi):
418 """
419 Add, modify or remove a schedule to/from a snapshot policy
420 """
421 snapshot_obj = netapp_utils.zapi.NaElement.create_node_with_children(zapi, **options)
422 try:
423 self.server.invoke_successfully(snapshot_obj, enable_tunneling=True)
424 except netapp_utils.zapi.NaApiError as error:
425 self.module.fail_json(msg='Error modifying snapshot policy schedule %s: %s' %
426 (self.parameters['name'], to_native(error)),
427 exception=traceback.format_exc())
428
429 def create_snapshot_policy(self):
430 """
431 Creates a new snapshot policy
432 """
433 # set up required variables to create a snapshot policy
434 self.validate_parameters()
435 options = {'policy': self.parameters['name'],
436 'enabled': str(self.parameters['enabled']),
437 }
438
439 if 'snapmirror_label' in self.parameters:
440 snapmirror_labels = self.parameters['snapmirror_label']
441 else:
442 # User hasn't supplied any snapmirror labels.
443 snapmirror_labels = [None] * len(self.parameters['schedule'])
444
445 if 'prefix' in self.parameters:
446 prefixes = self.parameters['prefix']
447 else:
448 # User hasn't supplied any prefixes.
449 prefixes = [None] * len(self.parameters['schedule'])
450
451 # zapi attribute for first schedule is schedule1, second is schedule2 and so on
452 positions = [str(i) for i in range(1, len(self.parameters['schedule']) + 1)]
453 for schedule, prefix, count, snapmirror_label, position in \
454 zip(self.parameters['schedule'], prefixes,
455 self.parameters['count'], snapmirror_labels, positions):
456 schedule = self.safe_strip(schedule)
457 options['count' + position] = str(count)
458 options['schedule' + position] = schedule
459 snapmirror_label = self.safe_strip(snapmirror_label)
460 if snapmirror_label:
461 options['snapmirror-label' + position] = snapmirror_label
462 prefix = self.safe_strip(prefix)
463 if prefix:
464 options['prefix' + position] = prefix
465
466 snapshot_obj = netapp_utils.zapi.NaElement.create_node_with_children('snapshot-policy-create', **options)
467
468 # Set up optional variables to create a snapshot policy
469 if self.parameters.get('comment'):
470 snapshot_obj.add_new_child("comment", self.parameters['comment'])
471 try:
472 self.server.invoke_successfully(snapshot_obj, True)
473 except netapp_utils.zapi.NaApiError as error:
474 self.module.fail_json(msg='Error creating snapshot policy %s: %s' %
475 (self.parameters['name'], to_native(error)),
476 exception=traceback.format_exc())
477
478 def delete_snapshot_policy(self):
479 """
480 Deletes an existing snapshot policy
481 """
482 snapshot_obj = netapp_utils.zapi.NaElement("snapshot-policy-delete")
483
484 # Set up required variables to delete a snapshot policy
485 snapshot_obj.add_new_child("policy", self.parameters['name'])
486 try:
487 self.server.invoke_successfully(snapshot_obj, True)
488 except netapp_utils.zapi.NaApiError as error:
489 self.module.fail_json(msg='Error deleting snapshot policy %s: %s' %
490 (self.parameters['name'], to_native(error)),
491 exception=traceback.format_exc())
492
493 def asup_log_for_cserver(self, event_name):
494 """
495 Fetch admin vserver for the given cluster
496 Create and Autosupport log event with the given module name
497 :param event_name: Name of the event log
498 :return: None
499 """
500 if 'vserver' in self.parameters:
501 netapp_utils.ems_log_event(event_name, self.server)
502 else:
503 results = netapp_utils.get_cserver(self.server)
504 cserver = netapp_utils.setup_na_ontap_zapi(module=self.module, vserver=results)
505 netapp_utils.ems_log_event(event_name, cserver)
506
507 # REST API support for create, delete and modify snapshot policy
508 def get_snapshot_schedule_rest(self, current):
509 """
510 get details of the snapshot schedule with rest API.
511 """
512 query = {'snapshot_policy.name': current['name']}
513 api = 'storage/snapshot-policies/%s/schedules' % current['uuid']
514 fields = 'schedule.name,schedule.uuid,snapmirror_label,count,prefix,'
515 if self.parameters.get('retention_period') is not None:
516 fields += 'retention_period,'
517 records, error = rest_generic.get_0_or_more_records(self.rest_api, api, query, fields)
518 if error:
519 self.module.fail_json(msg="Error on fetching snapshot schedule: %s" % error)
520 if records:
521 scheduleRecords = {
522 'counts': [],
523 'prefixes': [],
524 'schedule_names': [],
525 'schedule_uuids': [],
526 'snapmirror_labels': []
527 }
528 if self.parameters.get('retention_period') is not None:
529 scheduleRecords.update({'retention_periods': []})
530 for item in records:
531 scheduleRecords['counts'].append(item['count'])
532 scheduleRecords['prefixes'].append(item['prefix'])
533 scheduleRecords['schedule_names'].append(item['schedule']['name'])
534 scheduleRecords['schedule_uuids'].append(item['schedule']['uuid'])
535 scheduleRecords['snapmirror_labels'].append(item['snapmirror_label'])
536 if 'retention_periods' in scheduleRecords.keys():
537 scheduleRecords['retention_periods'].append(item['retention_period'])
538 return scheduleRecords
539 return None
540
541 def get_snapshot_policy_rest(self):
542 """
543 get details of the snapshot policy with rest API.
544 """
545 if not self.use_rest:
546 return self.get_snapshot_policy()
547 query = {'name': self.parameters['name']}
548 if self.parameters.get('vserver'):
549 query['svm.name'] = self.parameters['vserver']
550 query['scope'] = 'svm'
551 else:
552 query['scope'] = 'cluster'
553 api = 'storage/snapshot-policies'
554 fields = 'enabled,svm.uuid,comment,copies.snapmirror_label,copies.count,copies.prefix,copies.schedule.name,scope,'
555 if self.parameters.get('retention_period') is not None:
556 fields += 'copies.retention_period,'
557 record, error = rest_generic.get_one_record(self.rest_api, api, query, fields)
558 if error:
559 self.module.fail_json(msg="Error on fetching snapshot policy: %s" % error)
560 if record:
561 current = {
562 'enabled': record['enabled'],
563 'name': record['name'],
564 'uuid': record['uuid'],
565 'comment': record.get('comment', ''),
566 'count': [],
567 'prefix': [],
568 'schedule': [],
569 'snapmirror_label': []
570 }
571 if self.parameters.get('retention_period') is not None:
572 current.update({'retention_period': []})
573 if query['scope'] == 'svm':
574 current['svm_name'] = record['svm']['name']
575 current['svm_uuid'] = record['svm']['uuid']
576 if record['copies']:
577 for item in record['copies']:
578 current['count'].append(item['count'])
579 current['prefix'].append(item['prefix'])
580 current['schedule'].append(item['schedule']['name'])
581 item_snapmirror_label = item['snapmirror_label'] if item['snapmirror_label'] != '-' else ''
582 current['snapmirror_label'].append(item_snapmirror_label)
583 if 'retention_period' in current.keys():
584 current['retention_period'].append(item['retention_period'])
585 return current
586 return record
587
588 def create_snapshot_policy_rest(self):
589 """
590 create snapshot policy with rest API.
591 """
592 if not self.use_rest:
593 return self.create_snapshot_policy()
594
595 body = {
596 'name': self.parameters.get('name'),
597 'enabled': self.parameters.get('enabled'),
598 'copies': []
599 }
600 if self.parameters.get('vserver'):
601 body['svm.name'] = self.parameters['vserver']
602 if 'comment' in self.parameters:
603 body['comment'] = self.parameters['comment']
604 if 'snapmirror_label' in self.parameters:
605 snapmirror_labels = self.parameters['snapmirror_label']
606 else:
607 # User hasn't supplied any snapmirror labels.
608 snapmirror_labels = [None] * len(self.parameters['schedule'])
609
610 if 'prefix' in self.parameters:
611 prefixes = self.parameters['prefix']
612 else:
613 # User hasn't supplied any prefixes.
614 prefixes = [None] * len(self.parameters['schedule'])
615 if 'retention_period' in self.parameters:
616 retention_periods = self.parameters['retention_period']
617 else:
618 # User hasn't supplied any retention period values.
619 retention_periods = [None] * len(self.parameters['schedule'])
620 for schedule, prefix, count, snapmirror_label, retention_period in \
621 zip(self.parameters['schedule'], prefixes,
622 self.parameters['count'], snapmirror_labels, retention_periods):
623 copy = {
624 'schedule': {'name': self.safe_strip(schedule)},
625 'count': count
626 }
627 snapmirror_label = self.safe_strip(snapmirror_label)
628 if snapmirror_label:
629 copy['snapmirror_label'] = snapmirror_label
630 prefix = self.safe_strip(prefix)
631 if prefix:
632 copy['prefix'] = prefix
633 retention_period = self.safe_strip(retention_period)
634 if retention_period:
635 copy['retention_period'] = retention_period
636 body['copies'].append(copy)
637 api = 'storage/snapshot-policies'
638 dummy, error = rest_generic.post_async(self.rest_api, api, body)
639 if error is not None:
640 self.module.fail_json(msg="Error on creating snapshot policy: %s" % error)
641
642 def delete_snapshot_policy_rest(self, current):
643 """
644 delete snapshot policy with rest API.
645 """
646 if not self.use_rest:
647 return self.delete_snapshot_policy()
648 api = 'storage/snapshot-policies'
649 dummy, error = rest_generic.delete_async(self.rest_api, api, current['uuid'])
650 if error is not None:
651 self.module.fail_json(msg="Error on deleting snapshot policy: %s" % error)
652
653 def modify_snapshot_policy_rest(self, modify, current=None):
654 """
655 Modify snapshot policy with rest API.
656 """
657 if not self.use_rest:
658 return self.modify_snapshot_policy(current)
659 api = 'storage/snapshot-policies'
660 body = {}
661 if 'enabled' in modify:
662 body['enabled'] = modify['enabled']
663 if 'comment' in modify:
664 body['comment'] = modify['comment']
665 if body:
666 dummy, error = rest_generic.patch_async(self.rest_api, api, current['uuid'], body)
667 if error is not None:
668 self.module.fail_json(msg="Error on modifying snapshot policy: %s" % error)
669
670 def modify_snapshot_policy_schedule_rest(self, modify, current):
671 """
672 Modify snapshot schedule with rest API.
673 """
674 if not self.use_rest:
675 return self.modify_snapshot_policy_schedules(current)
676
677 schedule_info = None
678 api = 'storage/snapshot-policies/%s/schedules' % current['uuid']
679 schedule_info = self.get_snapshot_schedule_rest(current)
680 delete_schedules, modify_schedules, add_schedules = [], [], []
681 retain_schedules_count = 0
682
683 if 'snapmirror_label' in self.parameters:
684 snapmirror_labels = self.parameters['snapmirror_label']
685 else:
686 # User hasn't supplied any snapmirror labels.
687 snapmirror_labels = [None] * len(self.parameters['schedule'])
688
689 if 'prefix' in self.parameters:
690 prefixes = self.parameters['prefix']
691 else:
692 # User hasn't supplied any prefix.
693 prefixes = [None] * len(self.parameters['schedule'])
694
695 if 'retention_period' in self.parameters:
696 retention_periods = self.parameters['retention_period']
697 else:
698 # User hasn't supplied any retention period values.
699 retention_periods = [None] * len(self.parameters['schedule'])
700
701 # Identify schedules to be deleted
702 for schedule_name, schedule_uuid in zip(schedule_info['schedule_names'], schedule_info['schedule_uuids']):
703 schedule_name = self.safe_strip(schedule_name)
704 if schedule_name not in [item.strip() for item in self.parameters['schedule']]:
705 delete_schedules.append(schedule_uuid)
706 else:
707 retain_schedules_count += 1
708
709 # Identify schedules to be modified or added
710 for schedule_name, count, snapmirror_label, prefix, retention_period in \
711 zip(self.parameters['schedule'], self.parameters['count'], snapmirror_labels, prefixes, retention_periods):
712 schedule_name = self.safe_strip(schedule_name)
713 if snapmirror_label:
714 snapmirror_label = self.safe_strip(snapmirror_label)
715 if prefix:
716 prefix = self.safe_strip(prefix)
717 if retention_period:
718 retention_period = self.safe_strip(retention_period)
719 body = {}
720 if schedule_name in schedule_info['schedule_names']:
721 # Schedule exists. Only modify if it has changed.
722 modify = False
723 schedule_index = schedule_info['schedule_names'].index(schedule_name)
724 schedule_uuid = schedule_info['schedule_uuids'][schedule_index]
725 if count != schedule_info['counts'][schedule_index]:
726 body['count'] = str(count)
727 modify = True
728
729 if snapmirror_label is not None and snapmirror_label != schedule_info['snapmirror_labels'][schedule_index]:
730 body['snapmirror_label'] = snapmirror_label
731 modify = True
732
733 if prefix is not None and prefix != schedule_info['prefixes'][schedule_index]:
734 body['prefix'] = prefix
735 modify = True
736
737 if retention_period is not None and retention_period != schedule_info['retention_periods'][schedule_index]:
738 body['retention_period'] = retention_period
739 modify = True
740
741 if modify:
742 body['schedule_uuid'] = schedule_uuid
743 modify_schedules.append(body)
744 else:
745 # New schedule
746 body['schedule.name'] = schedule_name
747 body['count'] = str(count)
748 if snapmirror_label is not None and snapmirror_label != '':
749 body['snapmirror_label'] = snapmirror_label
750 if prefix is not None and prefix != '':
751 body['prefix'] = prefix
752 if retention_period is not None and retention_period != '':
753 body['retention_period'] = retention_period
754 add_schedules.append(body)
755
756 # Delete N schedules no longer required if there is at least 1 schedule is to be retained
757 # Otherwise, delete N-1 schedules no longer required as policy must have at least 1 schedule
758 # at any one time. Delete last one afterwards.
759 count = 0 if retain_schedules_count > 0 else 1
760 while len(delete_schedules) > count:
761 schedule_uuid = delete_schedules.pop()
762 record, error = rest_generic.delete_async(self.rest_api, api, schedule_uuid)
763 if error is not None:
764 self.module.fail_json(msg="Error on deleting snapshot policy schedule: %s" % error)
765
766 # Modify schedules.
767 while modify_schedules:
768 body = modify_schedules.pop()
769 schedule_id = body.pop('schedule_uuid')
770 record, error = rest_generic.patch_async(self.rest_api, api, schedule_id, body)
771 if error is not None:
772 self.module.fail_json(msg="Error on modifying snapshot policy schedule: %s" % error)
773
774 # Add 1 new schedule. At least one schedule must be present, before we can delete the last old one.
775 if add_schedules:
776 body = add_schedules.pop()
777 record, error = rest_generic.post_async(self.rest_api, api, body)
778 if error is not None:
779 self.module.fail_json(msg="Error on adding snapshot policy schedule: %s" % error)
780
781 while delete_schedules:
782 schedule_uuid = delete_schedules.pop()
783 record, error = rest_generic.delete_async(self.rest_api, api, schedule_uuid)
784 if error is not None:
785 self.module.fail_json(msg="Error on deleting snapshot policy schedule: %s" % error)
786
787 while add_schedules:
788 body = add_schedules.pop()
789 record, error = rest_generic.post_async(self.rest_api, api, body)
790 if error is not None:
791 self.module.fail_json(msg="Error on adding snapshot policy schedule: %s" % error)
792
793 def apply(self):
794 """
795 Check to see which play we should run
796 """
797 current = self.get_snapshot_policy_rest()
798 modify = None
799 cd_action = self.na_helper.get_cd_action(current, self.parameters)
800 if self.parameters['state'] == 'present':
801 self.validate_parameters()
802 if cd_action is None and self.parameters['state'] == 'present':
803 # Don't sort schedule/prefix/count/snapmirror_label/retention_period lists as it can
804 # mess up the intended parameter order.
805 if 'retention_period' in self.parameters:
806 self.parameters['retention_period'] = [item if item != '' else 'PT0S' for item in self.parameters['retention_period']]
807 modify = self.na_helper.get_modified_attributes(current, self.parameters)
808
809 if self.na_helper.changed and not self.module.check_mode:
810 if cd_action == 'create':
811 self.create_snapshot_policy_rest()
812 elif cd_action == 'delete':
813 self.delete_snapshot_policy_rest(current)
814
815 if modify:
816 self.modify_snapshot_policy_rest(modify, current)
817 self.modify_snapshot_policy_schedule_rest(modify, current)
818 result = netapp_utils.generate_result(self.na_helper.changed, cd_action, modify)
819 self.module.exit_json(**result)
820
821
822 def main():
823 """
824 Creates and deletes a Snapshot Policy
825 """
826 obj = NetAppOntapSnapshotPolicy()
827 obj.apply()
828
829
830 if __name__ == '__main__':
831 main()