Debian Codegraph @

ansible_collections/cisco/nxos/plugins/modules/nxos_aaa_server_host.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_aaa_server_host
26 extends_documentation_fragment:
27 - cisco.nxos.nxos
28 short_description: Manages AAA server host-specific configuration.
29 description:
30 - Manages AAA server host-specific configuration.
31 version_added: 1.0.0
32 author: Jason Edelman (@jedelman8)
33 notes:
34 - Tested against NXOSv 7.3.(0)D1(1) on VIRL
35 - Limited Support for Cisco MDS
36 - Changes to the host key (shared secret) are not idempotent for type 0.
37 - If C(state=absent) removes the whole host configuration.
38 options:
39 server_type:
40 description:
41 - The server type is either radius or tacacs.
42 required: true
43 choices:
44 - radius
45 - tacacs
46 type: str
47 address:
48 description:
49 - Address or name of the radius or tacacs host.
50 required: true
51 type: str
52 key:
53 description:
54 - Shared secret for the specified host or keyword 'default'.
55 type: str
56 encrypt_type:
57 description:
58 - The state of encryption applied to the entered key. O for clear text, 7 for
59 encrypted. Type-6 encryption is not supported.
60 choices:
61 - '0'
62 - '7'
63 type: str
64 host_timeout:
65 description:
66 - Timeout period for specified host, in seconds or keyword 'default. Range is
67 1-60.
68 type: str
69 auth_port:
70 description:
71 - Alternate UDP port for RADIUS authentication or keyword 'default'.
72 type: str
73 acct_port:
74 description:
75 - Alternate UDP port for RADIUS accounting or keyword 'default'.
76 type: str
77 tacacs_port:
78 description:
79 - Alternate TCP port TACACS Server or keyword 'default'.
80 type: str
81 state:
82 description:
83 - Manage the state of the resource.
84 default: present
85 choices:
86 - present
87 - absent
88 type: str
89 """
90 EXAMPLES = """
91 # Radius Server Host Basic settings
92 - name: Radius Server Host Basic settings
93 cisco.nxos.nxos_aaa_server_host:
94 state: present
95 server_type: radius
96 address: 1.2.3.4
97 acct_port: 2084
98 host_timeout: 10
99
100 # Radius Server Host Key Configuration
101 - name: Radius Server Host Key Configuration
102 cisco.nxos.nxos_aaa_server_host:
103 state: present
104 server_type: radius
105 address: 1.2.3.4
106 key: hello
107 encrypt_type: 7
108
109 # TACACS Server Host Configuration
110 - name: Tacacs Server Host Configuration
111 cisco.nxos.nxos_aaa_server_host:
112 state: present
113 server_type: tacacs
114 tacacs_port: 89
115 host_timeout: 10
116 address: 5.6.7.8
117 """
118
119 RETURN = """
120 proposed:
121 description: k/v pairs of parameters passed into module
122 returned: always
123 type: dict
124 sample: {"address": "1.2.3.4", "auth_port": "2084",
125 "host_timeout": "10", "server_type": "radius"}
126 existing:
127 description:
128 - k/v pairs of existing configuration
129 returned: always
130 type: dict
131 sample: {}
132 end_state:
133 description: k/v pairs of configuration after module execution
134 returned: always
135 type: dict
136 sample: {"address": "1.2.3.4", "auth_port": "2084",
137 "host_timeout": "10", "server_type": "radius"}
138 updates:
139 description: command sent to the device
140 returned: always
141 type: list
142 sample: ["radius-server host 1.2.3.4 auth-port 2084 timeout 10"]
143 changed:
144 description: check to see if a change was made on the device
145 returned: always
146 type: bool
147 sample: true
148 """
149 import re
150
151 from ansible.module_utils.basic import AnsibleModule
152
153 from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.nxos import (
154 get_capabilities,
155 load_config,
156 run_commands,
157 )
158
159
160 def execute_show_command(command, module):
161 device_info = get_capabilities(module)
162 network_api = device_info.get("network_api", "nxapi")
163
164 if network_api == "cliconf":
165 cmds = [command]
166 body = run_commands(module, cmds)
167 elif network_api == "nxapi":
168 cmds = {"command": command, "output": "text"}
169 body = run_commands(module, cmds)
170
171 return body
172
173
174 def flatten_list(command_lists):
175 flat_command_list = []
176 for command in command_lists:
177 if isinstance(command, list):
178 flat_command_list.extend(command)
179 else:
180 flat_command_list.append(command)
181 return flat_command_list
182
183
184 def get_aaa_host_info(module, server_type, address):
185 aaa_host_info = {}
186 command = "show run | inc {0}-server.host.{1}".format(server_type, address)
187
188 body = execute_show_command(command, module)[0]
189 if body:
190 try:
191 if "radius" in body:
192 pattern = (
193 r"\S+ host \S+(?:\s+key 7\s+(\S+))?(?:\s+auth-port (\d+))?"
194 r"(?:\s+acct-port (\d+))?(?:\s+authentication)?"
195 r"(?:\s+accounting)?(?:\s+timeout (\d+))?"
196 )
197 match = re.search(pattern, body)
198 aaa_host_info["key"] = match.group(1)
199 if aaa_host_info["key"]:
200 aaa_host_info["key"] = aaa_host_info["key"].replace('"', "")
201 aaa_host_info["encrypt_type"] = "7"
202 aaa_host_info["auth_port"] = match.group(2)
203 aaa_host_info["acct_port"] = match.group(3)
204 aaa_host_info["host_timeout"] = match.group(4)
205 elif "tacacs" in body:
206 pattern = (
207 r"\S+ host \S+(?:\s+key 7\s+(\S+))?(?:\s+port (\d+))?(?:\s+timeout (\d+))?"
208 )
209 match = re.search(pattern, body)
210 aaa_host_info["key"] = match.group(1)
211 if aaa_host_info["key"]:
212 aaa_host_info["key"] = aaa_host_info["key"].replace('"', "")
213 aaa_host_info["encrypt_type"] = "7"
214 aaa_host_info["tacacs_port"] = match.group(2)
215 aaa_host_info["host_timeout"] = match.group(3)
216
217 aaa_host_info["server_type"] = server_type
218 aaa_host_info["address"] = address
219 except TypeError:
220 return {}
221 else:
222 return {}
223
224 return aaa_host_info
225
226
227 def config_aaa_host(server_type, address, params, existing):
228 cmds = []
229 cmd_str = "{0}-server host {1}".format(server_type, address)
230 cmd_no_str = "no " + cmd_str
231
232 key = params.get("key")
233 enc_type = params.get("encrypt_type", "")
234
235 defval = False
236 nondef = False
237
238 if key:
239 if key != "default":
240 cmds.append(cmd_str + " key {0} {1}".format(enc_type, key))
241 else:
242 cmds.append(cmd_no_str + " key 7 {0}".format(existing.get("key")))
243
244 locdict = {
245 "auth_port": "auth-port",
246 "acct_port": "acct-port",
247 "tacacs_port": "port",
248 "host_timeout": "timeout",
249 }
250
251 # platform CLI needs the keywords in the following order
252 for key in ["auth_port", "acct_port", "tacacs_port", "host_timeout"]:
253 item = params.get(key)
254 if item:
255 if item != "default":
256 cmd_str += " {0} {1}".format(locdict.get(key), item)
257 nondef = True
258 else:
259 cmd_no_str += " {0} 1".format(locdict.get(key))
260 defval = True
261 if defval:
262 cmds.append(cmd_no_str)
263 if nondef or not existing:
264 cmds.append(cmd_str)
265
266 return cmds
267
268
269 def main():
270 argument_spec = dict(
271 server_type=dict(choices=["radius", "tacacs"], required=True),
272 address=dict(type="str", required=True),
273 key=dict(type="str", no_log=False),
274 encrypt_type=dict(type="str", choices=["0", "7"]),
275 host_timeout=dict(type="str"),
276 auth_port=dict(type="str"),
277 acct_port=dict(type="str"),
278 tacacs_port=dict(type="str"),
279 state=dict(choices=["absent", "present"], default="present"),
280 )
281
282 module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
283
284 warnings = list()
285
286 server_type = module.params["server_type"]
287 address = module.params["address"]
288 key = module.params["key"]
289 encrypt_type = module.params["encrypt_type"]
290 host_timeout = module.params["host_timeout"]
291 auth_port = module.params["auth_port"]
292 acct_port = module.params["acct_port"]
293 tacacs_port = module.params["tacacs_port"]
294 state = module.params["state"]
295
296 args = dict(
297 server_type=server_type,
298 address=address,
299 key=key,
300 encrypt_type=encrypt_type,
301 host_timeout=host_timeout,
302 auth_port=auth_port,
303 acct_port=acct_port,
304 tacacs_port=tacacs_port,
305 )
306
307 proposed = dict((k, v) for k, v in args.items() if v is not None)
308 changed = False
309
310 if encrypt_type and not key:
311 module.fail_json(msg="encrypt_type must be used with key")
312
313 if tacacs_port and server_type != "tacacs":
314 module.fail_json(msg="tacacs_port can only be used with server_type=tacacs")
315
316 if (auth_port or acct_port) and server_type != "radius":
317 module.fail_json(
318 msg="auth_port and acct_port can only be used" "when server_type=radius",
319 )
320
321 existing = get_aaa_host_info(module, server_type, address)
322 end_state = existing
323
324 commands = []
325 delta = {}
326 if state == "present":
327 if not existing:
328 delta = proposed
329 else:
330 for key, value in proposed.items():
331 if key == "encrypt_type":
332 delta[key] = value
333 if value != existing.get(key):
334 if value != "default" or existing.get(key):
335 delta[key] = value
336
337 command = config_aaa_host(server_type, address, delta, existing)
338 if command:
339 commands.append(command)
340
341 elif state == "absent":
342 intersect = dict(set(proposed.items()).intersection(existing.items()))
343 if intersect.get("address") and intersect.get("server_type"):
344 command = "no {0}-server host {1}".format(
345 intersect.get("server_type"),
346 intersect.get("address"),
347 )
348 commands.append(command)
349
350 cmds = flatten_list(commands)
351 if cmds:
352 if module.check_mode:
353 module.exit_json(changed=True, commands=cmds)
354 else:
355 changed = True
356 load_config(module, cmds)
357 end_state = get_aaa_host_info(module, server_type, address)
358
359 results = {}
360 results["proposed"] = proposed
361 results["existing"] = existing
362 results["updates"] = cmds
363 results["changed"] = changed
364 results["warnings"] = warnings
365 results["end_state"] = end_state
366
367 module.exit_json(**results)
368
369
370 if __name__ == "__main__":
371 main()