Debian Codegraph @

ansible_collections/cisco/nxos/plugins/modules/nxos_vrrp.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_vrrp
26 extends_documentation_fragment:
27 - cisco.nxos.nxos
28 short_description: Manages VRRP configuration on NX-OS switches.
29 description:
30 - Manages VRRP configuration on NX-OS switches.
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 - VRRP feature needs to be enabled first on the system.
39 - SVIs must exist before using this module.
40 - Interface must be a L3 port before using this module.
41 - C(state=absent) removes the VRRP group if it exists on the device.
42 - VRRP cannot be configured on loopback interfaces.
43 options:
44 group:
45 description:
46 - VRRP group number.
47 required: true
48 type: str
49 interface:
50 description:
51 - Full name of interface that is being managed for VRRP.
52 required: true
53 type: str
54 interval:
55 description:
56 - Time interval between advertisement or 'default' keyword
57 required: false
58 type: str
59 priority:
60 description:
61 - VRRP priority or 'default' keyword
62 type: str
63 preempt:
64 description:
65 - Enable/Disable preempt.
66 type: bool
67 vip:
68 description:
69 - VRRP virtual IP address or 'default' keyword
70 type: str
71 authentication:
72 description:
73 - Clear text authentication string or 'default' keyword
74 type: str
75 admin_state:
76 description:
77 - Used to enable or disable the VRRP process.
78 choices:
79 - shutdown
80 - no shutdown
81 - default
82 default: shutdown
83 type: str
84 state:
85 description:
86 - Specify desired state of the resource.
87 default: present
88 choices:
89 - present
90 - absent
91 type: str
92 """
93
94 EXAMPLES = """
95 - name: Ensure vrrp group 100 and vip 10.1.100.1 is on vlan10
96 cisco.nxos.nxos_vrrp:
97 interface: vlan10
98 group: 100
99 vip: 10.1.100.1
100
101 - name: Ensure removal of the vrrp group config
102 cisco.nxos.nxos_vrrp:
103 interface: vlan10
104 group: 100
105 vip: 10.1.100.1
106 state: absent
107
108 - name: Re-config with more params
109 cisco.nxos.nxos_vrrp:
110 interface: vlan10
111 group: 100
112 vip: 10.1.100.1
113 preempt: false
114 priority: 130
115 authentication: AUTHKEY
116 """
117
118 RETURN = """
119 commands:
120 description: commands sent to the device
121 returned: always
122 type: list
123 sample: ["interface vlan10", "vrrp 150", "address 10.1.15.1",
124 "authentication text testing", "no shutdown"]
125 """
126
127 from ansible.module_utils.basic import AnsibleModule
128
129 from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.nxos import (
130 get_capabilities,
131 get_interface_type,
132 load_config,
133 run_commands,
134 )
135
136
137 PARAM_TO_DEFAULT_KEYMAP = {
138 "priority": "100",
139 "interval": "1",
140 "vip": "0.0.0.0",
141 "admin_state": "shutdown",
142 }
143
144
145 def execute_show_command(command, module):
146 if "show run" not in command:
147 output = "json"
148 else:
149 output = "text"
150
151 commands = [{"command": command, "output": output}]
152 return run_commands(module, commands)[0]
153
154
155 def apply_key_map(key_map, table):
156 new_dict = {}
157 for key, value in table.items():
158 new_key = key_map.get(key)
159 if new_key:
160 if value:
161 new_dict[new_key] = str(value)
162 else:
163 new_dict[new_key] = value
164 return new_dict
165
166
167 def is_default(interface, module):
168 command = "show run interface {0}".format(interface)
169
170 try:
171 body = execute_show_command(command, module)
172 if "invalid" in body.lower():
173 return "DNE"
174 else:
175 raw_list = body.split("\n")
176 if raw_list[-1].startswith("interface"):
177 return True
178 else:
179 return False
180 except KeyError:
181 return "DNE"
182
183
184 def get_interface_mode(interface, intf_type, module):
185 command = "show interface {0}".format(interface)
186 interface = {}
187 mode = "unknown"
188 body = execute_show_command(command, module)
189 interface_table = body["TABLE_interface"]["ROW_interface"]
190 name = interface_table.get("interface")
191
192 if intf_type in ["ethernet", "portchannel"]:
193 mode = str(interface_table.get("eth_mode", "layer3"))
194
195 if mode == "access" or mode == "trunk":
196 mode = "layer2"
197 elif intf_type == "svi":
198 mode = "layer3"
199
200 return mode, name
201
202
203 def get_vrr_status(group, module, interface):
204 command = "show run all | section interface.{0}$".format(interface)
205 body = execute_show_command(command, module)
206 vrf_index = None
207 admin_state = "shutdown"
208
209 if body:
210 splitted_body = body.splitlines()
211 for index in range(0, len(splitted_body) - 1):
212 if splitted_body[index].strip() == "vrrp {0}".format(group):
213 vrf_index = index
214 vrf_section = splitted_body[vrf_index::]
215
216 for line in vrf_section:
217 if line.strip() == "no shutdown":
218 admin_state = "no shutdown"
219 break
220
221 return admin_state
222
223
224 def get_existing_vrrp(interface, group, module, name):
225 command = "show vrrp detail interface {0}".format(interface)
226 body = execute_show_command(command, module)
227 vrrp = {}
228
229 vrrp_key = {
230 "sh_group_id": "group",
231 "sh_vip_addr": "vip",
232 "sh_priority": "priority",
233 "sh_group_preempt": "preempt",
234 "sh_auth_text": "authentication",
235 "sh_adv_interval": "interval",
236 }
237
238 try:
239 vrrp_table = body["TABLE_vrrp_group"]
240 except (AttributeError, IndexError, TypeError):
241 return {}
242
243 if isinstance(vrrp_table, dict):
244 vrrp_table = [vrrp_table]
245
246 for each_vrrp in vrrp_table:
247 vrrp_row = each_vrrp["ROW_vrrp_group"]
248 parsed_vrrp = apply_key_map(vrrp_key, vrrp_row)
249
250 if parsed_vrrp["preempt"] == "Disable":
251 parsed_vrrp["preempt"] = False
252 elif parsed_vrrp["preempt"] == "Enable":
253 parsed_vrrp["preempt"] = True
254
255 if parsed_vrrp["group"] == group:
256 parsed_vrrp["admin_state"] = get_vrr_status(group, module, name)
257 return parsed_vrrp
258
259 return vrrp
260
261
262 def get_commands_config_vrrp(delta, existing, group):
263 commands = []
264
265 CMDS = {
266 "priority": "priority {0}",
267 "preempt": "preempt",
268 "vip": "address {0}",
269 "interval": "advertisement-interval {0}",
270 "auth": "authentication text {0}",
271 "admin_state": "{0}",
272 }
273
274 for arg in ["vip", "priority", "interval", "admin_state"]:
275 val = delta.get(arg)
276 if val == "default":
277 val = PARAM_TO_DEFAULT_KEYMAP.get(arg)
278 if val != existing.get(arg):
279 commands.append((CMDS.get(arg)).format(val))
280 elif val:
281 commands.append((CMDS.get(arg)).format(val))
282
283 preempt = delta.get("preempt")
284 auth = delta.get("authentication")
285
286 if preempt:
287 commands.append(CMDS.get("preempt"))
288 elif preempt is False:
289 commands.append("no " + CMDS.get("preempt"))
290 if auth:
291 if auth != "default":
292 commands.append((CMDS.get("auth")).format(auth))
293 elif existing.get("authentication"):
294 commands.append("no authentication")
295
296 if commands:
297 commands.insert(0, "vrrp {0}".format(group))
298
299 return commands
300
301
302 def flatten_list(command_lists):
303 flat_command_list = []
304 for command in command_lists:
305 if isinstance(command, list):
306 flat_command_list.extend(command)
307 else:
308 flat_command_list.append(command)
309 return flat_command_list
310
311
312 def validate_params(param, module):
313 value = module.params[param]
314
315 if param == "group":
316 try:
317 if int(value) < 1 or int(value) > 255:
318 raise ValueError
319 except ValueError:
320 module.fail_json(
321 msg="Warning! 'group' must be an integer between" " 1 and 255",
322 group=value,
323 )
324 elif param == "priority":
325 try:
326 if int(value) < 1 or int(value) > 254:
327 raise ValueError
328 except ValueError:
329 module.fail_json(
330 msg="Warning! 'priority' must be an integer " "between 1 and 254",
331 priority=value,
332 )
333
334
335 def main():
336 argument_spec = dict(
337 group=dict(required=True, type="str"),
338 interface=dict(required=True),
339 interval=dict(required=False, type="str"),
340 priority=dict(required=False, type="str"),
341 preempt=dict(required=False, type="bool"),
342 vip=dict(required=False, type="str"),
343 admin_state=dict(
344 required=False,
345 type="str",
346 choices=["shutdown", "no shutdown", "default"],
347 default="shutdown",
348 ),
349 authentication=dict(required=False, type="str", no_log=True),
350 state=dict(choices=["absent", "present"], required=False, default="present"),
351 )
352 module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
353
354 warnings = list()
355 results = {"changed": False, "commands": [], "warnings": warnings}
356
357 state = module.params["state"]
358 interface = module.params["interface"].lower()
359 group = module.params["group"]
360 priority = module.params["priority"]
361 interval = module.params["interval"]
362 preempt = module.params["preempt"]
363 vip = module.params["vip"]
364 authentication = module.params["authentication"]
365 admin_state = module.params["admin_state"]
366
367 device_info = get_capabilities(module)
368 network_api = device_info.get("network_api", "nxapi")
369
370 if state == "present" and not vip:
371 module.fail_json(msg='the "vip" param is required when state=present')
372
373 intf_type = get_interface_type(interface)
374 if intf_type != "ethernet" and network_api == "cliconf":
375 if is_default(interface, module) == "DNE":
376 module.fail_json(
377 msg="That interface does not exist yet. Create " "it first.",
378 interface=interface,
379 )
380 if intf_type == "loopback":
381 module.fail_json(
382 msg="Loopback interfaces don't support VRRP.",
383 interface=interface,
384 )
385
386 mode, name = get_interface_mode(interface, intf_type, module)
387 if mode == "layer2":
388 module.fail_json(
389 msg="That interface is a layer2 port.\nMake it " "a layer 3 port first.",
390 interface=interface,
391 )
392
393 args = dict(
394 group=group,
395 priority=priority,
396 preempt=preempt,
397 vip=vip,
398 authentication=authentication,
399 interval=interval,
400 admin_state=admin_state,
401 )
402
403 proposed = dict((k, v) for k, v in args.items() if v is not None)
404 existing = get_existing_vrrp(interface, group, module, name)
405
406 commands = []
407
408 if state == "present":
409 delta = dict(set(proposed.items()).difference(existing.items()))
410 if delta:
411 command = get_commands_config_vrrp(delta, existing, group)
412 if command:
413 commands.append(command)
414 elif state == "absent":
415 if existing:
416 commands.append(["no vrrp {0}".format(group)])
417
418 if commands:
419 commands.insert(0, ["interface {0}".format(interface)])
420 commands = flatten_list(commands)
421 results["commands"] = commands
422 results["changed"] = True
423 if not module.check_mode:
424 load_config(module, commands)
425 if "configure" in commands:
426 commands.pop(0)
427
428 module.exit_json(**results)
429
430
431 if __name__ == "__main__":
432 main()