Debian Codegraph @

ansible_collections/cisco/nxos/plugins/modules/nxos_vrf.py

raw
1 #!/usr/bin/python
2 #
3 # This file is part of Ansible
4 #
5 # Ansible is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Ansible is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
17 #
18 from __future__ import absolute_import, division, print_function
19
20
21 __metaclass__ = type
22
23
24 DOCUMENTATION = """
25 module: nxos_vrf
26 extends_documentation_fragment:
27 - cisco.nxos.nxos
28 short_description: (deprecated, removed after 2026-07-25) Manages global VRF configuration.
29 description:
30 - This module provides declarative management of VRFs on CISCO NXOS network devices.
31 version_added: 1.0.0
32 author:
33 - Jason Edelman (@jedelman8)
34 - Gabriele Gerbino (@GGabriele)
35 - Trishna Guha (@trishnaguha)
36 notes:
37 - Tested against NXOSv 7.3.(0)D1(1) on VIRL
38 - Unsupported for Cisco MDS
39 - Cisco NX-OS creates the default VRF by itself. Therefore, you're not allowed to
40 use default as I(vrf) name in this module.
41 - C(vrf) name must be shorter than 32 chars.
42 - VRF names are not case sensible in NX-OS. Anyway, the name is stored just like it's
43 inserted by the user and it'll not be changed again unless the VRF is removed and
44 re-created. i.e. C(vrf=NTC) will create a VRF named NTC, but running it again with
45 C(vrf=ntc) will not cause a configuration change.
46 options:
47 name:
48 description:
49 - Name of VRF to be managed.
50 aliases:
51 - vrf
52 type: str
53 admin_state:
54 description:
55 - Administrative state of the VRF.
56 default: up
57 choices:
58 - up
59 - down
60 type: str
61 vni:
62 description:
63 - Specify virtual network identifier. Valid values are Integer or keyword 'default'.
64 type: str
65 rd:
66 description:
67 - VPN Route Distinguisher (RD). Valid values are a string in one of the route-distinguisher
68 formats (ASN2:NN, ASN4:NN, or IPV4:NN); the keyword 'auto', or the keyword 'default'.
69 type: str
70 interfaces:
71 description:
72 - List of interfaces to check the VRF has been configured correctly or keyword
73 'default'.
74 type: list
75 elements: str
76 associated_interfaces:
77 description:
78 - This is a intent option and checks the operational state of the for given vrf
79 C(name) for associated interfaces. If the value in the C(associated_interfaces)
80 does not match with the operational state of vrf interfaces on device it will
81 result in failure.
82 type: list
83 elements: str
84 aggregate:
85 description: List of VRFs definitions.
86 type: list
87 elements: dict
88 suboptions:
89 name:
90 description:
91 - Name of VRF to be managed.
92 aliases:
93 - vrf
94 type: str
95 admin_state:
96 description:
97 - Administrative state of the VRF.
98 choices:
99 - up
100 - down
101 type: str
102 vni:
103 description:
104 - Specify virtual network identifier. Valid values are Integer or keyword 'default'.
105 type: str
106 rd:
107 description:
108 - VPN Route Distinguisher (RD). Valid values are a string in one of the route-distinguisher
109 formats (ASN2:NN, ASN4:NN, or IPV4:NN); the keyword 'auto', or the keyword 'default'.
110 type: str
111 interfaces:
112 description:
113 - List of interfaces to check the VRF has been configured correctly or keyword
114 'default'.
115 type: list
116 elements: str
117 associated_interfaces:
118 description:
119 - This is a intent option and checks the operational state of the for given vrf
120 C(name) for associated interfaces. If the value in the C(associated_interfaces)
121 does not match with the operational state of vrf interfaces on device it will
122 result in failure.
123 type: list
124 elements: str
125 state:
126 description:
127 - Manages desired state of the resource.
128 choices:
129 - present
130 - absent
131 type: str
132 description:
133 description:
134 - Description of the VRF or keyword 'default'.
135 type: str
136 delay:
137 description:
138 - Time in seconds to wait before checking for the operational state on remote
139 device. This wait is applicable for operational state arguments.
140 type: int
141 purge:
142 description:
143 - Purge VRFs not defined in the I(aggregate) parameter.
144 type: bool
145 default: false
146 state:
147 description:
148 - Manages desired state of the resource.
149 default: present
150 choices:
151 - present
152 - absent
153 type: str
154 description:
155 description:
156 - Description of the VRF or keyword 'default'.
157 type: str
158 delay:
159 description:
160 - Time in seconds to wait before checking for the operational state on remote
161 device. This wait is applicable for operational state arguments.
162 default: 10
163 type: int
164 """
165
166 EXAMPLES = """
167 - name: Ensure ntc VRF exists on switch
168 cisco.nxos.nxos_vrf:
169 name: ntc
170 description: testing
171 state: present
172 - name: Aggregate definition of VRFs
173 cisco.nxos.nxos_vrf:
174 aggregate:
175 - name: test1
176 description: Testing
177 admin_state: down
178 - name: test2
179 interfaces: Ethernet1/2
180 - name: Aggregate definitions of VRFs with Purge
181 cisco.nxos.nxos_vrf:
182 aggregate:
183 - name: ntc1
184 description: purge test1
185 - name: ntc2
186 description: purge test2
187 state: present
188 purge: true
189 - name: Delete VRFs exist on switch
190 cisco.nxos.nxos_vrf:
191 aggregate:
192 - name: ntc1
193 - name: ntc2
194 state: absent
195 - name: Assign interfaces to VRF declaratively
196 cisco.nxos.nxos_vrf:
197 name: test1
198 interfaces:
199 - Ethernet2/3
200 - Ethernet2/5
201 - name: Check interfaces assigned to VRF
202 cisco.nxos.nxos_vrf:
203 name: test1
204 associated_interfaces:
205 - Ethernet2/3
206 - Ethernet2/5
207 - name: >-
208 Ensure VRF is tagged with interface Ethernet2/5 only (Removes from
209 Ethernet2/3)
210 cisco.nxos.nxos_vrf:
211 name: test1
212 interfaces:
213 - Ethernet2/5
214 - name: Delete VRF
215 cisco.nxos.nxos_vrf:
216 name: ntc
217 state: absent
218 """
219
220 RETURN = """
221 commands:
222 description: commands sent to the device
223 returned: always
224 type: list
225 sample:
226 - vrf context ntc
227 - no shutdown
228 - interface Ethernet1/2
229 - no switchport
230 - vrf member test2
231 """
232
233 import re
234 import time
235
236 from copy import deepcopy
237
238 from ansible.module_utils.basic import AnsibleModule
239 from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import (
240 remove_default_spec,
241 )
242
243 from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.nxos import (
244 get_interface_type,
245 load_config,
246 run_commands,
247 )
248
249
250 def search_obj_in_list(name, lst):
251 for o in lst:
252 if o["name"] == name:
253 return o
254
255
256 def execute_show_command(command, module):
257 if "show run" not in command:
258 output = "json"
259 else:
260 output = "text"
261 cmds = [{"command": command, "output": output}]
262 body = run_commands(module, cmds)
263 return body
264
265
266 def get_existing_vrfs(module):
267 objs = list()
268 command = "show vrf all"
269 try:
270 body = execute_show_command(command, module)[0]
271 except IndexError:
272 return list()
273 try:
274 vrf_table = body["TABLE_vrf"]["ROW_vrf"]
275 except (TypeError, IndexError, KeyError):
276 return list()
277
278 if isinstance(vrf_table, list):
279 for vrf in vrf_table:
280 obj = {}
281 obj["name"] = vrf["vrf_name"]
282 objs.append(obj)
283
284 elif isinstance(vrf_table, dict):
285 obj = {}
286 obj["name"] = vrf_table["vrf_name"]
287 objs.append(obj)
288
289 return objs
290
291
292 def map_obj_to_commands(updates, module):
293 commands = list()
294 want, have = updates
295 state = module.params["state"]
296 purge = module.params["purge"]
297
298 args = ("rd", "description", "vni")
299
300 for w in want:
301 name = w["name"]
302 admin_state = w["admin_state"]
303 vni = w["vni"]
304 interfaces = w.get("interfaces") or []
305 if purge:
306 state = "absent"
307 else:
308 state = w["state"]
309 del w["state"]
310
311 obj_in_have = search_obj_in_list(name, have)
312 if state == "absent" and obj_in_have:
313 commands.append("no vrf context {0}".format(name))
314
315 elif state == "present":
316 if not obj_in_have:
317 commands.append("vrf context {0}".format(name))
318 for item in args:
319 candidate = w.get(item)
320 if candidate and candidate != "default":
321 cmd = item + " " + str(candidate)
322 commands.append(cmd)
323 if admin_state == "up":
324 commands.append("no shutdown")
325 elif admin_state == "down":
326 commands.append("shutdown")
327 commands.append("exit")
328
329 if interfaces and interfaces[0] != "default":
330 for i in interfaces:
331 commands.append("interface {0}".format(i))
332 if get_interface_type(i) in (
333 "ethernet",
334 "portchannel",
335 ):
336 commands.append("no switchport")
337 commands.append("vrf member {0}".format(name))
338
339 else:
340 # If vni is already configured on vrf, unconfigure it first.
341 if vni:
342 if obj_in_have.get("vni") and vni != obj_in_have.get("vni"):
343 commands.append("no vni {0}".format(obj_in_have.get("vni")))
344
345 for item in args:
346 candidate = w.get(item)
347 if candidate == "default":
348 if obj_in_have.get(item):
349 cmd = "no " + item + " " + obj_in_have.get(item)
350 commands.append(cmd)
351 elif candidate and candidate != obj_in_have.get(item):
352 cmd = item + " " + str(candidate)
353 commands.append(cmd)
354 if admin_state and admin_state != obj_in_have.get("admin_state"):
355 if admin_state == "up":
356 commands.append("no shutdown")
357 elif admin_state == "down":
358 commands.append("shutdown")
359
360 if commands:
361 commands.insert(0, "vrf context {0}".format(name))
362 commands.append("exit")
363
364 if interfaces and interfaces[0] != "default":
365 if not obj_in_have["interfaces"]:
366 for i in interfaces:
367 commands.append("vrf context {0}".format(name))
368 commands.append("exit")
369 commands.append("interface {0}".format(i))
370 if get_interface_type(i) in (
371 "ethernet",
372 "portchannel",
373 ):
374 commands.append("no switchport")
375 commands.append("vrf member {0}".format(name))
376
377 elif set(interfaces) != set(obj_in_have["interfaces"]):
378 missing_interfaces = list(
379 set(interfaces) - set(obj_in_have["interfaces"]),
380 )
381 for i in missing_interfaces:
382 commands.append("vrf context {0}".format(name))
383 commands.append("exit")
384 commands.append("interface {0}".format(i))
385 if get_interface_type(i) in (
386 "ethernet",
387 "portchannel",
388 ):
389 commands.append("no switchport")
390 commands.append("vrf member {0}".format(name))
391
392 superfluous_interfaces = list(
393 set(obj_in_have["interfaces"]) - set(interfaces),
394 )
395 for i in superfluous_interfaces:
396 commands.append("vrf context {0}".format(name))
397 commands.append("exit")
398 commands.append("interface {0}".format(i))
399 if get_interface_type(i) in (
400 "ethernet",
401 "portchannel",
402 ):
403 commands.append("no switchport")
404 commands.append("no vrf member {0}".format(name))
405 elif interfaces and interfaces[0] == "default":
406 if obj_in_have["interfaces"]:
407 for i in obj_in_have["interfaces"]:
408 commands.append("vrf context {0}".format(name))
409 commands.append("exit")
410 commands.append("interface {0}".format(i))
411 if get_interface_type(i) in (
412 "ethernet",
413 "portchannel",
414 ):
415 commands.append("no switchport")
416 commands.append("no vrf member {0}".format(name))
417
418 if purge:
419 existing = get_existing_vrfs(module)
420 if existing:
421 for h in existing:
422 if h["name"] in ("default", "management"):
423 pass
424 else:
425 obj_in_want = search_obj_in_list(h["name"], want)
426 if not obj_in_want:
427 commands.append("no vrf context {0}".format(h["name"]))
428
429 return commands
430
431
432 def validate_vrf(name, module):
433 if name:
434 name = name.strip()
435 if name == "default":
436 module.fail_json(msg="cannot use default as name of a VRF")
437 elif len(name) > 32:
438 module.fail_json(msg="VRF name exceeded max length of 32", name=name)
439 else:
440 return name
441
442
443 def map_params_to_obj(module):
444 obj = []
445 aggregate = module.params.get("aggregate")
446 if aggregate:
447 for item in aggregate:
448 for key in item:
449 if item.get(key) is None:
450 item[key] = module.params[key]
451
452 d = item.copy()
453 d["name"] = validate_vrf(d["name"], module)
454 obj.append(d)
455 else:
456 obj.append(
457 {
458 "name": validate_vrf(module.params["name"], module),
459 "description": module.params["description"],
460 "vni": module.params["vni"],
461 "rd": module.params["rd"],
462 "admin_state": module.params["admin_state"],
463 "state": module.params["state"],
464 "interfaces": module.params["interfaces"],
465 "associated_interfaces": module.params["associated_interfaces"],
466 },
467 )
468 return obj
469
470
471 def get_value(arg, config, module):
472 extra_arg_regex = re.compile(r"(?:{0}\s)(?P<value>.*)$".format(arg), re.M)
473 value = ""
474 if arg in config:
475 value = extra_arg_regex.search(config).group("value")
476 return value
477
478
479 def map_config_to_obj(want, element_spec, module):
480 objs = list()
481
482 for w in want:
483 obj = deepcopy(element_spec)
484 del obj["delay"]
485 del obj["state"]
486
487 command = "show vrf {0}".format(w["name"])
488 try:
489 body = execute_show_command(command, module)[0]
490 vrf_table = body["TABLE_vrf"]["ROW_vrf"]
491 except (TypeError, IndexError):
492 return list()
493
494 name = vrf_table["vrf_name"]
495 obj["name"] = name
496 obj["admin_state"] = vrf_table["vrf_state"].lower()
497
498 command = "show run all | section vrf.context.{0}".format(name)
499 body = execute_show_command(command, module)[0]
500 extra_params = ["vni", "rd", "description"]
501 for param in extra_params:
502 obj[param] = get_value(param, body, module)
503
504 obj["interfaces"] = []
505 command = "show vrf {0} interface".format(name)
506 try:
507 body = execute_show_command(command, module)[0]
508 vrf_int = body["TABLE_if"]["ROW_if"]
509 except (TypeError, IndexError):
510 vrf_int = None
511
512 if vrf_int:
513 if isinstance(vrf_int, list):
514 for i in vrf_int:
515 intf = i["if_name"]
516 obj["interfaces"].append(intf)
517 elif isinstance(vrf_int, dict):
518 intf = vrf_int["if_name"]
519 obj["interfaces"].append(intf)
520
521 objs.append(obj)
522 return objs
523
524
525 def check_declarative_intent_params(want, module, element_spec, result):
526 have = None
527 is_delay = False
528
529 for w in want:
530 if w.get("associated_interfaces") is None:
531 continue
532
533 if result["changed"] and not is_delay:
534 time.sleep(module.params["delay"])
535 is_delay = True
536
537 if have is None:
538 have = map_config_to_obj(want, element_spec, module)
539
540 for i in w["associated_interfaces"]:
541 obj_in_have = search_obj_in_list(w["name"], have)
542
543 if obj_in_have:
544 interfaces = obj_in_have.get("interfaces")
545 if interfaces is not None and i not in interfaces:
546 module.fail_json(
547 msg="Interface %s not configured on vrf %s" % (i, w["name"]),
548 )
549
550
551 def vrf_error_check(module, commands, responses):
552 """Checks for VRF config errors and executes a retry in some circumstances."""
553 pattern = "ERROR: Deletion of VRF .* in progress"
554 if re.search(pattern, str(responses)):
555 # Allow delay/retry for VRF changes
556 time.sleep(15)
557 responses = load_config(module, commands, opts={"catch_clierror": True})
558 if re.search(pattern, str(responses)):
559 module.fail_json(msg="VRF config (and retry) failure: %s " % responses)
560 module.warn("VRF config delayed by VRF deletion - passed on retry")
561
562
563 def main():
564 """main entry point for module execution"""
565 element_spec = dict(
566 name=dict(type="str", aliases=["vrf"]),
567 description=dict(type="str"),
568 vni=dict(type="str"),
569 rd=dict(type="str"),
570 admin_state=dict(type="str", default="up", choices=["up", "down"]),
571 interfaces=dict(type="list", elements="str"),
572 associated_interfaces=dict(type="list", elements="str"),
573 delay=dict(type="int", default=10),
574 state=dict(type="str", default="present", choices=["present", "absent"]),
575 )
576
577 aggregate_spec = deepcopy(element_spec)
578
579 # remove default in aggregate spec, to handle common arguments
580 remove_default_spec(aggregate_spec)
581
582 argument_spec = dict(
583 aggregate=dict(type="list", elements="dict", options=aggregate_spec),
584 purge=dict(type="bool", default=False),
585 )
586
587 argument_spec.update(element_spec)
588
589 required_one_of = [["name", "aggregate"]]
590 mutually_exclusive = [["name", "aggregate"]]
591 module = AnsibleModule(
592 argument_spec=argument_spec,
593 required_one_of=required_one_of,
594 mutually_exclusive=mutually_exclusive,
595 supports_check_mode=True,
596 )
597
598 warnings = list()
599 result = {"changed": False}
600 if warnings:
601 result["warnings"] = warnings
602
603 want = map_params_to_obj(module)
604 have = map_config_to_obj(want, element_spec, module)
605
606 commands = map_obj_to_commands((want, have), module)
607 result["commands"] = commands
608
609 if commands and not module.check_mode:
610 responses = load_config(module, commands, opts={"catch_clierror": True})
611 vrf_error_check(module, commands, responses)
612 result["changed"] = True
613
614 check_declarative_intent_params(want, module, element_spec, result)
615
616 module.exit_json(**result)
617
618
619 if __name__ == "__main__":
620 main()