Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # (c) 2018-2025, 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_snapshot
9 '''
10
11 from __future__ import absolute_import, division, print_function
12 __metaclass__ = type
13
14
15 DOCUMENTATION = '''
16 module: na_ontap_snapshot
17 short_description: NetApp ONTAP manage Snapshots
18 extends_documentation_fragment:
19 - netapp.ontap.netapp.na_ontap
20 version_added: 2.6.0
21 author: NetApp Ansible Team (@carchi8py) <[email protected]>
22 description:
23 - Create/Modify/Delete ONTAP snapshots
24 options:
25 state:
26 description:
27 - If you want to create/modify a snapshot, or delete it.
28 choices: ['present', 'absent']
29 type: str
30 default: present
31 snapshot:
32 description:
33 - Name of the snapshot to be managed.
34 - The maximum string length is 256 characters.
35 required: true
36 type: str
37 from_name:
38 description:
39 - Name of the existing snapshot to be renamed to.
40 version_added: 2.8.0
41 type: str
42 volume:
43 description:
44 - Name of the volume on which the snapshot is to be created.
45 required: true
46 type: str
47 async_bool:
48 description:
49 - If true, the snapshot is to be created asynchronously.
50 type: bool
51 comment:
52 description:
53 - A human readable comment attached with the snapshot.
54 - The size of the comment can be at most 255 characters.
55 type: str
56 snapmirror_label:
57 description:
58 - A human readable SnapMirror Label attached with the snapshot.
59 - Size of the label can be at most 31 characters.
60 - Supported with REST on Ontap 9.7 or higher.
61 type: str
62 ignore_owners:
63 description:
64 - if this field is true, snapshot will be deleted even if some other processes are accessing it.
65 type: bool
66 snapshot_instance_uuid:
67 description:
68 - The 128 bit unique snapshot identifier expressed in the form of UUID.
69 type: str
70 vserver:
71 description:
72 - The Vserver name
73 required: true
74 type: str
75 expiry_time:
76 description:
77 - Snapshot expire time, only available with REST.
78 - format should be in the timezone configured with cluster.
79 type: str
80 version_added: 21.8.0
81 snaplock_expiry_time:
82 description:
83 - SnapLock expiry time for the snapshot, if the snapshot is taken on a SnapLock volume.
84 - Only supported with REST, requires ONTAP 9.15.1 or later.
85 type: str
86 version_added: 23.2.0
87 lambda_config:
88 description:
89 - Configuration parameters for AWS Lambda proxy functionality.
90 - These option and suboptions are only supported with REST.
91 type: dict
92 version_added: 23.3.0
93 suboptions:
94 function_name:
95 description:
96 - The name of the AWS Lambda function to invoke.
97 type: str
98 required: true
99 aws_region:
100 description:
101 - The name of the AWS region.
102 type: str
103 required: true
104 aws_profile:
105 description:
106 - The name of the AWS profile to use for authentication.
107 type: str
108
109 notes:
110 - Supports AWS Lambda proxy functionality when using REST. See the README file for examples.
111 '''
112 EXAMPLES = """
113 - name: Create SnapShot
114 netapp.ontap.na_ontap_snapshot:
115 state: present
116 snapshot: "{{ snapshot_name }}"
117 volume: "{{ vol_name }}"
118 comment: "sample comment"
119 expiry_time: "2022-02-04T14:00:00-05:00"
120 vserver: "{{ vserver name }}"
121 hostname: "{{ netapp_hostname }}"
122 username: "{{ netapp_username }}"
123 password: "{{ netapp_password }}"
124
125 - name: Delete SnapShot
126 netapp.ontap.na_ontap_snapshot:
127 state: absent
128 snapshot: "{{ snapshot_name }}"
129 volume: "{{ vol_name }}"
130 vserver: "{{ vserver_name }}"
131 hostname: "{{ netapp_hostname }}"
132 username: "{{ netapp_username }}"
133 password: "{{ netapp_password }}"
134
135 - name: Modify SnapShot
136 netapp.ontap.na_ontap_snapshot:
137 state: present
138 snapshot: "{{ snapshot_name }}"
139 comment: "New comments are great"
140 volume: "{{ vol_name }}"
141 vserver: "{{ vserver_name }}"
142 hostname: "{{ netapp_hostname }}"
143 username: "{{ netapp_username }}"
144 password: "{{ netapp_password }}"
145 """
146
147 RETURN = """
148 """
149
150 import traceback
151 import ansible_collections.netapp.ontap.plugins.module_utils.netapp as netapp_utils
152 from ansible_collections.netapp.ontap.plugins.module_utils.netapp_module import NetAppModule
153 from ansible.module_utils.basic import AnsibleModule
154 from ansible.module_utils._text import to_native
155 from ansible_collections.netapp.ontap.plugins.module_utils import rest_generic
156 from ansible_collections.netapp.ontap.plugins.module_utils import rest_volume
157
158
159 class NetAppOntapSnapshot:
160 """
161 Creates, modifies, and deletes a Snapshot
162 """
163
164 def __init__(self):
165 self.argument_spec = netapp_utils.na_ontap_host_argument_spec()
166 self.argument_spec.update(dict(
167 state=dict(required=False, type='str', choices=['present', 'absent'], default='present'),
168 from_name=dict(required=False, type='str'),
169 snapshot=dict(required=True, type="str"),
170 volume=dict(required=True, type="str"),
171 async_bool=dict(required=False, type="bool"),
172 comment=dict(required=False, type="str"),
173 snapmirror_label=dict(required=False, type="str"),
174 ignore_owners=dict(required=False, type="bool"),
175 snapshot_instance_uuid=dict(required=False, type="str"),
176 vserver=dict(required=True, type="str"),
177 expiry_time=dict(required=False, type="str"),
178 snaplock_expiry_time=dict(required=False, type="str"),
179 ))
180 self.argument_spec.update(netapp_utils.na_ontap_lambda_argument_spec())
181
182 self.module = AnsibleModule(
183 argument_spec=self.argument_spec,
184 required_if=[
185 ['use_lambda', True, ('lambda_config',)]
186 ],
187 supports_check_mode=True
188 )
189
190 self.na_helper = NetAppModule()
191 self.parameters = self.na_helper.set_parameters(self.module.params)
192
193 self.rest_api = netapp_utils.OntapRestAPI(self.module)
194 unsupported_rest_properties = ['async_bool', 'ignore_owners', 'snapshot_instance_uuid']
195 partially_supported_rest_properties = [['snapmirror_label', (9, 7)],
196 ['snaplock_expiry_time', (9, 15, 1)]]
197 self.use_rest = self.rest_api.is_rest_supported_properties(self.parameters, unsupported_rest_properties, partially_supported_rest_properties)
198
199 if not self.use_rest:
200 if self.parameters.get('use_lambda'):
201 self.module.fail_json(msg="Error: AWS Lambda proxy for ONTAP APIs is only supported with REST.")
202 if self.parameters.get('expiry_time'):
203 self.module.fail_json(msg="expiry_time is currently only supported with REST on Ontap 9.6 or higher")
204 if self.parameters.get('snaplock_expiry_time'):
205 self.module.fail_json(msg="snaplock_expiry_time is only supported with REST on Ontap 9.15.1 or higher")
206 if not netapp_utils.has_netapp_lib():
207 self.module.fail_json(msg=netapp_utils.netapp_lib_is_required())
208 self.server = netapp_utils.setup_na_ontap_zapi(module=self.module, vserver=self.parameters['vserver'])
209
210 def get_snapshot(self, snapshot_name=None, volume_id=None):
211 """
212 Checks to see if a snapshot exists or not
213 :return: Return True if a snapshot exists, False if it doesn't
214 """
215 if self.use_rest:
216 api = ('storage/volumes/%s/snapshots' % volume_id)
217 params = {
218 'svm.name': self.parameters['vserver'],
219 'fields': 'uuid,comment,expiry_time,volume,name',
220 }
221 if self.parameters.get('snapmirror_label'):
222 params['fields'] += ',snapmirror_label'
223 if self.parameters.get('snaplock_expiry_time'):
224 params['fields'] += ',snaplock.expiry_time'
225 params['name'] = snapshot_name or self.parameters['snapshot']
226 snapshot, error = rest_generic.get_one_record(self.rest_api, api, params)
227 if error:
228 self.module.fail_json(msg='Error fetching snapshot %s: %s' %
229 (params['name'], to_native(error)),
230 exception=traceback.format_exc())
231 if snapshot:
232 return {
233 'uuid': snapshot['uuid'],
234 'snapshot': snapshot['name'],
235 'snapmirror_label': snapshot.get('snapmirror_label'),
236 'expiry_time': snapshot.get('expiry_time'),
237 'comment': snapshot.get('comment'),
238 'snaplock_expiry_time': self.na_helper.safe_get(snapshot, ['snaplock', 'expiry_time'])
239 }
240 return None
241
242 else:
243 if snapshot_name is None:
244 snapshot_name = self.parameters['snapshot']
245 snapshot_obj = netapp_utils.zapi.NaElement("snapshot-get-iter")
246 desired_attr = netapp_utils.zapi.NaElement("desired-attributes")
247 snapshot_info = netapp_utils.zapi.NaElement('snapshot-info')
248 comment = netapp_utils.zapi.NaElement('comment')
249 snapmirror_label = netapp_utils.zapi.NaElement('snapmirror-label')
250 # add more desired attributes that are allowed to be modified
251 snapshot_info.add_child_elem(comment)
252 snapshot_info.add_child_elem(snapmirror_label)
253 desired_attr.add_child_elem(snapshot_info)
254 snapshot_obj.add_child_elem(desired_attr)
255 # compose query
256 query = netapp_utils.zapi.NaElement("query")
257 snapshot_info_obj = netapp_utils.zapi.NaElement("snapshot-info")
258 snapshot_info_obj.add_new_child("name", snapshot_name)
259 snapshot_info_obj.add_new_child("volume", self.parameters['volume'])
260 snapshot_info_obj.add_new_child("vserver", self.parameters['vserver'])
261 query.add_child_elem(snapshot_info_obj)
262 snapshot_obj.add_child_elem(query)
263 try:
264 result = self.server.invoke_successfully(snapshot_obj, True)
265 except netapp_utils.zapi.NaApiError as error:
266 self.module.fail_json(msg='Error fetching snapshot %s: %s' %
267 (snapshot_name, to_native(error)),
268 exception=traceback.format_exc())
269 return_value = None
270 if result.get_child_by_name('num-records') and \
271 int(result.get_child_content('num-records')) == 1:
272 attributes_list = result.get_child_by_name('attributes-list')
273 snap_info = attributes_list.get_child_by_name('snapshot-info')
274 return_value = {
275 'comment': snap_info.get_child_content('comment'),
276 'snapmirror_label': None
277 }
278 if snap_info.get_child_by_name('snapmirror-label'):
279 return_value['snapmirror_label'] = snap_info.get_child_content('snapmirror-label')
280 return return_value
281
282 def create_snapshot(self, volume_id=None):
283 """
284 Creates a new snapshot
285 """
286
287 if self.use_rest:
288 api = ('storage/volumes/%s/snapshots' % volume_id)
289 body = {
290 'name': self.parameters['snapshot'],
291 'svm': {
292 'name': self.parameters['vserver']
293 }
294 }
295 if self.parameters.get('comment'):
296 body['comment'] = self.parameters['comment']
297 if self.parameters.get('snapmirror_label'):
298 body['snapmirror_label'] = self.parameters['snapmirror_label']
299 if self.parameters.get('expiry_time'):
300 body['expiry_time'] = self.parameters['expiry_time']
301 if self.parameters.get('snaplock_expiry_time'):
302 body['snaplock.expiry_time'] = self.parameters['snaplock_expiry_time']
303 response, error = rest_generic.post_async(self.rest_api, api, body)
304 if error:
305 self.module.fail_json(msg="Error when creating snapshot: %s" % error)
306
307 else:
308 snapshot_obj = netapp_utils.zapi.NaElement("snapshot-create")
309
310 # set up required variables to create a snapshot
311 snapshot_obj.add_new_child("snapshot", self.parameters['snapshot'])
312 snapshot_obj.add_new_child("volume", self.parameters['volume'])
313 # Set up optional variables to create a snapshot
314 if self.parameters.get('async_bool'):
315 snapshot_obj.add_new_child("async", str(self.parameters['async_bool']))
316 if self.parameters.get('comment'):
317 snapshot_obj.add_new_child("comment", self.parameters['comment'])
318 if self.parameters.get('snapmirror_label'):
319 snapshot_obj.add_new_child(
320 "snapmirror-label", self.parameters['snapmirror_label'])
321 try:
322 self.server.invoke_successfully(snapshot_obj, True)
323 except netapp_utils.zapi.NaApiError as error:
324 self.module.fail_json(msg='Error creating snapshot %s: %s' %
325 (self.parameters['snapshot'], to_native(error)),
326 exception=traceback.format_exc())
327
328 def delete_snapshot(self, volume_id=None, uuid=None):
329 """
330 Deletes an existing snapshot
331 """
332 if self.use_rest:
333 api = ('storage/volumes/%s/snapshots/%s' % (volume_id, uuid))
334 response, error = rest_generic.delete_async(self.rest_api, api, None)
335 if error:
336 self.module.fail_json(msg="Error when deleting snapshot: %s" % error)
337
338 else:
339 snapshot_obj = netapp_utils.zapi.NaElement("snapshot-delete")
340
341 # Set up required variables to delete a snapshot
342 snapshot_obj.add_new_child("snapshot", self.parameters['snapshot'])
343 snapshot_obj.add_new_child("volume", self.parameters['volume'])
344 # set up optional variables to delete a snapshot
345 if self.parameters.get('ignore_owners'):
346 snapshot_obj.add_new_child("ignore-owners", str(self.parameters['ignore_owners']))
347 if self.parameters.get('snapshot_instance_uuid'):
348 snapshot_obj.add_new_child("snapshot-instance-uuid", self.parameters['snapshot_instance_uuid'])
349 try:
350 self.server.invoke_successfully(snapshot_obj, True)
351 except netapp_utils.zapi.NaApiError as error:
352 self.module.fail_json(msg='Error deleting snapshot %s: %s' %
353 (self.parameters['snapshot'], to_native(error)),
354 exception=traceback.format_exc())
355
356 def modify_snapshot(self, volume_id=None, uuid=None, rename=False):
357 """
358 Modify an existing snapshot
359 :return:
360 """
361 if self.use_rest:
362 api = 'storage/volumes/%s/snapshots/%s' % (volume_id, uuid)
363 body = {'name': self.parameters['snapshot']} if rename else {}
364 if self.parameters.get('comment'):
365 body['comment'] = self.parameters['comment']
366 if self.parameters.get('snapmirror_label'):
367 body['snapmirror_label'] = self.parameters['snapmirror_label']
368 if self.parameters.get('expiry_time'):
369 body['expiry_time'] = self.parameters['expiry_time']
370 if self.parameters.get('snaplock_expiry_time'):
371 body['snaplock.expiry_time'] = self.parameters['snaplock_expiry_time']
372 response, error = rest_generic.patch_async(self.rest_api, api, None, body)
373 if error:
374 self.module.fail_json(msg="Error when modifying snapshot: %s" % error)
375
376 else:
377 snapshot_obj = netapp_utils.zapi.NaElement("snapshot-modify-iter")
378 # Create query object, this is the existing object
379 query = netapp_utils.zapi.NaElement("query")
380 snapshot_info_obj = netapp_utils.zapi.NaElement("snapshot-info")
381 snapshot_info_obj.add_new_child("name", self.parameters['snapshot'])
382 snapshot_info_obj.add_new_child("vserver", self.parameters['vserver'])
383 query.add_child_elem(snapshot_info_obj)
384 snapshot_obj.add_child_elem(query)
385
386 # this is what we want to modify in the snapshot object
387 attributes = netapp_utils.zapi.NaElement("attributes")
388 snapshot_info_obj = netapp_utils.zapi.NaElement("snapshot-info")
389 snapshot_info_obj.add_new_child("name", self.parameters['snapshot'])
390 if self.parameters.get('comment'):
391 snapshot_info_obj.add_new_child("comment", self.parameters['comment'])
392 if self.parameters.get('snapmirror_label'):
393 snapshot_info_obj.add_new_child("snapmirror-label", self.parameters['snapmirror_label'])
394 attributes.add_child_elem(snapshot_info_obj)
395 snapshot_obj.add_child_elem(attributes)
396 try:
397 self.server.invoke_successfully(snapshot_obj, True)
398 except netapp_utils.zapi.NaApiError as error:
399 self.module.fail_json(msg='Error modifying snapshot %s: %s' %
400 (self.parameters['snapshot'], to_native(error)),
401 exception=traceback.format_exc())
402
403 def rename_snapshot(self):
404 """
405 Rename the sanpshot
406 """
407 snapshot_obj = netapp_utils.zapi.NaElement("snapshot-rename")
408
409 # set up required variables to rename a snapshot
410 snapshot_obj.add_new_child("current-name", self.parameters['from_name'])
411 snapshot_obj.add_new_child("new-name", self.parameters['snapshot'])
412 snapshot_obj.add_new_child("volume", self.parameters['volume'])
413 try:
414 self.server.invoke_successfully(snapshot_obj, True)
415 except netapp_utils.zapi.NaApiError as error:
416 self.module.fail_json(msg='Error renaming snapshot %s to %s: %s' %
417 (self.parameters['from_name'], self.parameters['snapshot'], to_native(error)),
418 exception=traceback.format_exc())
419
420 def get_volume_uuid(self):
421 """
422 Get a volume's UUID
423 :return: uuid of the volume
424 """
425 response, error = rest_volume.get_volume(self.rest_api, self.parameters['vserver'], self.parameters['volume'])
426 if error is not None:
427 self.module.fail_json(msg="Error getting volume info: %s" % error)
428 return response['uuid'] if response else None
429
430 def apply(self):
431 """
432 Check to see which play we should run
433 """
434 volume_id = None
435 uuid = None
436 current = None
437 if not self.use_rest:
438 current = self.get_snapshot()
439 else:
440 volume_id = self.get_volume_uuid()
441 if volume_id is None:
442 self.module.fail_json(msg="Error: volume %s not found for vserver %s." % (self.parameters['volume'], self.parameters['vserver']))
443 current = self.get_snapshot(volume_id=volume_id)
444
445 rename = False
446 modify = {}
447 cd_action = self.na_helper.get_cd_action(current, self.parameters)
448 if cd_action == 'create' and self.parameters.get('from_name'):
449 current = self.get_snapshot(self.parameters['from_name'], volume_id=volume_id)
450 if current is None:
451 self.module.fail_json(msg='Error renaming snapshot: %s - no snapshot with from_name: %s.'
452 % (self.parameters['snapshot'], self.parameters['from_name']))
453 rename = True
454 cd_action = None
455 if cd_action is None:
456 modify = self.na_helper.get_modified_attributes(current, self.parameters)
457 if self.na_helper.changed and not self.module.check_mode:
458 uuid = current['uuid'] if current and self.use_rest else None
459 if rename and not self.use_rest:
460 # with REST, rename forces a change in modify for 'name'
461 self.rename_snapshot()
462 if cd_action == 'create':
463 self.create_snapshot(volume_id=volume_id)
464 elif cd_action == 'delete':
465 self.delete_snapshot(volume_id=volume_id, uuid=uuid)
466 elif modify:
467 self.modify_snapshot(volume_id=volume_id, uuid=uuid, rename=rename)
468 result = netapp_utils.generate_result(self.na_helper.changed, cd_action, modify)
469 self.module.exit_json(**result)
470
471
472 def main():
473 """
474 Creates, modifies, and deletes a Snapshot
475 """
476 obj = NetAppOntapSnapshot()
477 obj.apply()
478
479
480 if __name__ == '__main__':
481 main()