Debian Codegraph @

ansible_collections/fortinet/fortios/plugins/modules/fortios_user_tacacsplus.py

raw symbols SCIP
1 #!/usr/bin/python
2 from __future__ import absolute_import, division, print_function
3
4 # Copyright: (c) 2022 Fortinet
5 # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
6 #
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11
12 __metaclass__ = type
13
14 ANSIBLE_METADATA = {
15 "status": ["preview"],
16 "supported_by": "community",
17 "metadata_version": "1.1",
18 }
19
20 DOCUMENTATION = """
21 ---
22 module: fortios_user_tacacsplus
23 short_description: Configure TACACS+ server entries in Fortinet's FortiOS and FortiGate.
24 description:
25 - This module is able to configure a FortiGate or FortiOS (FOS) device by allowing the
26 user to set and modify user feature and tacacsplus category.
27 Examples include all parameters and values need to be adjusted to datasources before usage.
28 Tested with FOS v6.0.0
29 version_added: "2.0.0"
30 author:
31 - Link Zheng (@chillancezen)
32 - Jie Xue (@JieX19)
33 - Hongbin Lu (@fgtdev-hblu)
34 - Frank Shen (@frankshen01)
35 - Miguel Angel Munoz (@mamunozgonzalez)
36 - Nicolas Thomas (@thomnico)
37 notes:
38 - Legacy fortiosapi has been deprecated, httpapi is the preferred way to run playbooks
39
40 - The module supports check_mode.
41
42 requirements:
43 - ansible>=2.16
44 options:
45 access_token:
46 description:
47 - Token-based authentication.
48 Generated from GUI of Fortigate.
49 type: str
50 required: false
51 enable_log:
52 description:
53 - Enable/Disable logging for task.
54 type: bool
55 required: false
56 default: false
57 vdom:
58 description:
59 - Virtual domain, among those defined previously. A vdom is a
60 virtual instance of the FortiGate that can be configured and
61 used as a different unit.
62 type: str
63 default: root
64 member_path:
65 type: str
66 description:
67 - Member attribute path to operate on.
68 - Delimited by a slash character if there are more than one attribute.
69 - Parameter marked with member_path is legitimate for doing member operation.
70 member_state:
71 type: str
72 description:
73 - Add or delete a member under specified attribute path.
74 - When member_state is specified, the state option is ignored.
75 choices:
76 - 'present'
77 - 'absent'
78
79 state:
80 description:
81 - Indicates whether to create or remove the object.
82 type: str
83 required: true
84 choices:
85 - 'present'
86 - 'absent'
87 user_tacacsplus:
88 description:
89 - Configure TACACS+ server entries.
90 default: null
91 type: dict
92 suboptions:
93 authen_type:
94 description:
95 - Allowed authentication protocols/methods.
96 type: str
97 choices:
98 - 'mschap'
99 - 'chap'
100 - 'pap'
101 - 'ascii'
102 - 'auto'
103 authorization:
104 description:
105 - Enable/disable TACACS+ authorization.
106 type: str
107 choices:
108 - 'enable'
109 - 'disable'
110 interface:
111 description:
112 - Specify outgoing interface to reach server. Source system.interface.name.
113 type: str
114 interface_select_method:
115 description:
116 - Specify how to select outgoing interface to reach server.
117 type: str
118 choices:
119 - 'auto'
120 - 'sdwan'
121 - 'specify'
122 key:
123 description:
124 - Key to access the primary server.
125 type: str
126 name:
127 description:
128 - TACACS+ server entry name.
129 required: true
130 type: str
131 port:
132 description:
133 - Port number of the TACACS+ server.
134 type: int
135 secondary_key:
136 description:
137 - Key to access the secondary server.
138 type: str
139 secondary_server:
140 description:
141 - Secondary TACACS+ server CN domain name or IP address.
142 type: str
143 server:
144 description:
145 - Primary TACACS+ server CN domain name or IP address.
146 type: str
147 source_ip:
148 description:
149 - Source IP address for communications to TACACS+ server.
150 type: str
151 status_ttl:
152 description:
153 - Time for which server reachability is cached so that when a server is unreachable, it will not be retried for at least this period of
154 time (0 = cache disabled).
155 type: int
156 tertiary_key:
157 description:
158 - Key to access the tertiary server.
159 type: str
160 tertiary_server:
161 description:
162 - Tertiary TACACS+ server CN domain name or IP address.
163 type: str
164 vrf_select:
165 description:
166 - VRF ID used for connection to server.
167 type: int
168 """
169
170 EXAMPLES = """
171 - name: Configure TACACS+ server entries.
172 fortinet.fortios.fortios_user_tacacsplus:
173 vdom: "{{ vdom }}"
174 state: "present"
175 access_token: "<your_own_value>"
176 user_tacacsplus:
177 authen_type: "mschap"
178 authorization: "enable"
179 interface: "<your_own_value> (source system.interface.name)"
180 interface_select_method: "auto"
181 key: "<your_own_value>"
182 name: "default_name_8"
183 port: "49"
184 secondary_key: "<your_own_value>"
185 secondary_server: "<your_own_value>"
186 server: "192.168.100.40"
187 source_ip: "84.230.14.43"
188 status_ttl: "300"
189 tertiary_key: "<your_own_value>"
190 tertiary_server: "<your_own_value>"
191 vrf_select: "0"
192 """
193
194 RETURN = """
195 build:
196 description: Build number of the fortigate image
197 returned: always
198 type: str
199 sample: '1547'
200 http_method:
201 description: Last method used to provision the content into FortiGate
202 returned: always
203 type: str
204 sample: 'PUT'
205 http_status:
206 description: Last result given by FortiGate on last operation applied
207 returned: always
208 type: str
209 sample: "200"
210 mkey:
211 description: Master key (id) used in the last call to FortiGate
212 returned: success
213 type: str
214 sample: "id"
215 name:
216 description: Name of the table used to fulfill the request
217 returned: always
218 type: str
219 sample: "urlfilter"
220 path:
221 description: Path of the table used to fulfill the request
222 returned: always
223 type: str
224 sample: "webfilter"
225 revision:
226 description: Internal revision number
227 returned: always
228 type: str
229 sample: "17.0.2.10658"
230 serial:
231 description: Serial number of the unit
232 returned: always
233 type: str
234 sample: "FGVMEVYYQT3AB5352"
235 status:
236 description: Indication of the operation's result
237 returned: always
238 type: str
239 sample: "success"
240 vdom:
241 description: Virtual domain used
242 returned: always
243 type: str
244 sample: "root"
245 version:
246 description: Version of the FortiGate
247 returned: always
248 type: str
249 sample: "v5.6.3"
250 """
251 from ansible.module_utils.basic import AnsibleModule
252 from ansible.module_utils.connection import Connection
253 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
254 FortiOSHandler,
255 )
256 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
257 check_legacy_fortiosapi,
258 )
259 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
260 schema_to_module_spec,
261 )
262 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
263 check_schema_versioning,
264 )
265 from ansible_collections.fortinet.fortios.plugins.module_utils.fortimanager.common import (
266 FAIL_SOCKET_MSG,
267 )
268 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.data_post_processor import (
269 remove_invalid_fields,
270 )
271 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
272 is_same_comparison,
273 )
274 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
275 serialize,
276 )
277 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
278 find_current_values,
279 )
280 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
281 unify_data_format,
282 )
283
284
285 def filter_user_tacacsplus_data(json):
286 option_list = [
287 "authen_type",
288 "authorization",
289 "interface",
290 "interface_select_method",
291 "key",
292 "name",
293 "port",
294 "secondary_key",
295 "secondary_server",
296 "server",
297 "source_ip",
298 "status_ttl",
299 "tertiary_key",
300 "tertiary_server",
301 "vrf_select",
302 ]
303
304 json = remove_invalid_fields(json)
305 dictionary = {}
306
307 for attribute in option_list:
308 if attribute in json and json[attribute] is not None:
309 dictionary[attribute] = json[attribute]
310
311 return dictionary
312
313
314 def underscore_to_hyphen(data):
315 new_data = None
316 if isinstance(data, list):
317 new_data = []
318 for i, elem in enumerate(data):
319 new_data.append(underscore_to_hyphen(elem))
320 elif isinstance(data, dict):
321 new_data = {}
322 for k, v in data.items():
323 new_data[k.replace("_", "-")] = underscore_to_hyphen(v)
324 else:
325 return data
326 return new_data
327
328
329 def user_tacacsplus(data, fos, check_mode=False):
330
331 state = None
332 vdom = data["vdom"]
333 parameters = None
334 state = data.get("state", None)
335 user_tacacsplus_data = data["user_tacacsplus"]
336
337 filtered_data = filter_user_tacacsplus_data(user_tacacsplus_data)
338 converted_data = underscore_to_hyphen(filtered_data)
339
340 # check_mode starts from here
341 if check_mode:
342 diff = {
343 "before": "",
344 "after": filtered_data,
345 }
346 mkeyname = fos.get_mkeyname(None, None)
347 mkey = fos.get_mkey("user", "tacacs+", filtered_data, vdom=vdom)
348 current_data = fos.get(
349 "user", "tacacs+", vdom=vdom, mkey=mkey, parameters=parameters
350 )
351 is_existed = (
352 current_data
353 and current_data.get("http_status") == 200
354 and (
355 mkeyname
356 and isinstance(current_data.get("results"), list)
357 and len(current_data["results"]) > 0
358 or not mkeyname
359 and current_data["results"] # global object response
360 )
361 )
362
363 # 2. if it exists and the state is 'present' then compare current settings with desired
364 if state == "present" or state is True or state is None:
365 # for non global modules, mkeyname must exist and it's a new module when mkey is None
366 if mkeyname is not None and mkey is None:
367 return False, True, filtered_data, diff
368
369 # if mkey exists then compare each other
370 # record exits and they're matched or not
371 copied_filtered_data = filtered_data.copy()
372 copied_filtered_data.pop(mkeyname, None)
373 unified_filtered_data = unify_data_format(copied_filtered_data)
374
375 current_data_results = current_data.get("results", {})
376 current_config = (
377 current_data_results[0]
378 if mkeyname
379 and isinstance(current_data_results, list)
380 and len(current_data_results) > 0
381 else current_data_results
382 )
383 if is_existed:
384 unified_current_values = find_current_values(
385 unified_filtered_data,
386 unify_data_format(current_config),
387 )
388
389 is_same = is_same_comparison(
390 serialize(unified_current_values), serialize(unified_filtered_data)
391 )
392
393 return (
394 False,
395 not is_same,
396 filtered_data,
397 {"before": unified_current_values, "after": unified_filtered_data},
398 )
399
400 # record does not exist
401 return False, True, filtered_data, diff
402
403 if state == "absent":
404 if mkey is None:
405 return (
406 False,
407 False,
408 filtered_data,
409 {"before": current_data["results"][0], "after": ""},
410 )
411
412 if is_existed:
413 return (
414 False,
415 True,
416 filtered_data,
417 {"before": current_data["results"][0], "after": ""},
418 )
419 return False, False, filtered_data, {}
420
421 return True, False, {"reason: ": "Must provide state parameter"}, {}
422 # pass post processed data to member operations
423 # no need to do underscore_to_hyphen since do_member_operation handles it by itself
424 data_copy = data.copy()
425 data_copy["user_tacacsplus"] = filtered_data
426 fos.do_member_operation(
427 "user",
428 "tacacs+",
429 data_copy,
430 )
431
432 if state == "present" or state is True:
433 return fos.set(
434 "user", "tacacs+", data=converted_data, vdom=vdom, parameters=parameters
435 )
436
437 elif state == "absent":
438 return fos.delete(
439 "user",
440 "tacacs+",
441 mkey=converted_data["name"],
442 vdom=vdom,
443 parameters=parameters,
444 )
445 else:
446 fos._module.fail_json(msg="state must be present or absent!")
447
448
449 def is_successful_status(resp):
450 return (
451 "status" in resp
452 and resp["status"] == "success"
453 or "http_status" in resp
454 and resp["http_status"] == 200
455 or "http_method" in resp
456 and resp["http_method"] == "DELETE"
457 and resp["http_status"] == 404
458 )
459
460
461 def fortios_user(data, fos, check_mode):
462
463 if data["user_tacacsplus"]:
464 resp = user_tacacsplus(data, fos, check_mode)
465 else:
466 fos._module.fail_json(msg="missing task body: %s" % ("user_tacacsplus"))
467 if isinstance(resp, tuple) and len(resp) == 4:
468 return resp
469 return (
470 not is_successful_status(resp),
471 is_successful_status(resp)
472 and (resp["revision_changed"] if "revision_changed" in resp else True),
473 resp,
474 {},
475 )
476
477
478 versioned_schema = {
479 "type": "list",
480 "elements": "dict",
481 "children": {
482 "name": {"v_range": [["v6.0.0", ""]], "type": "string", "required": True},
483 "server": {"v_range": [["v6.0.0", ""]], "type": "string"},
484 "secondary_server": {"v_range": [["v6.0.0", ""]], "type": "string"},
485 "tertiary_server": {"v_range": [["v6.0.0", ""]], "type": "string"},
486 "port": {"v_range": [["v6.0.0", ""]], "type": "integer"},
487 "key": {"v_range": [["v6.0.0", ""]], "type": "string"},
488 "secondary_key": {"v_range": [["v6.0.0", ""]], "type": "string"},
489 "tertiary_key": {"v_range": [["v6.0.0", ""]], "type": "string"},
490 "status_ttl": {"v_range": [["v7.4.4", ""]], "type": "integer"},
491 "authen_type": {
492 "v_range": [["v6.0.0", ""]],
493 "type": "string",
494 "options": [
495 {"value": "mschap"},
496 {"value": "chap"},
497 {"value": "pap"},
498 {"value": "ascii"},
499 {"value": "auto"},
500 ],
501 },
502 "authorization": {
503 "v_range": [["v6.0.0", ""]],
504 "type": "string",
505 "options": [{"value": "enable"}, {"value": "disable"}],
506 },
507 "source_ip": {"v_range": [["v6.0.0", ""]], "type": "string"},
508 "interface_select_method": {
509 "v_range": [["v6.2.0", "v6.2.0"], ["v6.2.5", ""]],
510 "type": "string",
511 "options": [{"value": "auto"}, {"value": "sdwan"}, {"value": "specify"}],
512 },
513 "interface": {
514 "v_range": [["v6.2.0", "v6.2.0"], ["v6.2.5", ""]],
515 "type": "string",
516 },
517 "vrf_select": {"v_range": [["v7.6.1", ""]], "type": "integer"},
518 },
519 "v_range": [["v6.0.0", ""]],
520 }
521
522
523 def main():
524 module_spec = schema_to_module_spec(versioned_schema)
525 mkeyname = "name"
526 fields = {
527 "access_token": {"required": False, "type": "str", "no_log": True},
528 "enable_log": {"required": False, "type": "bool", "default": False},
529 "vdom": {"required": False, "type": "str", "default": "root"},
530 "member_path": {"required": False, "type": "str"},
531 "member_state": {
532 "type": "str",
533 "required": False,
534 "choices": ["present", "absent"],
535 },
536 "state": {"required": True, "type": "str", "choices": ["present", "absent"]},
537 "user_tacacsplus": {
538 "required": False,
539 "type": "dict",
540 "default": None,
541 "options": {},
542 },
543 }
544 for attribute_name in module_spec["options"]:
545 fields["user_tacacsplus"]["options"][attribute_name] = module_spec["options"][
546 attribute_name
547 ]
548 if mkeyname and mkeyname == attribute_name:
549 fields["user_tacacsplus"]["options"][attribute_name]["required"] = True
550
551 module = AnsibleModule(argument_spec=fields, supports_check_mode=True)
552 check_legacy_fortiosapi(module)
553
554 is_error = False
555 has_changed = False
556 result = None
557 diff = None
558
559 versions_check_result = None
560 if module._socket_path:
561 connection = Connection(module._socket_path)
562 if "access_token" in module.params:
563 connection.set_custom_option("access_token", module.params["access_token"])
564
565 if "enable_log" in module.params:
566 connection.set_custom_option("enable_log", module.params["enable_log"])
567 else:
568 connection.set_custom_option("enable_log", False)
569 fos = FortiOSHandler(connection, module, mkeyname, admin_passwd_header=False)
570 versions_check_result = check_schema_versioning(
571 fos, versioned_schema, "user_tacacsplus"
572 )
573
574 is_error, has_changed, result, diff = fortios_user(
575 module.params, fos, module.check_mode
576 )
577
578 else:
579 module.fail_json(**FAIL_SOCKET_MSG)
580
581 if versions_check_result and versions_check_result["matched"] is False:
582 module.warn(
583 "Ansible has detected version mismatch between FortOS system and your playbook, see more details by specifying option -vvv"
584 )
585
586 if not is_error:
587 if versions_check_result and versions_check_result["matched"] is False:
588 module.exit_json(
589 changed=has_changed,
590 version_check_warning=versions_check_result,
591 meta=result,
592 diff=diff,
593 )
594 else:
595 module.exit_json(changed=has_changed, meta=result, diff=diff)
596 else:
597 if versions_check_result and versions_check_result["matched"] is False:
598 module.fail_json(
599 msg="Error in repo",
600 version_check_warning=versions_check_result,
601 meta=result,
602 )
603 else:
604 module.fail_json(msg="Error in repo", meta=result)
605
606
607 if __name__ == "__main__":
608 main()