Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 from __future__ import absolute_import, division, print_function
4
5
6 __metaclass__ = type
7
8 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
9
10
11 DOCUMENTATION = """
12 module: nxos_pim_interface
13 extends_documentation_fragment:
14 - cisco.nxos.nxos
15 short_description: Manages PIM interface configuration.
16 description:
17 - Manages PIM interface configuration settings.
18 version_added: 1.0.0
19 author:
20 - Jason Edelman (@jedelman8)
21 notes:
22 - Tested against NXOSv 7.3.(0)D1(1) on VIRL
23 - Unsupported for Cisco MDS
24 - When C(state=default), supported params will be reset to a default state. These
25 include C(dr_prio), C(hello_auth_key), C(hello_interval), C(jp_policy_out), C(jp_policy_in),
26 C(jp_type_in), C(jp_type_out), C(border), C(neighbor_policy), C(neighbor_type).
27 - The C(hello_auth_key) param is not idempotent.
28 - C(hello_auth_key) only supports clear text passwords.
29 - When C(state=absent), pim interface configuration will be set to defaults and pim-sm
30 will be disabled on the interface.
31 - PIM must be enabled on the device to use this module.
32 - This module is for Layer 3 interfaces.
33 options:
34 interface:
35 description:
36 - Full name of the interface such as Ethernet1/33.
37 type: str
38 required: true
39 sparse:
40 description:
41 - Enable/disable sparse-mode on the interface.
42 type: bool
43 default: false
44 bfd:
45 description:
46 - Enables BFD for PIM at the interface level. This overrides the bfd variable
47 set at the pim global level.
48 - Valid values are 'enable', 'disable' or 'default'.
49 - "Dependency: ''feature bfd''"
50 type: str
51 choices:
52 - enable
53 - disable
54 - default
55 dr_prio:
56 description:
57 - Configures priority for PIM DR election on interface.
58 type: str
59 hello_auth_key:
60 description:
61 - Authentication for hellos on this interface.
62 type: str
63 hello_interval:
64 description:
65 - Hello interval in milliseconds or seconds for this interface.
66 - Use the option I(hello_interval_ms) to specify if the given value is in
67 milliseconds or seconds. The default is seconds.
68 type: int
69 hello_interval_ms:
70 description:
71 - Specifies that the hello_interval is in milliseconds.
72 - When set to True, this indicates that the user is providing the
73 hello_interval in milliseconds and hence, no conversion is required.
74 type: bool
75 version_added: 2.0.0
76 jp_policy_out:
77 description:
78 - Policy for join-prune messages (outbound).
79 type: str
80 jp_policy_in:
81 description:
82 - Policy for join-prune messages (inbound).
83 type: str
84 jp_type_out:
85 description:
86 - Type of policy mapped to C(jp_policy_out).
87 type: str
88 choices:
89 - prefix
90 - routemap
91 jp_type_in:
92 description:
93 - Type of policy mapped to C(jp_policy_in).
94 type: str
95 choices:
96 - prefix
97 - routemap
98 border:
99 description:
100 - Configures interface to be a boundary of a PIM domain.
101 type: bool
102 default: false
103 neighbor_policy:
104 description:
105 - Configures a neighbor policy for filtering adjacencies.
106 type: str
107 neighbor_type:
108 description:
109 - Type of policy mapped to neighbor_policy.
110 type: str
111 choices:
112 - prefix
113 - routemap
114 state:
115 description:
116 - Manages desired state of the resource.
117 type: str
118 choices:
119 - present
120 - absent
121 - default
122 default: present
123 """
124 EXAMPLES = """
125 - name: Ensure PIM is not running on the interface
126 cisco.nxos.nxos_pim_interface:
127 interface: eth1/33
128 state: absent
129
130 - name: Ensure the interface has pim-sm enabled with the appropriate priority and
131 hello interval
132 cisco.nxos.nxos_pim_interface:
133 interface: eth1/33
134 dr_prio: 10
135 hello_interval: 40
136 state: present
137
138 - name: Ensure join-prune policies exist
139 cisco.nxos.nxos_pim_interface:
140 interface: eth1/33
141 jp_policy_in: JPIN
142 jp_policy_out: JPOUT
143 jp_type_in: routemap
144 jp_type_out: routemap
145
146 - name: disable bfd on the interface
147 cisco.nxos.nxos_pim_interface:
148 interface: eth1/33
149 bfd: disable
150
151 - name: Ensure defaults are in place
152 cisco.nxos.nxos_pim_interface:
153 interface: eth1/33
154 state: default
155 """
156
157 RETURN = r"""
158 commands:
159 description: command sent to the device
160 returned: always
161 type: list
162 sample: ["interface eth1/33",
163 "ip pim neighbor-policy test",
164 "ip pim bfd-instance disable",
165 "ip pim neighbor-policy test"
166 ]
167 """
168
169 import re
170
171 from ansible.module_utils.basic import AnsibleModule
172
173 from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.nxos import (
174 get_config,
175 get_interface_type,
176 load_config,
177 run_commands,
178 )
179
180
181 PARAM_TO_COMMAND_KEYMAP = {
182 "interface": "",
183 "bfd": "ip pim bfd-instance",
184 "sparse": "ip pim sparse-mode",
185 "dr_prio": "ip pim dr-priority {0}",
186 "hello_interval": "ip pim hello-interval {0}",
187 "hello_auth_key": "ip pim hello-authentication ah-md5 {0}",
188 "border": "ip pim border",
189 "jp_policy_out": "ip pim jp-policy prefix-list {0} out",
190 "jp_policy_in": "ip pim jp-policy prefix-list {0} in",
191 "jp_type_in": "",
192 "jp_type_out": "",
193 "neighbor_policy": "ip pim neighbor-policy prefix-list {0}",
194 "neighbor_type": "",
195 }
196
197 PARAM_TO_DEFAULT_KEYMAP = {
198 "bfd": "default",
199 "dr_prio": "1",
200 "hello_interval": "30000",
201 "sparse": False,
202 "border": False,
203 "hello_auth_key": False,
204 }
205
206 BFD_KEYMAP = {
207 None: None,
208 "default": "no ip pim bfd-instance",
209 "disable": "ip pim bfd-instance disable",
210 "enable": "ip pim bfd-instance",
211 }
212
213
214 def execute_show_command(command, module, text=False):
215 if text:
216 cmds = [{"command": command, "output": "text"}]
217 else:
218 cmds = [{"command": command, "output": "json"}]
219
220 return run_commands(module, cmds)
221
222
223 def flatten_list(command_lists):
224 flat_command_list = []
225 for command in command_lists:
226 if isinstance(command, list):
227 flat_command_list.extend(command)
228 else:
229 flat_command_list.append(command)
230 return flat_command_list
231
232
233 def local_existing(gexisting):
234 jp_bidir = False
235 isauth = False
236 if gexisting:
237 jp_bidir = gexisting.get("jp_bidir")
238 isauth = gexisting.get("isauth")
239 if jp_bidir and isauth:
240 gexisting.pop("jp_bidir")
241 gexisting.pop("isauth")
242
243 return gexisting, jp_bidir, isauth
244
245
246 def get_interface_mode(interface, intf_type, module):
247 mode = "unknown"
248 command = "show interface {0}".format(interface)
249 body = execute_show_command(command, module)
250
251 try:
252 interface_table = body[0]["TABLE_interface"]["ROW_interface"]
253 except (KeyError, AttributeError, IndexError):
254 return mode
255
256 if intf_type in ["ethernet", "portchannel"]:
257 mode = str(interface_table.get("eth_mode", "layer3"))
258 if mode in ["access", "trunk"]:
259 mode = "layer2"
260 elif mode == "routed":
261 mode = "layer3"
262 elif intf_type in ["loopback", "svi"]:
263 mode = "layer3"
264 return mode
265
266
267 def get_pim_interface(module, interface):
268 pim_interface = {}
269 body = get_config(module, flags=["interface {0}".format(interface)])
270
271 pim_interface["bfd"] = "default"
272 pim_interface["neighbor_type"] = None
273 pim_interface["neighbor_policy"] = None
274 pim_interface["jp_policy_in"] = None
275 pim_interface["jp_policy_out"] = None
276 pim_interface["jp_type_in"] = None
277 pim_interface["jp_type_out"] = None
278 pim_interface["jp_bidir"] = False
279 pim_interface["isauth"] = False
280
281 if body:
282 all_lines = body.splitlines()
283
284 for each in all_lines:
285 if "jp-policy" in each:
286 policy_name = re.search(
287 r"ip pim jp-policy(?: prefix-list)? (\S+)(?: \S+)?",
288 each,
289 ).group(1)
290 if "prefix-list" in each:
291 ptype = "prefix"
292 else:
293 ptype = "routemap"
294 if "out" in each:
295 pim_interface["jp_policy_out"] = policy_name
296 pim_interface["jp_type_out"] = ptype
297 elif "in" in each:
298 pim_interface["jp_policy_in"] = policy_name
299 pim_interface["jp_type_in"] = ptype
300 else:
301 pim_interface["jp_policy_in"] = policy_name
302 pim_interface["jp_policy_out"] = policy_name
303 pim_interface["jp_bidir"] = True
304 elif "neighbor-policy" in each:
305 pim_interface["neighbor_policy"] = re.search(
306 r"ip pim neighbor-policy(?: prefix-list)? (\S+)",
307 each,
308 ).group(1)
309 if "prefix-list" in each:
310 pim_interface["neighbor_type"] = "prefix"
311 else:
312 pim_interface["neighbor_type"] = "routemap"
313 elif "ah-md5" in each:
314 pim_interface["isauth"] = True
315 elif "sparse-mode" in each:
316 pim_interface["sparse"] = True
317 elif "bfd-instance" in each:
318 m = re.search(r"ip pim bfd-instance(?P<disable> disable)?", each)
319 if m:
320 pim_interface["bfd"] = "disable" if m.group("disable") else "enable"
321 elif "border" in each:
322 pim_interface["border"] = True
323 elif "hello-interval" in each:
324 pim_interface["hello_interval"] = re.search(
325 r"ip pim hello-interval (\d+)",
326 body,
327 ).group(1)
328 elif "dr-priority" in each:
329 pim_interface["dr_prio"] = re.search(r"ip pim dr-priority (\d+)", body).group(1)
330
331 return pim_interface
332
333
334 def fix_delta(delta, existing):
335 for key in list(delta):
336 if key in ["dr_prio", "hello_interval", "sparse", "border"]:
337 if delta.get(key) == PARAM_TO_DEFAULT_KEYMAP.get(key) and existing.get(key) is None:
338 delta.pop(key)
339 return delta
340
341
342 def config_pim_interface(delta, existing, jp_bidir, isauth):
343 command = None
344 commands = []
345
346 delta = fix_delta(delta, existing)
347
348 if jp_bidir:
349 if delta.get("jp_policy_in") or delta.get("jp_policy_out"):
350 if existing.get("jp_type_in") == "prefix":
351 command = "no ip pim jp-policy prefix-list {0}".format(existing.get("jp_policy_in"))
352 else:
353 command = "no ip pim jp-policy {0}".format(existing.get("jp_policy_in"))
354 if command:
355 commands.append(command)
356
357 for k, v in delta.items():
358 if k in [
359 "bfd",
360 "dr_prio",
361 "hello_interval",
362 "hello_auth_key",
363 "border",
364 "sparse",
365 ]:
366 if k == "bfd":
367 command = BFD_KEYMAP[v]
368 elif v:
369 command = PARAM_TO_COMMAND_KEYMAP.get(k).format(v)
370 elif k == "hello_auth_key":
371 if isauth:
372 command = "no ip pim hello-authentication ah-md5"
373 else:
374 command = "no " + PARAM_TO_COMMAND_KEYMAP.get(k).format(v)
375
376 if command:
377 commands.append(command)
378 elif k in [
379 "neighbor_policy",
380 "jp_policy_in",
381 "jp_policy_out",
382 "neighbor_type",
383 ]:
384 if k in ["neighbor_policy", "neighbor_type"]:
385 temp = delta.get("neighbor_policy") or existing.get("neighbor_policy")
386 if delta.get("neighbor_type") == "prefix":
387 command = PARAM_TO_COMMAND_KEYMAP.get(k).format(temp)
388 elif delta.get("neighbor_type") == "routemap":
389 command = "ip pim neighbor-policy {0}".format(temp)
390 elif existing.get("neighbor_type") == "prefix":
391 command = PARAM_TO_COMMAND_KEYMAP.get(k).format(temp)
392 elif existing.get("neighbor_type") == "routemap":
393 command = "ip pim neighbor-policy {0}".format(temp)
394 elif k in ["jp_policy_in", "jp_type_in"]:
395 temp = delta.get("jp_policy_in") or existing.get("jp_policy_in")
396 if delta.get("jp_type_in") == "prefix":
397 command = PARAM_TO_COMMAND_KEYMAP.get(k).format(temp)
398 elif delta.get("jp_type_in") == "routemap":
399 command = "ip pim jp-policy {0} in".format(temp)
400 elif existing.get("jp_type_in") == "prefix":
401 command = PARAM_TO_COMMAND_KEYMAP.get(k).format(temp)
402 elif existing.get("jp_type_in") == "routemap":
403 command = "ip pim jp-policy {0} in".format(temp)
404 elif k in ["jp_policy_out", "jp_type_out"]:
405 temp = delta.get("jp_policy_out") or existing.get("jp_policy_out")
406 if delta.get("jp_type_out") == "prefix":
407 command = PARAM_TO_COMMAND_KEYMAP.get(k).format(temp)
408 elif delta.get("jp_type_out") == "routemap":
409 command = "ip pim jp-policy {0} out".format(temp)
410 elif existing.get("jp_type_out") == "prefix":
411 command = PARAM_TO_COMMAND_KEYMAP.get(k).format(temp)
412 elif existing.get("jp_type_out") == "routemap":
413 command = "ip pim jp-policy {0} out".format(temp)
414 if command:
415 commands.append(command)
416 command = None
417
418 if "no ip pim sparse-mode" in commands:
419 # sparse is long-running on some platforms, process it last
420 commands.remove("no ip pim sparse-mode")
421 commands.append("no ip pim sparse-mode")
422 return commands
423
424
425 def get_pim_interface_defaults():
426 args = dict(
427 dr_prio=PARAM_TO_DEFAULT_KEYMAP.get("dr_prio"),
428 bfd=PARAM_TO_DEFAULT_KEYMAP.get("bfd"),
429 border=PARAM_TO_DEFAULT_KEYMAP.get("border"),
430 sparse=PARAM_TO_DEFAULT_KEYMAP.get("sparse"),
431 hello_interval=PARAM_TO_DEFAULT_KEYMAP.get("hello_interval"),
432 hello_auth_key=PARAM_TO_DEFAULT_KEYMAP.get("hello_auth_key"),
433 )
434
435 default = dict((param, value) for (param, value) in args.items() if value is not None)
436
437 return default
438
439
440 def default_pim_interface_policies(existing, jp_bidir):
441 commands = []
442
443 if jp_bidir:
444 if existing.get("jp_policy_in") or existing.get("jp_policy_out"):
445 if existing.get("jp_type_in") == "prefix":
446 command = "no ip pim jp-policy prefix-list {0}".format(existing.get("jp_policy_in"))
447 if command:
448 commands.append(command)
449
450 elif not jp_bidir:
451 command = None
452 for k in existing:
453 if k == "jp_policy_in":
454 if existing.get("jp_policy_in"):
455 if existing.get("jp_type_in") == "prefix":
456 command = "no ip pim jp-policy prefix-list {0} in".format(
457 existing.get("jp_policy_in"),
458 )
459 else:
460 command = "no ip pim jp-policy {0} in".format(existing.get("jp_policy_in"))
461 elif k == "jp_policy_out":
462 if existing.get("jp_policy_out"):
463 if existing.get("jp_type_out") == "prefix":
464 command = "no ip pim jp-policy prefix-list {0} out".format(
465 existing.get("jp_policy_out"),
466 )
467 else:
468 command = "no ip pim jp-policy {0} out".format(
469 existing.get("jp_policy_out"),
470 )
471 if command:
472 commands.append(command)
473 command = None
474
475 if existing.get("neighbor_policy"):
476 command = "no ip pim neighbor-policy"
477 commands.append(command)
478
479 return commands
480
481
482 def config_pim_interface_defaults(existing, jp_bidir, isauth):
483 command = []
484
485 # returns a dict
486 defaults = get_pim_interface_defaults()
487 delta = dict(set(defaults.items()).difference(existing.items()))
488 if delta:
489 # returns a list
490 command = config_pim_interface(delta, existing, jp_bidir, isauth)
491 comm = default_pim_interface_policies(existing, jp_bidir)
492 if comm:
493 for each in comm:
494 command.append(each)
495
496 return command
497
498
499 def normalize_proposed_values(proposed, module):
500 keys = proposed.keys()
501 if "bfd" in keys:
502 # bfd is a tri-state string: enable, disable, default
503 proposed["bfd"] = proposed["bfd"].lower()
504 if "hello_interval" in keys:
505 hello_interval = proposed["hello_interval"]
506 if not module.params["hello_interval_ms"]:
507 hello_interval = hello_interval * 1000
508 proposed["hello_interval"] = str(hello_interval)
509
510
511 def main():
512 argument_spec = dict(
513 interface=dict(type="str", required=True),
514 sparse=dict(type="bool", default=False),
515 dr_prio=dict(type="str"),
516 hello_auth_key=dict(type="str", no_log=True),
517 hello_interval=dict(type="int"),
518 hello_interval_ms=dict(type="bool"),
519 jp_policy_out=dict(type="str"),
520 jp_policy_in=dict(type="str"),
521 jp_type_out=dict(type="str", choices=["prefix", "routemap"]),
522 jp_type_in=dict(type="str", choices=["prefix", "routemap"]),
523 bfd=dict(type="str", choices=["enable", "disable", "default"]),
524 border=dict(type="bool", default=False),
525 neighbor_policy=dict(type="str"),
526 neighbor_type=dict(type="str", choices=["prefix", "routemap"]),
527 state=dict(
528 type="str",
529 default="present",
530 choices=["absent", "default", "present"],
531 ),
532 )
533
534 required_by = {"hello_interval_ms": "hello_interval"}
535 module = AnsibleModule(
536 argument_spec=argument_spec,
537 supports_check_mode=True,
538 required_by=required_by,
539 )
540
541 warnings = list()
542 results = {"changed": False, "commands": [], "warnings": warnings}
543
544 state = module.params["state"]
545 interface = module.params["interface"]
546 jp_type_in = module.params["jp_type_in"]
547 jp_type_out = module.params["jp_type_out"]
548 jp_policy_in = module.params["jp_policy_in"]
549 jp_policy_out = module.params["jp_policy_out"]
550 neighbor_policy = module.params["neighbor_policy"]
551 neighbor_type = module.params["neighbor_type"]
552
553 intf_type = get_interface_type(interface)
554 if get_interface_mode(interface, intf_type, module) == "layer2":
555 module.fail_json(msg="this module only works on Layer 3 interfaces.")
556
557 if jp_policy_in:
558 if not jp_type_in:
559 module.fail_json(msg="jp_type_in required when using jp_policy_in.")
560 if jp_policy_out:
561 if not jp_type_out:
562 module.fail_json(msg="jp_type_out required when using jp_policy_out.")
563 if neighbor_policy:
564 if not neighbor_type:
565 module.fail_json(msg="neighbor_type required when using neighbor_policy.")
566
567 get_existing = get_pim_interface(module, interface)
568 existing, jp_bidir, isauth = local_existing(get_existing)
569
570 args = PARAM_TO_COMMAND_KEYMAP.keys()
571 proposed = dict((k, v) for k, v in module.params.items() if v is not None and k in args)
572 normalize_proposed_values(proposed, module)
573
574 delta = dict(set(proposed.items()).difference(existing.items()))
575
576 commands = []
577 if state == "present":
578 if delta:
579 command = config_pim_interface(delta, existing, jp_bidir, isauth)
580 if command:
581 commands.append(command)
582 elif state == "default" or state == "absent":
583 defaults = config_pim_interface_defaults(existing, jp_bidir, isauth)
584 if defaults:
585 commands.append(defaults)
586
587 if commands:
588 commands.insert(0, ["interface {0}".format(interface)])
589
590 cmds = flatten_list(commands)
591 if cmds:
592 results["changed"] = True
593 if not module.check_mode:
594 load_config(module, cmds)
595 if "configure" in cmds:
596 cmds.pop(0)
597
598 results["commands"] = cmds
599
600 module.exit_json(**results)
601
602
603 if __name__ == "__main__":
604 main()