Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 """ this is lun mapping module
4
5 (c) 2018-2026, NetApp, Inc
6 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
7 """
8
9 from __future__ import absolute_import, division, print_function
10
11 __metaclass__ = type
12
13 DOCUMENTATION = """
14 module: na_ontap_lun_map
15 short_description: NetApp ONTAP LUN maps
16 extends_documentation_fragment:
17 - netapp.ontap.netapp.na_ontap
18 version_added: 2.6.0
19 author: NetApp Ansible Team (@carchi8py) <[email protected]>
20
21 description:
22 - Map and unmap LUNs on NetApp ONTAP.
23
24 options:
25
26 state:
27 description:
28 - Whether the specified LUN should exist or not.
29 choices: ['present', 'absent']
30 type: str
31 default: present
32
33 initiator_group_name:
34 description:
35 - Initiator group to map to the given LUN.
36 required: true
37 type: str
38
39 path:
40 description:
41 - Path of the LUN.
42 - For ASA r2 systems, The path should match the format <name>[@<snapshot-name>].
43 required: true
44 type: str
45
46 vserver:
47 required: true
48 description:
49 - The name of the vserver to use.
50 type: str
51
52 lun_id:
53 description:
54 - LUN ID assigned for the map.
55 type: str
56
57 lambda_config:
58 description:
59 - Configuration parameters for AWS Lambda proxy functionality.
60 - These option and suboptions are only supported with REST.
61 type: dict
62 version_added: 23.4.0
63 suboptions:
64 function_name:
65 description:
66 - The name of the AWS Lambda function to invoke.
67 type: str
68 required: true
69 aws_region:
70 description:
71 - The name of the AWS region.
72 type: str
73 required: true
74 aws_profile:
75 description:
76 - The name of the AWS profile to use for authentication.
77 type: str
78
79 notes:
80 - Compatible with ASA r2 system when using REST for ONTAP releases 9.16.0x onwards.
81 - Supports AWS Lambda proxy functionality when using REST. See the README file for examples.
82 """
83
84 EXAMPLES = """
85 - name: Create LUN mapping
86 netapp.ontap.na_ontap_lun_map:
87 state: present
88 initiator_group_name: ansibleIgroup3234
89 path: /vol/iscsi_path/iscsi_lun
90 vserver: ci_dev
91 hostname: "{{ netapp_hostname }}"
92 username: "{{ netapp_username }}"
93 password: "{{ netapp_password }}"
94
95 - name: Unmap LUN
96 netapp.ontap.na_ontap_lun_map:
97 state: absent
98 initiator_group_name: ansibleIgroup3234
99 path: /vol/iscsi_path/iscsi_lun
100 vserver: ci_dev
101 hostname: "{{ netapp_hostname }}"
102 username: "{{ netapp_username }}"
103 password: "{{ netapp_password }}"
104 """
105
106 RETURN = """
107 lun_node:
108 description: NetApp controller that is hosting the LUN. (Note Not returned with REST)
109 returned: success
110 type: str
111 sample: node01
112 lun_ostype:
113 description: Specifies the OS of the host accessing the LUN.
114 returned: success
115 type: str
116 sample: vmware
117 lun_serial:
118 description: A unique, 12-byte, ASCII string used to identify the LUN.
119 returned: success
120 type: str
121 sample: 80E7/]LZp1Tt
122 lun_naa_id:
123 description: The Network Address Authority (NAA) identifier for the LUN.
124 returned: success
125 type: str
126 sample: 600a0980383045372f5d4c5a70315474
127 lun_state:
128 description: Online or offline status of the LUN.
129 returned: success
130 type: str
131 sample: online
132 lun_size:
133 description: Size of the LUN in bytes.
134 returned: success
135 type: int
136 sample: 2199023255552
137 """
138
139 import traceback
140
141 from ansible.module_utils.basic import AnsibleModule
142 from ansible.module_utils._text import to_native
143 import ansible_collections.netapp.ontap.plugins.module_utils.netapp as netapp_utils
144 import codecs
145 from ansible.module_utils._text import to_text, to_bytes
146 from ansible_collections.netapp.ontap.plugins.module_utils.netapp_module import NetAppModule
147 from ansible_collections.netapp.ontap.plugins.module_utils.netapp import OntapRestAPI
148 from ansible_collections.netapp.ontap.plugins.module_utils import rest_generic, rest_ontap_personality
149
150 HAS_NETAPP_LIB = netapp_utils.has_netapp_lib()
151
152
153 class NetAppOntapLUNMap:
154 """
155 Class with LUN map methods
156 """
157
158 def __init__(self):
159 self.lun_uuid, self.igroup_uuid = None, None
160 self.argument_spec = netapp_utils.na_ontap_host_argument_spec()
161 self.argument_spec.update(dict(
162 state=dict(required=False, type='str', choices=['present', 'absent'], default='present'),
163 initiator_group_name=dict(required=True, type='str'),
164 path=dict(required=True, type='str'),
165 vserver=dict(required=True, type='str'),
166 lun_id=dict(required=False, type='str', default=None),
167 ))
168
169 self.argument_spec.update(netapp_utils.na_ontap_lambda_argument_spec())
170
171 self.module = AnsibleModule(
172 argument_spec=self.argument_spec,
173 required_if=[
174 ('state', 'present', ['path']),
175 ('use_lambda', True, ['lambda_config'])
176 ],
177 supports_check_mode=True
178 )
179 self.lun_info = dict()
180
181 self.na_helper = NetAppModule()
182 self.parameters = self.na_helper.set_parameters(self.module.params)
183 self.rest_api = OntapRestAPI(self.module)
184 self.use_rest = self.rest_api.is_rest()
185 self.asa_r2_system = False
186 if self.use_rest:
187 if self.rest_api.meets_rest_minimum_version(self.use_rest, 9, 16, 0):
188 self.asa_r2_system = rest_ontap_personality.is_asa_r2_system(self.rest_api, self.module)
189 if self.asa_r2_system:
190 # If the path is passed as vol/vol1/lun_map it will be converted to lun_map for asa r2 systems.
191 if 'path' in self.parameters:
192 self.module.warn('For ASA r2 systems, The path should match the format <name>[@<snapshot-name>].'
193 'The name must begin with a letter or \"_\" and contain only \"_\" and alphanumeric character')
194 self.parameters['path'] = self.parameters.get('path').split("/")[-1]
195 if not self.use_rest:
196 if self.parameters.get('use_lambda'):
197 self.module.fail_json(msg="Error: AWS Lambda proxy for ONTAP APIs is only supported with REST.")
198 if HAS_NETAPP_LIB is False:
199 self.module.fail_json(msg="the python NetApp-Lib module is required")
200 else:
201 self.server = netapp_utils.setup_na_ontap_zapi(module=self.module, vserver=self.parameters['vserver'])
202
203 def get_lun_map(self):
204 """
205 Return details about the LUN map
206
207 :return: Details about the lun map
208 :rtype: dict
209 """
210 if self.use_rest:
211 return self.get_lun_map_rest()
212 lun_info = netapp_utils.zapi.NaElement('lun-map-list-info')
213 lun_info.add_new_child('path', self.parameters['path'])
214 result = self.server.invoke_successfully(lun_info, True)
215 return_value = None
216 igroups = result.get_child_by_name('initiator-groups')
217 if igroups:
218 for igroup_info in igroups.get_children():
219 initiator_group_name = igroup_info.get_child_content('initiator-group-name')
220 lun_id = igroup_info.get_child_content('lun-id')
221 if initiator_group_name == self.parameters['initiator_group_name']:
222 return_value = {
223 'lun_id': lun_id
224 }
225 break
226
227 return return_value
228
229 def get_lun(self):
230 """
231 Return details about the LUN
232
233 :return: Details about the lun
234 :rtype: dict
235 """
236 if self.use_rest:
237 return self.get_lun_rest()
238 # build the lun query
239 query_details = netapp_utils.zapi.NaElement('lun-info')
240 query_details.add_new_child('path', self.parameters['path'])
241
242 query = netapp_utils.zapi.NaElement('query')
243 query.add_child_elem(query_details)
244
245 lun_query = netapp_utils.zapi.NaElement('lun-get-iter')
246 lun_query.add_child_elem(query)
247
248 # find lun using query
249 result = self.server.invoke_successfully(lun_query, True)
250 return_value = None
251 if result.get_child_by_name('num-records') and int(result.get_child_content('num-records')) >= 1:
252 lun = result.get_child_by_name('attributes-list').get_child_by_name('lun-info')
253
254 return_value = {
255 'lun_node': lun.get_child_content('node'),
256 'lun_ostype': lun.get_child_content('multiprotocol-type'),
257 'lun_serial': lun.get_child_content('serial-number'),
258 'lun_naa_id': self.return_naa_id(lun.get_child_content('serial-number')),
259 'lun_state': lun.get_child_content('state'),
260 'lun_size': lun.get_child_content('size'),
261 }
262
263 return return_value
264
265 def return_naa_id(self, serial_number):
266 hexlify = codecs.getencoder('hex')
267 return '600a0980' + to_text(hexlify(to_bytes(serial_number))[0])
268
269 def create_lun_map(self):
270 """
271 Create LUN map
272 """
273 if self.use_rest:
274 return self.create_lun_map_rest()
275 options = {'path': self.parameters['path'], 'initiator-group': self.parameters['initiator_group_name']}
276 if self.parameters['lun_id'] is not None:
277 options['lun-id'] = self.parameters['lun_id']
278 lun_map_create = netapp_utils.zapi.NaElement.create_node_with_children('lun-map', **options)
279
280 try:
281 self.server.invoke_successfully(lun_map_create, enable_tunneling=True)
282 except netapp_utils.zapi.NaApiError as e:
283 self.module.fail_json(msg="Error mapping lun %s of initiator_group_name %s: %s" %
284 (self.parameters['path'], self.parameters['initiator_group_name'], to_native(e)),
285 exception=traceback.format_exc())
286
287 def delete_lun_map(self):
288 """
289 Unmap LUN map
290 """
291 if self.use_rest:
292 return self.delete_lun_map_rest()
293 lun_map_delete = netapp_utils.zapi.NaElement.create_node_with_children('lun-unmap', **{
294 'path': self.parameters['path'], 'initiator-group': self.parameters['initiator_group_name']})
295
296 try:
297 self.server.invoke_successfully(lun_map_delete, enable_tunneling=True)
298 except netapp_utils.zapi.NaApiError as e:
299 self.module.fail_json(msg="Error unmapping lun %s of initiator_group_name %s: %s" %
300 (self.parameters['path'], self.parameters['initiator_group_name'], to_native(e)),
301 exception=traceback.format_exc())
302
303 def get_lun_rest(self):
304 api = 'storage/luns'
305 params = {'name': self.parameters['path'],
306 'svm.name': self.parameters['vserver'],
307 'fields': 'name,'
308 'os_type,'
309 'serial_number,'
310 'status.state,'
311 'space.size,'
312 'uuid,'
313 'lun_maps'
314 }
315 record, error = rest_generic.get_one_record(self.rest_api, api, params)
316 if error:
317 self.module.fail_json(msg='Error getting lun %s: %s' % (self.parameters['path'], error))
318 if record:
319 return {'lun_ostype': self.na_helper.safe_get(record, ['os_type']),
320 'lun_serial': self.na_helper.safe_get(record, ['serial_number']),
321 'lun_naa_id': self.return_naa_id(self.na_helper.safe_get(record, ['serial_number'])),
322 'lun_state': self.na_helper.safe_get(record, ['status', 'state']),
323 'lun_size': self.na_helper.safe_get(record, ['space', 'size']),
324 }
325 return None
326
327 def get_lun_map_rest(self):
328 api = 'protocols/san/lun-maps'
329 params = {'lun.name': self.parameters['path'],
330 'svm.name': self.parameters['vserver'],
331 'igroup.name': self.parameters['initiator_group_name'],
332 'fields': 'logical_unit_number,igroup.uuid,lun.uuid,lun.name,igroup.name'
333 }
334 record, error = rest_generic.get_one_record(self.rest_api, api, params)
335 if error:
336 self.module.fail_json(msg='Error getting lun_map %s: %s' % (self.parameters['path'], error))
337 if record:
338 return {'lun_id': str(self.na_helper.safe_get(record, ['logical_unit_number'])),
339 'igroup_uuid': self.na_helper.safe_get(record, ['igroup', 'uuid']),
340 'initiator_group_name': self.na_helper.safe_get(record, ['igroup', 'name']),
341 'lun_uuid': self.na_helper.safe_get(record, ['lun', 'uuid']),
342 'path': self.na_helper.safe_get(record, ['lun', 'name']),
343 }
344 return None
345
346 def create_lun_map_rest(self):
347 api = 'protocols/san/lun-maps'
348 body = {'svm.name': self.parameters['vserver'],
349 'igroup.name': self.parameters['initiator_group_name'],
350 'lun.name': self.parameters['path']}
351 if self.parameters.get('lun_id') is not None:
352 body['logical_unit_number'] = self.parameters['lun_id']
353 dummy, error = rest_generic.post_async(self.rest_api, api, body, job_timeout=120)
354 if error:
355 self.module.fail_json(msg='Error creating lun_map %s: %s' % (self.parameters['path'], to_native(error)),
356 exception=traceback.format_exc())
357
358 def delete_lun_map_rest(self):
359 api = 'protocols/san/lun-maps'
360 both_uuids = '%s/%s' % (self.lun_uuid, self.igroup_uuid)
361 dummy, error = rest_generic.delete_async(self.rest_api, api, both_uuids, job_timeout=120)
362 if error:
363 self.module.fail_json(msg='Error deleting lun_map %s: %s' % (self.parameters['path'], to_native(error)),
364 exception=traceback.format_exc())
365
366 def apply(self):
367 lun_details = self.get_lun()
368 # why do we do this, it never used in the module, and has nothing to do with lun_map (it probably should be in
369 # the lun module
370 current = self.get_lun_map()
371 if self.use_rest and current:
372 self.lun_uuid = current.get('lun_uuid', None)
373 self.igroup_uuid = current.get('igroup_uuid', None)
374 cd_action = self.na_helper.get_cd_action(current, self.parameters)
375 if cd_action is None and self.parameters['state'] == 'present':
376 modify = self.na_helper.get_modified_attributes(current, self.parameters)
377 if modify:
378 self.module.fail_json(msg="Modification of lun_map not allowed")
379 if self.parameters['state'] == 'present' and lun_details:
380 self.lun_info.update(lun_details)
381 if self.na_helper.changed and not self.module.check_mode:
382 if cd_action == 'create':
383 self.create_lun_map()
384 if cd_action == 'delete':
385 self.delete_lun_map()
386 result = netapp_utils.generate_result(self.na_helper.changed, cd_action, extra_responses=self.lun_info)
387 self.module.exit_json(**result)
388
389
390 def main():
391 lun_mapping = NetAppOntapLUNMap()
392 lun_mapping.apply()
393
394
395 if __name__ == '__main__':
396 main()