Debian Codegraph @

ansible_collections/cisco/nxos/plugins/modules/nxos_vrf_interface.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_interface
26 extends_documentation_fragment:
27 - cisco.nxos.nxos
28 short_description: (deprecated, removed after 2028-06-01) Manages interface specific VRF configuration.
29 description:
30 - Manages interface specific VRF 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 - VRF needs to be added globally with M(cisco.nxos.nxos_vrf) before adding a VRF to an interface.
39 - Remove a VRF from an interface will still remove all L3 attributes just as it does
40 from CLI.
41 - VRF is not read from an interface until IP address is configured on that interface.
42 options:
43 vrf:
44 description:
45 - Name of VRF to be managed.
46 required: true
47 type: str
48 interface:
49 description:
50 - Full name of interface to be managed, i.e. Ethernet1/1.
51 required: true
52 type: str
53 state:
54 description:
55 - Manages desired state of the resource.
56 required: false
57 default: present
58 choices:
59 - present
60 - absent
61 type: str
62 """
63
64 EXAMPLES = """
65 - name: Ensure vrf ntc exists on Eth1/1
66 cisco.nxos.nxos_vrf_interface:
67 vrf: ntc
68 interface: Ethernet1/1
69 state: present
70
71 - name: Ensure ntc VRF does not exist on Eth1/1
72 cisco.nxos.nxos_vrf_interface:
73 vrf: ntc
74 interface: Ethernet1/1
75 state: absent
76 """
77
78 RETURN = """
79 commands:
80 description: commands sent to the device
81 returned: always
82 type: list
83 sample: ["interface loopback16", "vrf member ntc"]
84 """
85 import re
86
87 from ansible.module_utils.basic import AnsibleModule
88
89 from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.nxos import (
90 get_capabilities,
91 get_interface_type,
92 load_config,
93 normalize_interface,
94 run_commands,
95 )
96
97
98 def execute_show_command(command, module):
99 if "show run" not in command:
100 output = "json"
101 else:
102 output = "text"
103 cmds = [{"command": command, "output": output}]
104 return run_commands(module, cmds)[0]
105
106
107 def get_interface_mode(interface, intf_type, module):
108 command = "show interface {0}".format(interface)
109 interface = {}
110 mode = "unknown"
111
112 if intf_type in ["ethernet", "portchannel"]:
113 body = execute_show_command(command, module)
114 try:
115 interface_table = body["TABLE_interface"]["ROW_interface"]
116 except KeyError:
117 return mode
118
119 if interface_table and isinstance(interface_table, dict):
120 mode = str(interface_table.get("eth_mode", "layer3"))
121 if mode == "access" or mode == "trunk":
122 mode = "layer2"
123 else:
124 return mode
125
126 elif intf_type == "loopback" or intf_type == "svi":
127 mode = "layer3"
128 return mode
129
130
131 def get_vrf_list(module):
132 command = "show vrf all"
133 vrf_list = []
134 body = execute_show_command(command, module)
135
136 try:
137 vrf_table = body["TABLE_vrf"]["ROW_vrf"]
138 except (KeyError, AttributeError):
139 return vrf_list
140
141 for each in vrf_table:
142 vrf_list.append(str(each["vrf_name"]))
143
144 return vrf_list
145
146
147 def get_interface_info(interface, module):
148 if not interface.startswith("loopback"):
149 interface = interface.capitalize()
150
151 command = "show run interface {0}".format(interface)
152 vrf_regex = r".*vrf\s+member\s+(?P<vrf>\S+).*"
153
154 try:
155 body = execute_show_command(command, module)
156 match_vrf = re.match(vrf_regex, body, re.DOTALL)
157 group_vrf = match_vrf.groupdict()
158 vrf = group_vrf["vrf"]
159 except (AttributeError, TypeError):
160 return ""
161
162 return vrf
163
164
165 def is_default(interface, module):
166 command = "show run interface {0}".format(interface)
167
168 try:
169 body = execute_show_command(command, module)
170 raw_list = body.split("\n")
171 if raw_list[-1].startswith("interface"):
172 return True
173 else:
174 return False
175
176 except (KeyError, IndexError):
177 return "DNE"
178
179
180 def main():
181 argument_spec = dict(
182 vrf=dict(required=True),
183 interface=dict(type="str", required=True),
184 state=dict(default="present", choices=["present", "absent"], required=False),
185 )
186
187 module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
188
189 warnings = list()
190 results = {"changed": False, "commands": [], "warnings": warnings}
191
192 vrf = module.params["vrf"]
193 interface = normalize_interface(module.params["interface"])
194 state = module.params["state"]
195
196 device_info = get_capabilities(module)
197 network_api = device_info.get("network_api", "nxapi")
198
199 current_vrfs = get_vrf_list(module)
200 if vrf not in current_vrfs:
201 warnings.append("The VRF is not present/active on the device. Use nxos_vrf to fix this.")
202
203 intf_type = get_interface_type(interface)
204 if intf_type != "ethernet" and network_api == "cliconf":
205 if is_default(interface, module) == "DNE":
206 module.fail_json(
207 msg="interface does not exist on switch. Verify "
208 "switch platform or create it first with "
209 "nxos_interfaces if it's a logical interface",
210 )
211
212 mode = get_interface_mode(interface, intf_type, module)
213 if mode == "layer2":
214 module.fail_json(
215 msg="Ensure interface is a Layer 3 port before "
216 "configuring a VRF on an interface. You can "
217 "use nxos_interfaces",
218 )
219
220 current_vrf = get_interface_info(interface, module)
221 existing = dict(interface=interface, vrf=current_vrf)
222 changed = False
223
224 if not existing["vrf"]:
225 pass
226 elif vrf != existing["vrf"] and state == "absent":
227 module.fail_json(
228 msg="The VRF you are trying to remove "
229 "from the interface does not exist "
230 "on that interface.",
231 interface=interface,
232 proposed_vrf=vrf,
233 existing_vrf=existing["vrf"],
234 )
235
236 commands = []
237 if existing:
238 if state == "absent":
239 if existing and vrf == existing["vrf"]:
240 command = "no vrf member {0}".format(vrf)
241 commands.append(command)
242
243 elif state == "present":
244 if existing["vrf"] != vrf:
245 command = "vrf member {0}".format(vrf)
246 commands.append(command)
247
248 if commands:
249 commands.insert(0, "interface {0}".format(interface))
250
251 if commands:
252 if module.check_mode:
253 module.exit_json(changed=True, commands=commands)
254 else:
255 load_config(module, commands)
256 changed = True
257 if "configure" in commands:
258 commands.pop(0)
259
260 results["commands"] = commands
261 results["changed"] = changed
262
263 module.exit_json(**results)
264
265
266 if __name__ == "__main__":
267 main()