Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # (c) 2018-2025, NetApp, Inc
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 '''
7 na_ontap_net_ifgrp
8 '''
9
10 from __future__ import absolute_import, division, print_function
11 __metaclass__ = type
12
13 DOCUMENTATION = """
14 module: na_ontap_net_ifgrp
15 short_description: NetApp Ontap modify network interface group
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 description:
21 - Create, modify ports, destroy the network interface group
22 options:
23 state:
24 description:
25 - Whether the specified network interface group should exist or not.
26 choices: ['present', 'absent']
27 type: str
28 default: present
29
30 distribution_function:
31 description:
32 - Specifies the traffic distribution function for the ifgrp.
33 choices: ['mac', 'ip', 'sequential', 'port']
34 type: str
35
36 name:
37 description:
38 - Specifies the interface group name.
39 - Not supported with REST, use C(ports) or C(from_lag_ports). LAG names are automatically created in REST and returned in module output.
40 - Required with ZAPI.
41 type: str
42
43 mode:
44 description:
45 - Specifies the link policy for the ifgrp.
46 choices: ['multimode', 'multimode_lacp', 'singlemode']
47 type: str
48
49 node:
50 description:
51 - Specifies the name of node.
52 required: true
53 type: str
54
55 ports:
56 aliases:
57 - port
58 description:
59 - List of expected ports to be present in the interface group.
60 - If a port is present in this list, but not on the target, it will be added.
61 - If a port is not in the list, but present on the target, it will be removed.
62 - Make sure the list contains all ports you want to see on the target.
63 - With REST, ports in this list are used to find the current LAG port.
64 - If LAG is not found or only partial port matches, then C(from_lag_port) are used to get the current LAG.
65 - With REST, when C(state=absent) is set, all of the ports in ifgrp should be provided to delete it.
66 - Example C(ports=['e0c','e0a']) will delete ifgrp that has ports C(['e0c','e0a']).
67 version_added: 2.8.0
68 type: list
69 elements: str
70
71 from_lag_ports:
72 description:
73 - Only supported with REST and is ignored with ZAPI.
74 - Specify all the ports to find current LAG port.
75 - Ignored if LAG found with exact match of C(ports).
76 - Example if current LAG has ports C(['e0c','e0d']) and C(ports=['e0c','e0d']), then from_lag_ports will be ignored.
77 - If LAG not found with C(ports), then ports in this list are used to find the current LAG.
78 - Ports in this list are used only for finding current LAG, provide exact match of all the ports in the current LAG.
79 - Ignored when C(state=absent).
80 version_added: 2.14.0
81 type: list
82 elements: str
83
84 broadcast_domain:
85 description:
86 - Specify the broadcast_domain name.
87 - Only supported with REST and is ignored with ZAPI.
88 - Required with ONTAP 9.6 and 9.7, but optional with 9.8 or later.
89 type: str
90 version_added: 21.14.0
91
92 ipspace:
93 description:
94 - Specify the ipspace for the broadcast domain.
95 - Only supported with REST and is ignored with ZAPI.
96 - Required with ONTAP 9.6 and 9.7, but optional with 9.8 or later.
97 type: str
98 version_added: 21.14.0
99 """
100
101 EXAMPLES = """
102 - name: Create ifgrp
103 netapp.ontap.na_ontap_net_ifgrp:
104 state: present
105 username: "{{ netapp_username }}"
106 password: "{{ netapp_password }}"
107 hostname: "{{ netapp_hostname }}"
108 distribution_function: ip
109 name: a0c
110 ports: [e0a]
111 mode: multimode
112 node: "{{ vsim_node_name }}"
113
114 - name: Modify ports in an ifgrp
115 netapp.ontap.na_ontap_net_ifgrp:
116 state: present
117 username: "{{ netapp_username }}"
118 password: "{{ netapp_password }}"
119 hostname: "{{ netapp_hostname }}"
120 distribution_function: ip
121 name: a0c
122 port: [e0a, e0c]
123 mode: multimode
124 node: "{{ vsim_node_name }}"
125
126 - name: Delete ifgrp
127 netapp.ontap.na_ontap_net_ifgrp:
128 state: absent
129 username: "{{ netapp_username }}"
130 password: "{{ netapp_password }}"
131 hostname: "{{ netapp_hostname }}"
132 name: a0c
133 node: "{{ vsim_node_name }}"
134
135 - name: Create ifgrp - REST
136 netapp.ontap.na_ontap_net_ifgrp:
137 state: present
138 username: "{{ netapp_username }}"
139 password: "{{ netapp_password }}"
140 hostname: "{{ netapp_hostname }}"
141 distribution_function: ip
142 ports: [e0a, e0b]
143 mode: multimode
144 node: "{{ vsim_node_name }}"
145 broadcast_domain: Default
146 ipspace: Default
147
148 - name: Remove e0a and add port e0d to above created lag REST
149 netapp.ontap.na_ontap_net_ifgrp:
150 state: present
151 username: "{{ netapp_username }}"
152 password: "{{ netapp_password }}"
153 hostname: "{{ netapp_hostname }}"
154 from_lag_ports: [a0a, e0b]
155 ports: [e0b, e0d]
156 node: "{{ vsim_node_name }}"
157
158 - name: Add e0a to lag that has port e0b e0d REST
159 netapp.ontap.na_ontap_net_ifgrp:
160 state: present
161 username: "{{ netapp_username }}"
162 password: "{{ netapp_password }}"
163 hostname: "{{ netapp_hostname }}"
164 distribution_function: ip
165 ports: [e0b, e0d, e0a]
166 mode: multimode
167 node: "{{ vsim_node_name }}"
168
169 - name: Modify broadcast_domain and ipspace REST
170 netapp.ontap.na_ontap_net_ifgrp:
171 state: present
172 username: "{{ netapp_username }}"
173 password: "{{ netapp_password }}"
174 hostname: "{{ netapp_hostname }}"
175 broadcast_domain: test
176 ipspace: test
177 ports: [e0b, e0d, e0a]
178 node: "{{ vsim_node_name }}"
179
180 - name: Delete LAG with exact match of ports
181 netapp.ontap.na_ontap_net_ifgrp:
182 state: absent
183 username: "{{ netapp_username }}"
184 password: "{{ netapp_password }}"
185 hostname: "{{ netapp_hostname }}"
186 ports: [e0b, e0d, e0a]
187 node: "{{ vsim_node_name }}"
188 """
189
190 RETURN = """
191
192 """
193
194 import traceback
195
196 from ansible.module_utils.basic import AnsibleModule
197 from ansible_collections.netapp.ontap.plugins.module_utils.netapp_module import NetAppModule
198 from ansible.module_utils._text import to_native
199 import ansible_collections.netapp.ontap.plugins.module_utils.netapp as netapp_utils
200 from ansible_collections.netapp.ontap.plugins.module_utils.netapp import OntapRestAPI
201 from ansible_collections.netapp.ontap.plugins.module_utils import rest_generic
202
203
204 class NetAppOntapIfGrp:
205 """
206 Create, Modifies and Destroys a IfGrp
207 """
208 def __init__(self):
209 """
210 Initialize the Ontap IfGrp class
211 """
212 self.argument_spec = netapp_utils.na_ontap_host_argument_spec()
213 self.argument_spec.update(dict(
214 state=dict(required=False, type='str', choices=['present', 'absent'], default='present'),
215 distribution_function=dict(required=False, type='str', choices=['mac', 'ip', 'sequential', 'port']),
216 name=dict(required=False, type='str'),
217 mode=dict(required=False, type='str', choices=['multimode', 'multimode_lacp', 'singlemode']),
218 node=dict(required=True, type='str'),
219 ports=dict(required=False, type='list', elements='str', aliases=["port"]),
220 from_lag_ports=dict(required=False, type='list', elements='str'),
221 broadcast_domain=dict(required=False, type='str'),
222 ipspace=dict(required=False, type='str')
223 ))
224
225 self.module = AnsibleModule(
226 argument_spec=self.argument_spec,
227 required_if=[
228 ('state', 'present', ['distribution_function', 'mode'])
229 ],
230 required_together=[['broadcast_domain', 'ipspace']],
231 supports_check_mode=True
232 )
233
234 self.current_records = []
235
236 # set up variables
237 self.na_helper = NetAppModule()
238 self.parameters = self.na_helper.set_parameters(self.module.params)
239
240 # Set up Rest API
241 self.rest_api = OntapRestAPI(self.module)
242
243 # if rest and use_rest: auto and name is present, revert to zapi
244 # if rest and use_rest: always and name is present, throw error.
245 unsupported_rest_properties = ['name']
246 self.use_rest = self.rest_api.is_rest_supported_properties(self.parameters, unsupported_rest_properties)
247 if self.use_rest:
248 # if rest and ports is not present, throw error as ports is a required field with REST
249 if 'ports' not in self.parameters:
250 error_msg = "Error: ports is a required field with REST"
251 self.module.fail_json(msg=error_msg)
252
253 required_options = ['broadcast_domain', 'ipspace']
254 min_ontap_98 = self.rest_api.meets_rest_minimum_version(self.use_rest, 9, 8, 0)
255 if not min_ontap_98 and not any(x in self.parameters for x in required_options):
256 error_msg = "'%s' are mandatory fields with ONTAP 9.6 and 9.7" % ', '.join(required_options)
257 self.module.fail_json(msg=error_msg)
258 else:
259 if not netapp_utils.has_netapp_lib():
260 self.module.fail_json(msg=netapp_utils.netapp_lib_is_required())
261 if 'name' not in self.parameters:
262 self.module.fail_json("Error: name is a required field with ZAPI.")
263 if 'broadcast_domain' in self.parameters or 'ipspace' in self.parameters or 'from_lag_ports' in self.parameters:
264 msg = 'Using ZAPI and ignoring options - broadcast_domain, ipspace and from_lag_ports'
265 self.module.warn(msg)
266 self.parameters.pop('broadcast_domain', None)
267 self.parameters.pop('ipspace', None)
268 self.parameters.pop('from_lag_ports', None)
269 self.server = netapp_utils.setup_na_ontap_zapi(module=self.module)
270
271 def get_if_grp(self):
272 """
273 Return details about the if_group
274 :param:
275 name : Name of the if_group
276
277 :return: Details about the if_group. None if not found.
278 :rtype: dict
279 """
280 if_group_iter = netapp_utils.zapi.NaElement('net-port-get-iter')
281 if_group_info = netapp_utils.zapi.NaElement('net-port-info')
282 if_group_info.add_new_child('port', self.parameters['name'])
283 if_group_info.add_new_child('port-type', 'if_group')
284 if_group_info.add_new_child('node', self.parameters['node'])
285 query = netapp_utils.zapi.NaElement('query')
286 query.add_child_elem(if_group_info)
287 if_group_iter.add_child_elem(query)
288 try:
289 result = self.server.invoke_successfully(if_group_iter, True)
290 except netapp_utils.zapi.NaApiError as error:
291 self.module.fail_json(msg='Error getting if_group %s: %s' % (self.parameters['name'], to_native(error)),
292 exception=traceback.format_exc())
293
294 return_value = None
295
296 if result.get_child_by_name('num-records') and int(result['num-records']) >= 1:
297 if_group_attributes = result['attributes-list']['net-port-info']
298 return_value = {
299 'name': if_group_attributes['port'],
300 'distribution_function': if_group_attributes['ifgrp-distribution-function'],
301 'mode': if_group_attributes['ifgrp-mode'],
302 'node': if_group_attributes['node'],
303 }
304 return return_value
305
306 def get_if_grp_rest(self, ports, allow_partial_match, force=False):
307 api = 'network/ethernet/ports'
308 query = {
309 'type': 'lag',
310 'node.name': self.parameters['node'],
311 }
312 fields = 'name,node,uuid,broadcast_domain,lag'
313 error = None
314 if not self.current_records or force:
315 self.current_records, error = rest_generic.get_0_or_more_records(self.rest_api, api, query, fields)
316 if error:
317 self.module.fail_json(msg=error)
318 if self.current_records:
319 current_ifgrp = self.get_if_grp_current(self.current_records, ports)
320 if current_ifgrp:
321 exact_match = self.check_exact_match(ports, current_ifgrp['ports'])
322 if exact_match or allow_partial_match:
323 return current_ifgrp, exact_match
324 return None, None
325
326 def check_exact_match(self, desired_ports, current_ifgrp):
327 matched = set(desired_ports) == set(current_ifgrp)
328 if not matched:
329 self.rest_api.log_debug(0, "found LAG with partial match of ports: %s but current is %s" % (desired_ports, current_ifgrp))
330 return matched
331
332 def get_if_grp_current(self, records, ports):
333 desired_ifgrp_in_current = []
334 for record in records:
335 if 'member_ports' in record['lag']:
336 current_port_list = [port['name'] for port in record['lag']['member_ports']]
337 for current_port in current_port_list:
338 if current_port in ports:
339 desired_ifgrp_in_current.append(self.get_if_grp_detail(record, current_port_list))
340 break
341 # if ports are in different LAGs and state is absent, return None
342 if len(desired_ifgrp_in_current) > 1 and self.parameters['state'] == 'present':
343 error_msg = "'%s' are in different LAGs" % ', '.join(ports)
344 self.module.fail_json(msg=error_msg)
345 elif len(desired_ifgrp_in_current) == 1:
346 return desired_ifgrp_in_current[0]
347 return None
348
349 def get_if_grp_detail(self, record, current_port_list):
350 current = {
351 'node': record['node']['name'],
352 'uuid': record['uuid'],
353 'name': record['name'],
354 'ports': current_port_list
355 }
356 if record.get('broadcast_domain'):
357 current['broadcast_domain'] = record['broadcast_domain']['name']
358 current['ipspace'] = record['broadcast_domain']['ipspace']['name']
359 return current
360
361 def get_if_grp_ports(self):
362 """
363 Return ports of the if_group
364 :param:
365 name : Name of the if_group
366 :return: Ports of the if_group. None if not found.
367 :rtype: dict
368 """
369 if_group_iter = netapp_utils.zapi.NaElement('net-port-ifgrp-get')
370 if_group_iter.add_new_child('ifgrp-name', self.parameters['name'])
371 if_group_iter.add_new_child('node', self.parameters['node'])
372 try:
373 result = self.server.invoke_successfully(if_group_iter, True)
374 except netapp_utils.zapi.NaApiError as error:
375 self.module.fail_json(msg='Error getting if_group ports %s: %s' % (self.parameters['name'], to_native(error)),
376 exception=traceback.format_exc())
377
378 port_list = []
379 if result.get_child_by_name('attributes'):
380 if_group_attributes = result['attributes']['net-ifgrp-info']
381 if if_group_attributes.get_child_by_name('ports'):
382 ports = if_group_attributes.get_child_by_name('ports').get_children()
383 for each in ports:
384 port_list.append(each.get_content())
385 return {'ports': port_list}
386
387 def create_if_grp(self):
388 """
389 Creates a new ifgrp
390 """
391 if self.use_rest:
392 return self.create_if_grp_rest()
393 route_obj = netapp_utils.zapi.NaElement("net-port-ifgrp-create")
394 route_obj.add_new_child("distribution-function", self.parameters['distribution_function'])
395 route_obj.add_new_child("ifgrp-name", self.parameters['name'])
396 route_obj.add_new_child("mode", self.parameters['mode'])
397 route_obj.add_new_child("node", self.parameters['node'])
398 try:
399 self.server.invoke_successfully(route_obj, True)
400 except netapp_utils.zapi.NaApiError as error:
401 self.module.fail_json(msg='Error creating if_group %s: %s' % (self.parameters['name'], to_native(error)),
402 exception=traceback.format_exc())
403 if self.parameters.get('ports') is not None:
404 for port in self.parameters.get('ports'):
405 self.add_port_to_if_grp(port)
406
407 def create_if_grp_rest(self):
408 api = 'network/ethernet/ports'
409 body = {
410 'type': 'lag',
411 'node': {'name': self.parameters['node']},
412 'lag': {
413 "mode": self.parameters['mode'],
414 "distribution_policy": self.parameters['distribution_function']
415 }
416 }
417 if self.parameters.get('ports') is not None:
418 body['lag']['member_ports'] = self.build_member_ports()
419 if 'broadcast_domain' in self.parameters:
420 body['broadcast_domain'] = {'name': self.parameters['broadcast_domain']}
421 body['broadcast_domain']['ipspace'] = {'name': self.parameters['ipspace']}
422 dummy, error = rest_generic.post_async(self.rest_api, api, body)
423 if error:
424 self.module.fail_json(msg=error)
425
426 def delete_if_grp(self, uuid=None):
427 """
428 Deletes a ifgrp
429 """
430 if self.use_rest:
431 api = 'network/ethernet/ports'
432 dummy, error = rest_generic.delete_async(self.rest_api, api, uuid)
433 if error:
434 self.module.fail_json(msg=error)
435 else:
436 route_obj = netapp_utils.zapi.NaElement("net-port-ifgrp-destroy")
437 route_obj.add_new_child("ifgrp-name", self.parameters['name'])
438 route_obj.add_new_child("node", self.parameters['node'])
439 try:
440 self.server.invoke_successfully(route_obj, True)
441 except netapp_utils.zapi.NaApiError as error:
442 self.module.fail_json(msg='Error deleting if_group %s: %s' % (self.parameters['name'], to_native(error)),
443 exception=traceback.format_exc())
444
445 def add_port_to_if_grp(self, port):
446 """
447 adds port to a ifgrp
448 """
449 route_obj = netapp_utils.zapi.NaElement("net-port-ifgrp-add-port")
450 route_obj.add_new_child("ifgrp-name", self.parameters['name'])
451 route_obj.add_new_child("port", port)
452 route_obj.add_new_child("node", self.parameters['node'])
453 try:
454 self.server.invoke_successfully(route_obj, True)
455 except netapp_utils.zapi.NaApiError as error:
456 self.module.fail_json(msg='Error adding port %s to if_group %s: %s' %
457 (port, self.parameters['name'], to_native(error)),
458 exception=traceback.format_exc())
459
460 def modify_ports(self, current_ports):
461 add_ports = set(self.parameters['ports']) - set(current_ports)
462 remove_ports = set(current_ports) - set(self.parameters['ports'])
463 for port in add_ports:
464 self.add_port_to_if_grp(port)
465 for port in remove_ports:
466 self.remove_port_to_if_grp(port)
467
468 def modify_ports_rest(self, modify, uuid):
469 api = 'network/ethernet/ports'
470 body = {}
471 if 'ports' in modify:
472 member_ports = self.build_member_ports()
473 body['lag'] = {'member_ports': member_ports}
474 if 'broadcast_domain' in modify or 'ipspace' in modify:
475 broadcast_domain = modify['broadcast_domain'] if 'broadcast_domain' in modify else self.parameters['broadcast_domain']
476 ipspace = modify['ipspace'] if 'ipspace' in modify else self.parameters['ipspace']
477 body['broadcast_domain'] = {'name': broadcast_domain}
478 body['broadcast_domain']['ipspace'] = {'name': ipspace}
479 dummy, error = rest_generic.patch_async(self.rest_api, api, uuid, body)
480 if error:
481 self.module.fail_json(msg=error)
482
483 def build_member_ports(self):
484 member_ports = []
485 for port in self.parameters['ports']:
486 port_detail = {'name': port, 'node': {'name': self.parameters['node']}}
487 member_ports.append(port_detail)
488 return member_ports
489
490 def remove_port_to_if_grp(self, port):
491 """
492 removes port from a ifgrp
493 """
494 route_obj = netapp_utils.zapi.NaElement("net-port-ifgrp-remove-port")
495 route_obj.add_new_child("ifgrp-name", self.parameters['name'])
496 route_obj.add_new_child("port", port)
497 route_obj.add_new_child("node", self.parameters['node'])
498 try:
499 self.server.invoke_successfully(route_obj, True)
500 except netapp_utils.zapi.NaApiError as error:
501 self.module.fail_json(msg='Error removing port %s to if_group %s: %s' %
502 (port, self.parameters['name'], to_native(error)),
503 exception=traceback.format_exc())
504
505 def apply(self):
506 # for a LAG, rename is equivalent to adding/removing ports from an existing LAG.
507 current, exact_match, modify, rename = None, True, None, None
508 response = None
509 if not self.use_rest:
510 current = self.get_if_grp()
511 elif self.use_rest:
512 current, exact_match = self.get_if_grp_rest(self.parameters.get('ports'), allow_partial_match=True)
513 cd_action = self.na_helper.get_cd_action(current if exact_match else None, self.parameters)
514 if cd_action == 'create' and self.use_rest:
515 # if we could not find a lag, or only a lag with a partial match, do a new query using from_lag_ports.
516 if self.parameters.get('from_lag_ports') is not None:
517 from_ifgrp, dummy = self.get_if_grp_rest(self.parameters['from_lag_ports'], allow_partial_match=False)
518 if not from_ifgrp:
519 error_msg = "Error: cannot find LAG matching from_lag_ports: '%s'." % self.parameters['from_lag_ports']
520 self.module.fail_json(msg=error_msg)
521 rename = True
522 current = from_ifgrp
523 # if we have a partial match with an existing LAG, we will update the ports.
524 elif not exact_match and current:
525 rename = True
526 if rename:
527 cd_action = None
528 if cd_action is None and self.parameters['state'] == 'present':
529 # with rest, current will have the port details
530 current_ports = self.get_if_grp_ports() if not self.use_rest else current
531 modify = self.na_helper.get_modified_attributes(current_ports, self.parameters)
532 if self.na_helper.changed and not self.module.check_mode:
533 uuid = current['uuid'] if current and self.use_rest else None
534 if cd_action == 'create':
535 self.create_if_grp()
536 # While using REST, fetch the name of the created LAG and return as response in result
537 if self.use_rest:
538 response, exact_match = self.get_if_grp_rest(self.parameters.get('ports'), allow_partial_match=True, force=True)
539 elif cd_action == 'delete':
540 self.delete_if_grp(uuid)
541 elif modify:
542 if self.use_rest:
543 self.modify_ports_rest(modify, uuid)
544 else:
545 self.modify_ports(current_ports['ports'])
546 result = netapp_utils.generate_result(self.na_helper.changed, cd_action, modify, response=response)
547 self.module.exit_json(**result)
548
549
550 def main():
551 """
552 Creates the NetApp Ontap Net Route object and runs the correct play task
553 """
554 obj = NetAppOntapIfGrp()
555 obj.apply()
556
557
558 if __name__ == '__main__':
559 main()