Debian Codegraph @

ansible_collections/cisco/nxos/plugins/modules/nxos_vpc.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_vpc
26 extends_documentation_fragment:
27 - cisco.nxos.nxos
28 short_description: Manages global VPC configuration
29 description:
30 - Manages global VPC configuration
31 version_added: 1.0.0
32 author:
33 - Jason Edelman (@jedelman8)
34 - Gabriele Gerbino (@GGabriele)
35 notes:
36 - Tested against NXOSv 7.3.(0)D1(1) on VIRL
37 - Unsupported for Cisco MDS
38 - The feature vpc must be enabled before this module can be used
39 - If not using management vrf, vrf must be globally on the device before using in
40 the pkl config
41 - Although source IP isn't required on the command line it is required when using
42 this module. The PKL VRF must also be configured prior to using this module.
43 - Both pkl_src and pkl_dest are needed when changing PKL VRF.
44 options:
45 domain:
46 description:
47 - VPC domain
48 required: true
49 type: str
50 role_priority:
51 description:
52 - Role priority for device. Remember lower is better.
53 type: str
54 system_priority:
55 description:
56 - System priority device. Remember they must match between peers.
57 type: str
58 pkl_src:
59 description:
60 - Source IP address used for peer keepalive link
61 type: str
62 pkl_dest:
63 description:
64 - Destination (remote) IP address used for peer keepalive link
65 - pkl_dest is required whenever pkl options are used.
66 type: str
67 pkl_vrf:
68 description:
69 - VRF used for peer keepalive link
70 - The VRF must exist on the device before using pkl_vrf.
71 - "(Note) 'default' is an overloaded term: Default vrf context for pkl_vrf is
72 'management'; 'pkl_vrf: default' refers to the literal 'default' rib."
73 type: str
74 peer_gw:
75 description:
76 - Enables/Disables peer gateway
77 type: bool
78 peer_sw:
79 description:
80 - Enables/Disables peer-switch
81 type: bool
82 auto_recovery:
83 description:
84 - Enables/Disables auto recovery on platforms that support disable
85 - timers are not modifiable with this attribute
86 - mutually exclusive with auto_recovery_reload_delay
87 type: bool
88 auto_recovery_reload_delay:
89 description:
90 - Manages auto-recovery reload-delay timer in seconds
91 - mutually exclusive with auto_recovery
92 type: str
93 delay_restore:
94 description:
95 - manages delay restore command and config value in seconds
96 type: str
97 delay_restore_interface_vlan:
98 description:
99 - manages delay restore interface-vlan command and config value in seconds
100 - not supported on all platforms
101 type: str
102 delay_restore_orphan_port:
103 description:
104 - manages delay restore orphan-port command and config value in seconds
105 - not supported on all platforms
106 type: str
107 state:
108 description:
109 - Manages desired state of the resource
110 default: present
111 choices:
112 - present
113 - absent
114 type: str
115 """
116
117 EXAMPLES = """
118 - name: configure a simple asn
119 cisco.nxos.nxos_vpc:
120 domain: 100
121 role_priority: 1000
122 system_priority: 2000
123 pkl_dest: 192.168.100.4
124 pkl_src: 10.1.100.20
125 peer_gw: true
126 peer_sw: true
127 auto_recovery: true
128
129 - name: configure
130 cisco.nxos.nxos_vpc:
131 domain: 100
132 role_priority: 32667
133 system_priority: 2000
134 peer_gw: true
135 peer_sw: true
136 pkl_src: 10.1.100.2
137 pkl_dest: 192.168.100.4
138 auto_recovery: true
139
140 - name: Configure VPC with delay restore and existing keepalive VRF
141 cisco.nxos.nxos_vpc:
142 domain: 10
143 role_priority: 28672
144 system_priority: 2000
145 delay_restore: 180
146 peer_gw: true
147 peer_sw: true
148 pkl_src: 1.1.1.2
149 pkl_dest: 1.1.1.1
150 pkl_vrf: vpckeepalive
151 auto_recovery: true
152 """
153
154 RETURN = """
155 commands:
156 description: commands sent to the device
157 returned: always
158 type: list
159 sample: ["vpc domain 100",
160 "peer-keepalive destination 192.168.100.4 source 10.1.100.20 vrf management",
161 "auto-recovery", "peer-gateway","peer-switch"]
162 """
163
164 import re
165
166 from ansible.module_utils.basic import AnsibleModule
167
168 from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.nxos import (
169 get_config,
170 load_config,
171 run_commands,
172 )
173
174
175 CONFIG_ARGS = {
176 "role_priority": "role priority {role_priority}",
177 "system_priority": "system-priority {system_priority}",
178 "delay_restore": "delay restore {delay_restore}",
179 "delay_restore_interface_vlan": "delay restore interface-vlan {delay_restore_interface_vlan}",
180 "delay_restore_orphan_port": "delay restore orphan-port {delay_restore_orphan_port}",
181 "peer_sw": "{peer_sw} peer-switch",
182 "peer_gw": "{peer_gw} peer-gateway",
183 "auto_recovery": "{auto_recovery} auto-recovery",
184 "auto_recovery_reload_delay": "auto-recovery reload-delay {auto_recovery_reload_delay}",
185 }
186
187 PARAM_TO_DEFAULT_KEYMAP = {
188 "delay_restore": "60",
189 "delay_restore_interface_vlan": "10",
190 "delay_restore_orphan_port": "0",
191 "role_priority": "32667",
192 "system_priority": "32667",
193 "peer_gw": False,
194 "peer_sw": False,
195 "auto_recovery_reload_delay": 240,
196 }
197
198
199 def flatten_list(command_lists):
200 flat_command_list = []
201 for command in command_lists:
202 if isinstance(command, list):
203 flat_command_list.extend(command)
204 else:
205 flat_command_list.append(command)
206 return flat_command_list
207
208
209 def get_vrf_list(module):
210 try:
211 body = run_commands(module, ["show vrf all | json"])[0]
212 vrf_table = body["TABLE_vrf"]["ROW_vrf"]
213 except (KeyError, AttributeError):
214 return []
215
216 vrf_list = []
217 if vrf_table:
218 for each in vrf_table:
219 vrf_list.append(str(each["vrf_name"].lower()))
220
221 return vrf_list
222
223
224 def get_auto_recovery_default(module):
225 auto = False
226 data = run_commands(module, ["show inventory | json"])[0]
227 pid = data["TABLE_inv"]["ROW_inv"][0]["productid"]
228 if re.search(r"N7K", pid):
229 auto = True
230 elif re.search(r"N9K", pid):
231 data = run_commands(module, ["show hardware | json"])[0]
232 ver = data.get("kickstart_ver_str", "")
233
234 if re.search(r"7.0\(3\)F", ver):
235 auto = True
236
237 return auto
238
239
240 def get_vpc(module):
241 body = run_commands(module, ["show vpc | json"])[0]
242 if body:
243 domain = str(body["vpc-domain-id"])
244 else:
245 body = run_commands(module, ["show run vpc | inc domain"])[0]
246 if body:
247 domain = body.split()[2]
248 else:
249 domain = "not configured"
250
251 vpc = {}
252 if domain != "not configured":
253 run = get_config(module, flags=["vpc all"])
254 if run:
255 vpc["domain"] = domain
256 for key in PARAM_TO_DEFAULT_KEYMAP.keys():
257 vpc[key] = PARAM_TO_DEFAULT_KEYMAP.get(key)
258 vpc["auto_recovery"] = get_auto_recovery_default(module)
259 vpc_list = run.split("\n")
260 for each in vpc_list:
261 if "role priority" in each:
262 line = each.split()
263 vpc["role_priority"] = line[-1]
264 if "system-priority" in each:
265 line = each.split()
266 vpc["system_priority"] = line[-1]
267 if re.search(r"delay restore \d+", each):
268 line = each.split()
269 vpc["delay_restore"] = line[-1]
270 if "delay restore interface-vlan" in each:
271 line = each.split()
272 vpc["delay_restore_interface_vlan"] = line[-1]
273 if "delay restore orphan-port" in each:
274 line = each.split()
275 vpc["delay_restore_orphan_port"] = line[-1]
276 if "auto-recovery" in each:
277 vpc["auto_recovery"] = False if "no " in each else True
278 line = each.split()
279 vpc["auto_recovery_reload_delay"] = line[-1]
280 if "peer-gateway" in each:
281 vpc["peer_gw"] = False if "no " in each else True
282 if "peer-switch" in each:
283 vpc["peer_sw"] = True
284 if "peer-keepalive destination" in each:
285 # destination is reqd; src & vrf are optional
286 m = re.search(
287 r"destination (?P<pkl_dest>[\d.]+)"
288 r"(?:.* source (?P<pkl_src>[\d.]+))*"
289 r"(?:.* vrf (?P<pkl_vrf>\S+))*",
290 each,
291 )
292 if m:
293 for pkl in m.groupdict().keys():
294 if m.group(pkl):
295 vpc[pkl] = m.group(pkl)
296 return vpc
297
298
299 def pkl_dependencies(module, delta, existing):
300 """peer-keepalive dependency checking.
301 1. 'destination' is required with all pkl configs.
302 2. If delta has optional pkl keywords present, then all optional pkl
303 keywords in existing must be added to delta, otherwise the device cli
304 will remove those values when the new config string is issued.
305 3. The desired behavior for this set of properties is to merge changes;
306 therefore if an optional pkl property exists on the device but not
307 in the playbook, then that existing property should be retained.
308 Example:
309 CLI: peer-keepalive dest 10.1.1.1 source 10.1.1.2 vrf orange
310 Playbook: {pkl_dest: 10.1.1.1, pkl_vrf: blue}
311 Result: peer-keepalive dest 10.1.1.1 source 10.1.1.2 vrf blue
312 """
313 pkl_existing = [i for i in existing.keys() if i.startswith("pkl")]
314 for pkl in pkl_existing:
315 param = module.params.get(pkl)
316 if not delta.get(pkl):
317 if param and param == existing[pkl]:
318 # delta is missing this param because it's idempotent;
319 # however another pkl command has changed; therefore
320 # explicitly add it to delta so that the cli retains it.
321 delta[pkl] = existing[pkl]
322 elif param is None and existing[pkl]:
323 # retain existing pkl commands even if not in playbook
324 delta[pkl] = existing[pkl]
325
326
327 def get_commands_to_config_vpc(module, vpc, domain, existing):
328 vpc = dict(vpc)
329
330 domain_only = vpc.get("domain")
331
332 commands = []
333 if "pkl_dest" in vpc:
334 pkl_command = "peer-keepalive destination {pkl_dest}".format(**vpc)
335 if "pkl_src" in vpc:
336 pkl_command += " source {pkl_src}".format(**vpc)
337 if "pkl_vrf" in vpc:
338 pkl_command += " vrf {pkl_vrf}".format(**vpc)
339 commands.append(pkl_command)
340
341 if "auto_recovery" in vpc:
342 if not vpc.get("auto_recovery"):
343 vpc["auto_recovery"] = "no"
344 else:
345 vpc["auto_recovery"] = ""
346
347 if "peer_gw" in vpc:
348 if not vpc.get("peer_gw"):
349 vpc["peer_gw"] = "no"
350 else:
351 vpc["peer_gw"] = ""
352
353 if "peer_sw" in vpc:
354 if not vpc.get("peer_sw"):
355 vpc["peer_sw"] = "no"
356 else:
357 vpc["peer_sw"] = ""
358 for param in vpc:
359 command = CONFIG_ARGS.get(param)
360 if command is not None:
361 command = command.format(**vpc).strip()
362 if "peer-gateway" in command:
363 commands.append("terminal dont-ask")
364 if "peer-switch" in command:
365 commands.append("terminal dont-ask")
366 commands.append(command)
367
368 if commands or domain_only:
369 commands.insert(0, "vpc domain {0}".format(domain))
370 return commands
371
372
373 def main():
374 argument_spec = dict(
375 domain=dict(required=True, type="str"),
376 role_priority=dict(required=False, type="str"),
377 system_priority=dict(required=False, type="str"),
378 pkl_src=dict(required=False),
379 pkl_dest=dict(required=False),
380 pkl_vrf=dict(required=False),
381 peer_gw=dict(required=False, type="bool"),
382 peer_sw=dict(required=False, type="bool"),
383 auto_recovery=dict(required=False, type="bool"),
384 auto_recovery_reload_delay=dict(required=False, type="str"),
385 delay_restore=dict(required=False, type="str"),
386 delay_restore_interface_vlan=dict(required=False, type="str"),
387 delay_restore_orphan_port=dict(required=False, type="str"),
388 state=dict(choices=["absent", "present"], default="present"),
389 )
390
391 mutually_exclusive = [("auto_recovery", "auto_recovery_reload_delay")]
392 module = AnsibleModule(
393 argument_spec=argument_spec,
394 mutually_exclusive=mutually_exclusive,
395 supports_check_mode=True,
396 )
397
398 warnings = list()
399 results = {"changed": False, "warnings": warnings}
400
401 domain = module.params["domain"]
402 role_priority = module.params["role_priority"]
403 system_priority = module.params["system_priority"]
404 pkl_src = module.params["pkl_src"]
405 pkl_dest = module.params["pkl_dest"]
406 pkl_vrf = module.params["pkl_vrf"]
407 peer_gw = module.params["peer_gw"]
408 peer_sw = module.params["peer_sw"]
409 auto_recovery = module.params["auto_recovery"]
410 auto_recovery_reload_delay = module.params["auto_recovery_reload_delay"]
411 delay_restore = module.params["delay_restore"]
412 delay_restore_interface_vlan = module.params["delay_restore_interface_vlan"]
413 delay_restore_orphan_port = module.params["delay_restore_orphan_port"]
414 state = module.params["state"]
415
416 args = dict(
417 domain=domain,
418 role_priority=role_priority,
419 system_priority=system_priority,
420 pkl_src=pkl_src,
421 pkl_dest=pkl_dest,
422 pkl_vrf=pkl_vrf,
423 peer_gw=peer_gw,
424 peer_sw=peer_sw,
425 auto_recovery=auto_recovery,
426 auto_recovery_reload_delay=auto_recovery_reload_delay,
427 delay_restore=delay_restore,
428 delay_restore_interface_vlan=delay_restore_interface_vlan,
429 delay_restore_orphan_port=delay_restore_orphan_port,
430 )
431
432 if not pkl_dest:
433 if pkl_src:
434 module.fail_json(msg="dest IP for peer-keepalive is required" " when src IP is present")
435 elif pkl_vrf:
436 if pkl_vrf != "management":
437 module.fail_json(
438 msg="dest and src IP for peer-keepalive are required" " when vrf is present",
439 )
440 else:
441 module.fail_json(
442 msg="dest IP for peer-keepalive is required" " when vrf is present",
443 )
444 if pkl_vrf:
445 if pkl_vrf.lower() not in get_vrf_list(module):
446 module.fail_json(
447 msg="The VRF you are trying to use for the peer "
448 "keepalive link is not on device yet. Add it"
449 " first, please.",
450 )
451 proposed = dict((k, v) for k, v in args.items() if v is not None)
452 existing = get_vpc(module)
453
454 commands = []
455 if state == "present":
456 delta = {}
457 for key, value in proposed.items():
458 if str(value).lower() == "default" and key != "pkl_vrf":
459 # 'default' is a reserved word for vrf
460 value = PARAM_TO_DEFAULT_KEYMAP.get(key)
461 if existing.get(key) != value:
462 delta[key] = value
463
464 if delta:
465 pkl_dependencies(module, delta, existing)
466 command = get_commands_to_config_vpc(module, delta, domain, existing)
467 commands.append(command)
468 elif state == "absent":
469 if existing:
470 if domain != existing["domain"]:
471 module.fail_json(
472 msg="You are trying to remove a domain that " "does not exist on the device",
473 )
474 else:
475 commands.append("terminal dont-ask")
476 commands.append("no vpc domain {0}".format(domain))
477
478 cmds = flatten_list(commands)
479 results["commands"] = cmds
480
481 if cmds:
482 results["changed"] = True
483 if not module.check_mode:
484 load_config(module, cmds)
485 if "configure" in cmds:
486 cmds.pop(0)
487
488 module.exit_json(**results)
489
490
491 if __name__ == "__main__":
492 main()