Debian Codegraph @

ansible_collections/cisco/nxos/plugins/modules/nxos_vxlan_vtep_vni.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_vxlan_vtep_vni
26 extends_documentation_fragment:
27 - cisco.nxos.nxos
28 short_description: Creates a Virtual Network Identifier member (VNI)
29 description:
30 - Creates a Virtual Network Identifier member (VNI) for an NVE overlay interface.
31 version_added: 1.0.0
32 author: Gabriele Gerbino (@GGabriele)
33 notes:
34 - Tested against NXOSv 7.3.(0)D1(1) on VIRL
35 - Unsupported for Cisco MDS
36 - default, where supported, restores params default value.
37 options:
38 interface:
39 description:
40 - Interface name for the VXLAN Network Virtualization Endpoint.
41 required: true
42 type: str
43 vni:
44 description:
45 - ID of the Virtual Network Identifier.
46 required: true
47 type: str
48 assoc_vrf:
49 description:
50 - This attribute is used to identify and separate processing VNIs that are associated
51 with a VRF and used for routing. The VRF and VNI specified with this command
52 must match the configuration of the VNI under the VRF.
53 type: bool
54 ingress_replication:
55 description:
56 - Specifies mechanism for host reachability advertisement.
57 choices:
58 - bgp
59 - static
60 - default
61 type: str
62 multicast_group:
63 description:
64 - The multicast group (range) of the VNI. Valid values are string and keyword
65 'default'.
66 type: str
67 peer_list:
68 description:
69 - Set the ingress-replication static peer list. Valid values are an array, a space-separated
70 string of ip addresses, or the keyword 'default'.
71 type: list
72 elements: str
73 suppress_arp:
74 description:
75 - Suppress arp under layer 2 VNI.
76 type: bool
77 suppress_arp_disable:
78 description:
79 - Overrides the global ARP suppression config. This is available on NX-OS 9K series
80 running 9.2.x or higher.
81 type: bool
82 state:
83 description:
84 - Determines whether the config should be present or not on the device.
85 default: present
86 choices:
87 - present
88 - absent
89 type: str
90 multisite_ingress_replication:
91 description:
92 - Enables multisite ingress replication.
93 choices:
94 - disable
95 - enable
96 - optimized
97 type: str
98 version_added: 1.1.0
99 """
100 EXAMPLES = """
101 - cisco.nxos.nxos_vxlan_vtep_vni:
102 interface: nve1
103 vni: 6000
104 ingress_replication: default
105 multisite_ingress_replication: enable
106 """
107
108 RETURN = """
109 commands:
110 description: commands sent to the device
111 returned: always
112 type: list
113 sample: ["interface nve1", "member vni 6000", "multisite ingress-replication"]
114 """
115
116 import re
117
118 from ansible.module_utils.basic import AnsibleModule
119 from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.config import (
120 CustomNetworkConfig,
121 )
122
123 from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.nxos import (
124 get_config,
125 load_config,
126 )
127
128
129 BOOL_PARAMS = ["assoc_vrf", "suppress_arp", "suppress_arp_disable"]
130 PARAM_TO_DEFAULT_KEYMAP = {
131 "multicast_group": "",
132 "peer_list": [],
133 "ingress_replication": "",
134 }
135 PARAM_TO_COMMAND_KEYMAP = {
136 "assoc_vrf": "associate-vrf",
137 "interface": "interface",
138 "vni": "member vni",
139 "ingress_replication": "ingress-replication protocol",
140 "multicast_group": "mcast-group",
141 "peer_list": "peer-ip",
142 "suppress_arp": "suppress-arp",
143 "suppress_arp_disable": "suppress-arp disable",
144 "multisite_ingress_replication": "multisite ingress-replication",
145 }
146
147
148 def get_value(arg, config, module):
149 command = PARAM_TO_COMMAND_KEYMAP[arg]
150 command_val_re = re.compile(r"(?:{0}\s)(?P<value>.*)$".format(command), re.M)
151
152 if arg in BOOL_PARAMS:
153 command_re = re.compile(r"\s+{0}\s*$".format(command), re.M)
154 value = False
155 if command_re.search(config):
156 value = True
157 elif arg == "peer_list":
158 has_command_val = command_val_re.findall(config, re.M)
159 value = []
160 if has_command_val:
161 value = has_command_val
162 elif arg == "multisite_ingress_replication":
163 has_command = re.search(r"^\s+{0}$".format(command), config, re.M)
164 has_command_val = command_val_re.search(config, re.M)
165 value = "disable"
166 if has_command:
167 value = "enable"
168 elif has_command_val:
169 value = "optimized"
170 else:
171 value = ""
172 has_command_val = command_val_re.search(config, re.M)
173 if has_command_val:
174 value = has_command_val.group("value")
175 return value
176
177
178 def check_interface(module, netcfg):
179 config = str(netcfg)
180
181 has_interface = re.search(r"(?:interface nve)(?P<value>.*)$", config, re.M)
182 value = ""
183 if has_interface:
184 value = "nve{0}".format(has_interface.group("value"))
185
186 return value
187
188
189 def get_existing(module, args):
190 existing = {}
191 netcfg = CustomNetworkConfig(indent=2, contents=get_config(module))
192
193 interface_exist = check_interface(module, netcfg)
194 if interface_exist:
195 parents = ["interface {0}".format(interface_exist)]
196 temp_config = netcfg.get_section(parents)
197
198 if "member vni {0} associate-vrf".format(module.params["vni"]) in temp_config:
199 parents.append("member vni {0} associate-vrf".format(module.params["vni"]))
200 config = netcfg.get_section(parents)
201 elif "member vni {0}".format(module.params["vni"]) in temp_config:
202 parents.append("member vni {0}".format(module.params["vni"]))
203 config = netcfg.get_section(parents)
204 else:
205 config = {}
206
207 if config:
208 for arg in args:
209 if arg not in ["interface", "vni"]:
210 existing[arg] = get_value(arg, config, module)
211 existing["interface"] = interface_exist
212 existing["vni"] = module.params["vni"]
213
214 return existing, interface_exist
215
216
217 def apply_key_map(key_map, table):
218 new_dict = {}
219 for key, value in table.items():
220 new_key = key_map.get(key)
221 if new_key:
222 new_dict[new_key] = value
223 return new_dict
224
225
226 def state_present(module, existing, proposed, candidate):
227 commands = list()
228 proposed_commands = apply_key_map(PARAM_TO_COMMAND_KEYMAP, proposed)
229 existing_commands = apply_key_map(PARAM_TO_COMMAND_KEYMAP, existing)
230
231 for key, value in proposed_commands.items():
232 if key == "associate-vrf":
233 command = "member vni {0} {1}".format(module.params["vni"], key)
234 if not value:
235 command = "no {0}".format(command)
236 commands.append(command)
237
238 elif key == "peer-ip" and value != []:
239 for peer in value:
240 commands.append("{0} {1}".format(key, peer))
241
242 elif key == "mcast-group" and value != existing_commands.get(key):
243 commands.append("no {0}".format(key))
244 vni_command = "member vni {0}".format(module.params["vni"])
245 if vni_command not in commands:
246 commands.append("member vni {0}".format(module.params["vni"]))
247 if value != PARAM_TO_DEFAULT_KEYMAP.get("multicast_group", "default"):
248 commands.append("{0} {1}".format(key, value))
249
250 elif key == "ingress-replication protocol" and value != existing_commands.get(key):
251 evalue = existing_commands.get(key)
252 dvalue = PARAM_TO_DEFAULT_KEYMAP.get("ingress_replication", "default")
253 if value != dvalue:
254 if evalue and evalue != dvalue:
255 commands.append("no {0} {1}".format(key, evalue))
256 commands.append("{0} {1}".format(key, value))
257 else:
258 if evalue:
259 commands.append("no {0} {1}".format(key, evalue))
260
261 elif value is True:
262 commands.append(key)
263 elif value is False:
264 commands.append("no {0}".format(key))
265 elif value == "default" or value == []:
266 if existing_commands.get(key):
267 existing_value = existing_commands.get(key)
268 if key == "peer-ip":
269 for peer in existing_value:
270 commands.append("no {0} {1}".format(key, peer))
271 else:
272 commands.append("no {0} {1}".format(key, existing_value))
273 else:
274 if key.replace(" ", "_").replace("-", "_") in BOOL_PARAMS:
275 commands.append("no {0}".format(key.lower()))
276 elif key == "multisite ingress-replication" and value != existing_commands.get(key):
277 vni_command = "member vni {0}".format(module.params["vni"])
278 if vni_command not in commands:
279 commands.append("member vni {0}".format(module.params["vni"]))
280 if value == "disable":
281 command = "no {0}".format(key)
282 commands.append(command)
283 elif value == "enable":
284 command = "{0}".format(key)
285 commands.append(command)
286 elif value == "optimized":
287 command = "{0} {1}".format(key, value)
288 commands.append(command)
289 else:
290 command = "{0} {1}".format(key, value.lower())
291 commands.append(command)
292
293 if commands:
294 vni_command = "member vni {0}".format(module.params["vni"])
295 ingress_replications_command = "ingress-replication protocol static"
296 ingress_replicationb_command = "ingress-replication protocol bgp"
297 ingress_replicationns_command = "no ingress-replication protocol static"
298 ingress_replicationnb_command = "no ingress-replication protocol bgp"
299 interface_command = "interface {0}".format(module.params["interface"])
300
301 if any(
302 c in commands
303 for c in (
304 ingress_replications_command,
305 ingress_replicationb_command,
306 ingress_replicationnb_command,
307 ingress_replicationns_command,
308 )
309 ):
310 static_level_cmds = [cmd for cmd in commands if "peer" in cmd]
311 parents = [interface_command, vni_command]
312 commands = [cmd for cmd in commands if "peer" not in cmd]
313 for cmd in commands:
314 parents.append(cmd)
315 candidate.add(static_level_cmds, parents=parents)
316
317 elif "peer-ip" in commands[0]:
318 static_level_cmds = list(commands)
319 parents = [
320 interface_command,
321 vni_command,
322 ingress_replications_command,
323 ]
324 candidate.add(static_level_cmds, parents=parents)
325
326 if vni_command in commands:
327 parents = [interface_command]
328 commands.remove(vni_command)
329 if module.params["assoc_vrf"] is None:
330 parents.append(vni_command)
331 candidate.add(commands, parents=parents)
332
333
334 def state_absent(module, existing, proposed, candidate):
335 if existing["assoc_vrf"]:
336 commands = ["no member vni {0} associate-vrf".format(module.params["vni"])]
337 else:
338 commands = ["no member vni {0}".format(module.params["vni"])]
339 parents = ["interface {0}".format(module.params["interface"])]
340 candidate.add(commands, parents=parents)
341
342
343 def main():
344 argument_spec = dict(
345 interface=dict(required=True, type="str"),
346 vni=dict(required=True, type="str"),
347 assoc_vrf=dict(required=False, type="bool"),
348 multicast_group=dict(required=False, type="str"),
349 peer_list=dict(required=False, type="list", elements="str"),
350 suppress_arp=dict(required=False, type="bool"),
351 suppress_arp_disable=dict(required=False, type="bool"),
352 ingress_replication=dict(required=False, type="str", choices=["bgp", "static", "default"]),
353 state=dict(choices=["present", "absent"], default="present", required=False),
354 multisite_ingress_replication=dict(
355 required=False,
356 type="str",
357 choices=["enable", "optimized", "disable"],
358 ),
359 )
360
361 mutually_exclusive = [
362 ("suppress_arp", "suppress_arp_disable"),
363 ("assoc_vrf", "multicast_group"),
364 ("assoc_vrf", "suppress_arp"),
365 ("assoc_vrf", "suppress_arp_disable"),
366 ("assoc_vrf", "ingress_replication"),
367 ]
368 module = AnsibleModule(
369 argument_spec=argument_spec,
370 mutually_exclusive=mutually_exclusive,
371 supports_check_mode=True,
372 )
373
374 warnings = list()
375 result = {"changed": False, "commands": [], "warnings": warnings}
376
377 if module.params["peer_list"]:
378 if (
379 module.params["peer_list"][0] != "default"
380 and module.params["ingress_replication"] != "static"
381 ):
382 module.fail_json(
383 msg="ingress_replication=static is required " "when using peer_list param",
384 )
385 else:
386 peer_list = module.params["peer_list"]
387 if peer_list[0] == "default":
388 module.params["peer_list"] = "default"
389 else:
390 stripped_peer_list = list(map(str.strip, peer_list))
391 module.params["peer_list"] = stripped_peer_list
392
393 if (
394 module.params["multisite_ingress_replication"] == "enable"
395 or module.params["multisite_ingress_replication"] == "optimized"
396 ):
397 if module.params["ingress_replication"] == "static":
398 module.fail_json(
399 msg="ingress_replication=static is not allowed "
400 "when using multisite_ingress_replication",
401 )
402
403 state = module.params["state"]
404 args = PARAM_TO_COMMAND_KEYMAP.keys()
405 existing, interface_exist = get_existing(module, args)
406
407 if state == "present":
408 if not interface_exist:
409 module.fail_json(
410 msg="The proposed NVE interface does not exist. Use nxos_interface to create it first.",
411 )
412 elif interface_exist != module.params["interface"]:
413 module.fail_json(msg="Only 1 NVE interface is allowed on the switch.")
414 elif state == "absent":
415 if interface_exist != module.params["interface"]:
416 module.exit_json(**result)
417 elif existing and existing["vni"] != module.params["vni"]:
418 module.fail_json(
419 msg="ERROR: VNI delete failed: Could not find vni node for {0}".format(
420 module.params["vni"],
421 ),
422 existing_vni=existing["vni"],
423 )
424
425 proposed_args = dict((k, v) for k, v in module.params.items() if v is not None and k in args)
426
427 proposed = {}
428 for key, value in proposed_args.items():
429 if key in ["multicast_group", "peer_list", "ingress_replication"]:
430 if str(value).lower() == "default":
431 value = PARAM_TO_DEFAULT_KEYMAP.get(key, "default")
432 if key != "interface" and existing.get(key) != value:
433 proposed[key] = value
434
435 candidate = CustomNetworkConfig(indent=3)
436 if state == "present":
437 state_present(module, existing, proposed, candidate)
438 elif existing and state == "absent":
439 state_absent(module, existing, proposed, candidate)
440
441 if candidate:
442 candidate = candidate.items_text()
443 result["changed"] = True
444 result["commands"] = candidate
445 if not module.check_mode:
446 load_config(module, candidate)
447
448 module.exit_json(**result)
449
450
451 if __name__ == "__main__":
452 main()