Debian Codegraph @

ansible_collections/cisco/nxos/plugins/modules/nxos_vtp_password.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_vtp_password
26 extends_documentation_fragment:
27 - cisco.nxos.nxos
28 short_description: Manages VTP password configuration.
29 description:
30 - Manages VTP password configuration.
31 version_added: 1.0.0
32 author:
33 - Gabriele Gerbino (@GGabriele)
34 notes:
35 - Tested against NXOSv 7.3.(0)D1(1) on VIRL
36 - Unsupported for Cisco MDS
37 - VTP feature must be active on the device to use this module.
38 - This module is used to manage only VTP passwords.
39 - Use this in combination with M(cisco.nxos.nxos_vtp_domain) and M(cisco.nxos.nxos_vtp_version) to fully
40 manage VTP operations.
41 - You can set/remove password only if a VTP domain already exist.
42 - If C(state=absent) and no C(vtp_password) is provided, it remove the current VTP
43 password.
44 - If C(state=absent) and C(vtp_password) is provided, the proposed C(vtp_password)
45 has to match the existing one in order to remove it.
46 options:
47 vtp_password:
48 description:
49 - VTP password
50 type: str
51 state:
52 description:
53 - Manage the state of the resource
54 default: present
55 choices:
56 - present
57 - absent
58 type: str
59 """
60
61 EXAMPLES = """
62 # ENSURE VTP PASSWORD IS SET
63 - cisco.nxos.nxos_vtp_password:
64 state: present
65 host: '{{ inventory_hostname }}'
66 username: '{{ un }}'
67 password: '{{ pwd }}'
68
69 # ENSURE VTP PASSWORD IS REMOVED
70 - cisco.nxos.nxos_vtp_password:
71 state: absent
72 host: '{{ inventory_hostname }}'
73 username: '{{ un }}'
74 password: '{{ pwd }}'
75 """
76
77 RETURN = """
78 proposed:
79 description: k/v pairs of parameters passed into module
80 returned: always
81 type: dict
82 sample: {"vtp_password": "new_ntc"}
83 existing:
84 description:
85 - k/v pairs of existing vtp
86 returned: always
87 type: dict
88 sample: {"domain": "ntc", "version": "1", "vtp_password": "ntc"}
89 end_state:
90 description: k/v pairs of vtp after module execution
91 returned: always
92 type: dict
93 sample: {"domain": "ntc", "version": "1", "vtp_password": "new_ntc"}
94 updates:
95 description: command sent to the device
96 returned: always
97 type: list
98 sample: ["vtp password new_ntc"]
99 changed:
100 description: check to see if a change was made on the device
101 returned: always
102 type: bool
103 sample: true
104 """
105
106 import re
107
108 from ansible.module_utils.basic import AnsibleModule
109
110 from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.nxos import (
111 get_capabilities,
112 load_config,
113 run_commands,
114 )
115
116
117 def execute_show_command(command, module, output="json"):
118 cmds = [{"command": command, "output": output}]
119 body = run_commands(module, cmds)
120 return body
121
122
123 def flatten_list(command_lists):
124 flat_command_list = []
125 for command in command_lists:
126 if isinstance(command, list):
127 flat_command_list.extend(command)
128 else:
129 flat_command_list.append(command)
130 return flat_command_list
131
132
133 def apply_key_map(key_map, table):
134 new_dict = {}
135 for key, value in table.items():
136 new_key = key_map.get(key)
137 if new_key:
138 value = table.get(key)
139 if value:
140 new_dict[new_key] = str(value)
141 else:
142 new_dict[new_key] = value
143 return new_dict
144
145
146 def get_vtp_config(module):
147 command = "show vtp status"
148
149 body = execute_show_command(command, module, "text")[0]
150 vtp_parsed = {}
151
152 if body:
153 version_regex = r".*VTP version running\s+:\s+(?P<version>\d).*"
154 domain_regex = r".*VTP Domain Name\s+:\s+(?P<domain>\S+).*"
155
156 try:
157 match_version = re.match(version_regex, body, re.DOTALL)
158 version = match_version.groupdict()["version"]
159 except AttributeError:
160 version = ""
161
162 try:
163 match_domain = re.match(domain_regex, body, re.DOTALL)
164 domain = match_domain.groupdict()["domain"]
165 except AttributeError:
166 domain = ""
167
168 if domain and version:
169 vtp_parsed["domain"] = domain
170 vtp_parsed["version"] = version
171 vtp_parsed["vtp_password"] = get_vtp_password(module)
172
173 return vtp_parsed
174
175
176 def get_vtp_password(module):
177 command = "show vtp password"
178 output = "json"
179 cap = get_capabilities(module)["device_info"]["network_os_model"]
180 if re.search(r"Nexus 6", cap):
181 output = "text"
182
183 body = execute_show_command(command, module, output)[0]
184
185 if output == "json":
186 password = body.get("passwd", "")
187 else:
188 password = ""
189 rp = r"VTP Password: (\S+)"
190 mo = re.search(rp, body)
191 if mo:
192 password = mo.group(1)
193
194 return str(password)
195
196
197 def main():
198 argument_spec = dict(
199 vtp_password=dict(type="str", no_log=True),
200 state=dict(choices=["absent", "present"], default="present"),
201 )
202
203 module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
204
205 warnings = list()
206
207 vtp_password = module.params["vtp_password"] or None
208 state = module.params["state"]
209
210 existing = get_vtp_config(module)
211 end_state = existing
212
213 args = dict(vtp_password=vtp_password)
214
215 changed = False
216 proposed = dict((k, v) for k, v in args.items() if v is not None)
217 delta = dict(set(proposed.items()).difference(existing.items()))
218
219 commands = []
220 if state == "absent":
221 # if vtp_password is not set, some devices returns '\\' or the string 'None'
222 if (
223 not existing["vtp_password"]
224 or existing["vtp_password"] == "\\"
225 or existing["vtp_password"] == "None"
226 ):
227 pass
228 elif vtp_password is not None:
229 if existing["vtp_password"] == proposed["vtp_password"]:
230 commands.append(["no vtp password"])
231 else:
232 module.fail_json(
233 msg="Proposed vtp password doesn't match "
234 "current vtp password. It cannot be "
235 "removed when state=absent. If you are "
236 "trying to change the vtp password, use "
237 "state=present.",
238 )
239 else:
240 if not existing.get("domain"):
241 module.fail_json(msg="Cannot remove a vtp password " "before vtp domain is set.")
242
243 elif existing["vtp_password"] != ("\\"):
244 commands.append(["no vtp password"])
245
246 elif state == "present":
247 if delta:
248 if not existing.get("domain"):
249 module.fail_json(msg="Cannot set vtp password " "before vtp domain is set.")
250
251 else:
252 commands.append(["vtp password {0}".format(vtp_password)])
253
254 cmds = flatten_list(commands)
255 if cmds:
256 if module.check_mode:
257 module.exit_json(changed=True, commands=cmds)
258 else:
259 changed = True
260 load_config(module, cmds)
261 end_state = get_vtp_config(module)
262 if "configure" in cmds:
263 cmds.pop(0)
264
265 results = {}
266 results["proposed"] = proposed
267 results["existing"] = existing
268 results["end_state"] = end_state
269 results["updates"] = cmds
270 results["changed"] = changed
271 results["warnings"] = warnings
272
273 module.exit_json(**results)
274
275
276 if __name__ == "__main__":
277 main()