Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: NetApp, Inc
5 # GNU General Public License v3.0+ (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 DOCUMENTATION = """
11 module: na_ontap_storage_unit
12 short_description: NetApp ONTAP ASA r2 storage unit
13 extends_documentation_fragment:
14 - netapp.ontap.netapp.na_ontap_rest
15 version_added: 23.0.0
16 author: NetApp Ansible Team (@carchi8py) <[email protected]>
17 description:
18 - Clone a storage unit.
19 - Split a storage unit clone.
20 - Move a storage unit.
21 - Restore a storage unit to a prior snapshot.
22 options:
23 state:
24 description:
25 - Manage storage unit operations, only present is supported.
26 choices: ['present']
27 type: str
28 default: present
29
30 name:
31 description:
32 - Specifies the name of the storage unit (LUN or NVMe namespace).
33 type: str
34 required: true
35
36 clone:
37 type: dict
38 description:
39 - Identifiers of the parent storage unit or storage unit snapshot from which to clone a new storage unit.
40 - The storage unit clone and its source must reside on the same SVM.
41 suboptions:
42 snapshot:
43 description:
44 - The name of the snapshot the source storage unit resides in.
45 type: str
46 storage_unit:
47 description:
48 - The name of the source storage unit.
49 type: str
50
51 split_initiated:
52 description:
53 - Setting this field initiates a split of a FlexClone storage unit from a FlexVol storage unit.
54 - This operation stops the replication of data but doesn't remove the snapshots from the replicas.
55 type: bool
56
57 vserver:
58 description:
59 - Specifies the SVM in which the storage unit is located.
60 type: str
61 required: true
62
63 restore_to_snapshot:
64 description:
65 - Specifies the name of the snapshot to restore the storage unit to the point in time the snapshot was taken.
66 type: str
67
68 target_location:
69 description:
70 - Specifies the name of the destination storage availability zone for moving the storage unit.
71 type: str
72
73 restore_to:
74 description:
75 - Specifies the name of the snapshot to restore the storage unit to the point in time the snapshot was taken.
76 type: str
77
78 time_out:
79 description:
80 - With C(wait_for_completion) set, specifies time to wait for any storage unit clone, split, restore or move operations in seconds.
81 type: int
82 default: 180
83
84 wait_for_completion:
85 description:
86 - Set this parameter to 'true' for synchronous execution.
87 - For asynchronous, execution exits as soon as the request is sent, and the operation continues in the background.
88 type: bool
89 default: true
90
91 notes:
92 - Only supported with REST and requires ONTAP 9.16.1 or later.
93 - Only suppored with ASA r2 systems.
94 - The storage unit clone and its source must reside on the same SVM.
95 - Module is not idempotent when C(restore_to) is set.
96 - Storage unit REST API doesn't support DELETE operation. Kindly refer to module \
97 C(na_ontap_lun) or C(na_ontap_nvme_namespace) for deleting corresponding storage unit.
98 """
99
100 EXAMPLES = """
101 - name: Create a new storage unit(LUN) clone
102 netapp.ontap.na_ontap_storage_unit:
103 state: present
104 name: lun1_clone1
105 vserver: svm1
106 clone:
107 storage_unit: lun1
108 wait_for_completion: true
109 hostname: "{{ netapp_hostname }}"
110 username: "{{ netapp_username }}"
111 password: "{{ netapp_password }}"
112 https: true
113 validate_certs: "{{ validate_certs }}"
114 use_rest: always
115
116 - name: Split a storage unit(LUN) clone
117 netapp.ontap.na_ontap_storage_unit:
118 state: present
119 name: lun1_clone1
120 vserver: svm1
121 split_initiated: true
122 wait_for_completion: true
123 hostname: "{{ netapp_hostname }}"
124 username: "{{ netapp_username }}"
125 password: "{{ netapp_password }}"
126 https: true
127 validate_certs: "{{ validate_certs }}"
128 use_rest: always
129
130 - name: Create a new storage unit(LUN) clone using snapshot
131 netapp.ontap.na_ontap_storage_unit:
132 state: present
133 name: lun1_clone1
134 vserver: svm1
135 clone:
136 storage_unit: lun1
137 snapshot: "hourly.2025-04-23_0205"
138 wait_for_completion: true
139 hostname: "{{ netapp_hostname }}"
140 username: "{{ netapp_username }}"
141 password: "{{ netapp_password }}"
142 https: true
143 validate_certs: "{{ validate_certs }}"
144 use_rest: always
145
146 - name: Clone a storage unit(LUN), split new clone simultaneously
147 netapp.ontap.na_ontap_storage_unit:
148 state: present
149 name: lun1_clone1
150 vserver: svm1
151 clone:
152 storage_unit: lun1
153 split_initiated: true
154 wait_for_completion: true
155 hostname: "{{ netapp_hostname }}"
156 username: "{{ netapp_username }}"
157 password: "{{ netapp_password }}"
158 https: true
159 validate_certs: "{{ validate_certs }}"
160 use_rest: always
161
162 - name: Restore a storage unit(LUN) to a prior snapshot
163 netapp.ontap.na_ontap_storage_unit:
164 state: present
165 name: lun1
166 vserver: svm1
167 restore_to: "hourly.2025-04-21_0905"
168 wait_for_completion: true
169 hostname: "{{ netapp_hostname }}"
170 username: "{{ netapp_username }}"
171 password: "{{ netapp_password }}"
172 https: true
173 validate_certs: "{{ validate_certs }}"
174 use_rest: always
175
176 - name: Move a storage unit(LUN)
177 netapp.ontap.na_ontap_storage_unit:
178 state: present
179 name: lun1
180 vserver: svm1
181 target_location: storage_availability_zone_0
182 wait_for_completion: true
183 hostname: "{{ netapp_hostname }}"
184 username: "{{ netapp_username }}"
185 password: "{{ netapp_password }}"
186 https: true
187 validate_certs: "{{ validate_certs }}"
188 use_rest: always
189 """
190
191 RETURN = """
192
193 """
194
195 import traceback
196 from ansible.module_utils.basic import AnsibleModule
197 from ansible.module_utils._text import to_native
198 import ansible_collections.netapp.ontap.plugins.module_utils.netapp as netapp_utils
199 from ansible_collections.netapp.ontap.plugins.module_utils.netapp_module import NetAppModule
200 from ansible_collections.netapp.ontap.plugins.module_utils import rest_generic
201 from ansible_collections.netapp.ontap.plugins.module_utils import rest_ontap_personality
202
203
204 class NetAppOntapStorageUnit:
205 def __init__(self):
206 self.argument_spec = netapp_utils.na_ontap_rest_only_spec()
207 self.argument_spec.update(dict(
208 state=dict(required=False, type='str', choices=['present'], default='present'),
209 name=dict(required=True, type='str'),
210 clone=dict(type='dict', options=dict(
211 snapshot=dict(type='str'),
212 storage_unit=dict(type='str')
213 )),
214 split_initiated=dict(required=False, type='bool'),
215 vserver=dict(required=True, type='str'),
216 restore_to_snapshot=dict(required=False, type='str'),
217 target_location=dict(required=False, type='str'),
218 restore_to=dict(required=False, type='str'),
219 time_out=dict(required=False, type='int', default=180),
220 wait_for_completion=dict(required=False, type='bool', default=True),
221 ))
222
223 self.module = AnsibleModule(
224 argument_spec=self.argument_spec,
225 mutually_exclusive=[
226 ['clone', 'restore_to', 'target_location'],
227 ['split_initiated', 'restore_to', 'target_location']
228 ],
229 supports_check_mode=True
230 )
231
232 self.uuid = None
233 self.na_helper = NetAppModule(self.module)
234 self.parameters = self.na_helper.check_and_set_parameters(self.module)
235
236 self.rest_api = netapp_utils.OntapRestAPI(self.module)
237 self.rest_api.fail_if_not_rest_minimum_version('na_ontap_storage_unit:', 9, 16, 1)
238 asa_r2_system = self.is_asa_r2_system()
239 if not asa_r2_system:
240 self.module.fail_json(msg="na_ontap_storage_unit module is only supported with ASA r2 systems.")
241
242 def is_asa_r2_system(self):
243 ''' checks if the given host is a ASA r2 system or not '''
244 return rest_ontap_personality.is_asa_r2_system(self.rest_api, self.module)
245
246 def get_storage_unit(self):
247 """ Retrieves storage unit by name """
248 api = 'storage/storage-units'
249 fields = 'name,uuid,type,'
250 if 'clone' in self.parameters or 'split_initiated' in self.parameters:
251 fields += 'clone.*,'
252 if 'target_location' in self.parameters:
253 fields += 'location.storage_availability_zone.name,'
254 params = {
255 'name': self.parameters['name'],
256 'svm.name': self.parameters['vserver'],
257 'fields': fields
258 }
259 record, error = rest_generic.get_one_record(self.rest_api, api, params)
260 if error:
261 self.module.fail_json(msg="Error while fetching storage unit named %s: %s" % (self.parameters['name'], to_native(error)),
262 exception=traceback.format_exc())
263 if record:
264 self.uuid = record.get('uuid')
265 return {
266 'name': record.get('name'),
267 'type': record.get('type'),
268 'is_flexclone': self.na_helper.safe_get(record, ['clone', 'is_flexclone']),
269 'target_location': self.na_helper.safe_get(record, ['location', 'storage_availability_zone', 'name']),
270 'split_initiated': self.na_helper.safe_get(record, ['clone', 'split_initiated'])
271 }
272 return None
273
274 def clone_storage_unit(self):
275 """ Clone a storage unit """
276 api = 'storage/storage-units'
277 query = {'return_timeout': 0} if not self.parameters['wait_for_completion'] else None
278 timeout = 0 if not self.parameters['wait_for_completion'] else self.parameters['time_out']
279 body = {
280 'name': self.parameters['name'],
281 'svm.name': self.parameters['vserver'],
282 'clone': {'source': {}}
283 }
284 source_storage_unit = self.na_helper.safe_get(self.parameters, ['clone', 'storage_unit'])
285 source_snapshot = self.na_helper.safe_get(self.parameters, ['clone', 'snapshot'])
286 if source_storage_unit is not None:
287 body['clone']['source'].update({'storage_unit': {'name': source_storage_unit}})
288 if source_snapshot is not None:
289 body['clone']['source'].update({'snapshot': {'name': source_snapshot}})
290 if self.parameters.get('split_initiated') is True:
291 body['clone'].update({'split_initiated': True})
292
293 dummy, error = rest_generic.post_async(self.rest_api, api, body, query, job_timeout=timeout)
294 if error:
295 if 'job reported error:' in error and 'Timeout error: Process still running' in error:
296 if not self.parameters['wait_for_completion']:
297 warning = "Process is still running in the background, exiting with no further waiting as 'wait_for_completion' is set to false."
298 else:
299 warning = ('Storage unit cloning is still in progress after %d seconds.' % self.parameters['time_out'])
300 self.module.warn(warning)
301 return
302 self.module.fail_json(msg="Error while cloning storage unit %s: %s" % (self.parameters['name'], to_native(error)),
303 exception=traceback.format_exc())
304
305 def clone_split_storage_unit(self):
306 """ Clone split operation """
307 api = 'storage/storage-units'
308 query = {'return_timeout': 0} if not self.parameters['wait_for_completion'] else None
309 timeout = 0 if not self.parameters['wait_for_completion'] else self.parameters['time_out']
310 body = {'clone': {'split_initiated': True}}
311
312 dummy, error = rest_generic.patch_async(self.rest_api, api, self.uuid, body, query, job_timeout=timeout)
313 if error:
314 if 'job reported error:' in error and 'Timeout error: Process still running' in error:
315 if not self.parameters['wait_for_completion']:
316 warning = "Process is still running in the background, exiting with no further waiting as 'wait_for_completion' is set to false."
317 else:
318 warning = ('Storage unit clone split is still in progress after %d seconds.' % self.parameters['time_out'])
319 self.module.warn(warning)
320 return
321 self.module.fail_json(msg="Error while splitting storage unit clone %s: %s." % (self.parameters['name'], to_native(error)),
322 exception=traceback.format_exc())
323
324 def move_storage_unit(self):
325 """ Move a storage unit """
326 api = 'storage/storage-units'
327 query = {'return_timeout': 0} if not self.parameters['wait_for_completion'] else {}
328 timeout = 0 if not self.parameters['wait_for_completion'] else self.parameters['time_out']
329 body = {
330 'location.storage_availability_zone.name': self.parameters['target_location']
331 }
332
333 dummy, error = rest_generic.patch_async(self.rest_api, api, self.uuid, body, query, job_timeout=timeout)
334 if error:
335 if 'job reported error:' in error and 'Timeout error: Process still running' in error:
336 if not self.parameters['wait_for_completion']:
337 warning = "Process is still running in the background, exiting with no further waiting as 'wait_for_completion' is set to false."
338 else:
339 warning = ('Storage unit is still getting moved after %d seconds.' % self.parameters['time_out'])
340 self.module.warn(warning)
341 return
342 self.module.fail_json(msg="Error while moving storage unit %s: %s." % (self.parameters['name'], to_native(error)),
343 exception=traceback.format_exc())
344
345 def restore_storage_unit(self):
346 """ Restore a storage unit to given snapshot """
347 api = 'storage/storage-units'
348 query = {'return_timeout': 0} if not self.parameters['wait_for_completion'] else {}
349 timeout = 0 if not self.parameters['wait_for_completion'] else self.parameters['time_out']
350 query.update({'restore_to.snapshot.name': self.parameters['restore_to']})
351
352 dummy, error = rest_generic.patch_async(self.rest_api, api, self.uuid, body=None, query=query, job_timeout=timeout)
353 if error:
354 if "entry doesn't exist" in error:
355 self.module.fail_json(msg="The given snapshot does not seem to exist.")
356 if 'job reported error:' in error and 'Timeout error: Process still running' in error:
357 if not self.parameters['wait_for_completion']:
358 warning = "Process is still running in the background, exiting with no further waiting as 'wait_for_completion' is set to false."
359 else:
360 warning = ('Storage unit is still restoring after %d seconds.' % self.parameters['time_out'])
361 self.module.warn(warning)
362 return
363 self.module.fail_json(msg="Error while restoring storage unit %s: %s." % (self.parameters['name'], to_native(error)),
364 exception=traceback.format_exc())
365
366 def apply(self):
367 current = self.get_storage_unit()
368 modify = None
369 cd_action = self.na_helper.get_cd_action(current, self.parameters)
370 if cd_action is None and self.parameters['state'] == 'present':
371 modify = self.na_helper.get_modified_attributes(current, self.parameters)
372 if not current['is_flexclone'] and 'split_initiated' in modify:
373 self.module.warn('Clone split operation can be performed only for a FlexClone storage unit.')
374 modify.pop('split_initiated')
375 self.na_helper.changed = False
376 if 'restore_to' in self.parameters:
377 self.na_helper.changed = True
378 modify['restore_to'] = self.parameters['restore_to']
379 if self.na_helper.changed and not self.module.check_mode:
380 if cd_action == 'create':
381 self.clone_storage_unit()
382 elif modify:
383 if 'split_initiated' in modify:
384 self.clone_split_storage_unit()
385 elif 'target_location' in modify:
386 self.move_storage_unit()
387 elif 'restore_to' in modify:
388 self.restore_storage_unit()
389 result = netapp_utils.generate_result(self.na_helper.changed, cd_action, modify)
390 self.module.exit_json(**result)
391
392
393 def main():
394 storage_unit = NetAppOntapStorageUnit()
395 storage_unit.apply()
396
397
398 if __name__ == '__main__':
399 main()