Debian Codegraph @

ansible_collections/fortinet/fortios/plugins/modules/fortios_icap_server.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_icap_server
23 short_description: Configure ICAP servers 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 icap feature and server 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 icap_server:
88 description:
89 - Configure ICAP servers.
90 default: null
91 type: dict
92 suboptions:
93 addr_type:
94 description:
95 - 'Address type of the remote ICAP server: IPv4, IPv6 or FQDN.'
96 type: str
97 choices:
98 - 'ip4'
99 - 'ip6'
100 - 'fqdn'
101 fqdn:
102 description:
103 - ICAP remote server Fully Qualified Domain Name (FQDN).
104 type: str
105 healthcheck:
106 description:
107 - Enable/disable ICAP remote server health checking. Attempts to connect to the remote ICAP server to verify that the server is operating
108 normally.
109 type: str
110 choices:
111 - 'disable'
112 - 'enable'
113 healthcheck_service:
114 description:
115 - ICAP Service name to use for health checks.
116 type: str
117 ip_address:
118 description:
119 - IPv4 address of the ICAP server.
120 type: str
121 ip_version:
122 description:
123 - IP version.
124 type: str
125 choices:
126 - '4'
127 - '6'
128 ip6_address:
129 description:
130 - IPv6 address of the ICAP server.
131 type: str
132 max_connections:
133 description:
134 - Maximum number of concurrent connections to ICAP server (unlimited = 0). Must not be less than wad-worker-count.
135 type: int
136 name:
137 description:
138 - Server name.
139 required: true
140 type: str
141 port:
142 description:
143 - ICAP server port.
144 type: int
145 secure:
146 description:
147 - Enable/disable secure connection to ICAP server.
148 type: str
149 choices:
150 - 'disable'
151 - 'enable'
152 ssl_cert:
153 description:
154 - CA certificate name. Source certificate.ca.name.
155 type: str
156 """
157
158 EXAMPLES = """
159 - name: Configure ICAP servers.
160 fortinet.fortios.fortios_icap_server:
161 vdom: "{{ vdom }}"
162 state: "present"
163 access_token: "<your_own_value>"
164 icap_server:
165 addr_type: "ip4"
166 fqdn: "<your_own_value>"
167 healthcheck: "disable"
168 healthcheck_service: "<your_own_value>"
169 ip_address: "<your_own_value>"
170 ip_version: "4"
171 ip6_address: "<your_own_value>"
172 max_connections: "100"
173 name: "default_name_11"
174 port: "1344"
175 secure: "disable"
176 ssl_cert: "<your_own_value> (source certificate.ca.name)"
177 """
178
179 RETURN = """
180 build:
181 description: Build number of the fortigate image
182 returned: always
183 type: str
184 sample: '1547'
185 http_method:
186 description: Last method used to provision the content into FortiGate
187 returned: always
188 type: str
189 sample: 'PUT'
190 http_status:
191 description: Last result given by FortiGate on last operation applied
192 returned: always
193 type: str
194 sample: "200"
195 mkey:
196 description: Master key (id) used in the last call to FortiGate
197 returned: success
198 type: str
199 sample: "id"
200 name:
201 description: Name of the table used to fulfill the request
202 returned: always
203 type: str
204 sample: "urlfilter"
205 path:
206 description: Path of the table used to fulfill the request
207 returned: always
208 type: str
209 sample: "webfilter"
210 revision:
211 description: Internal revision number
212 returned: always
213 type: str
214 sample: "17.0.2.10658"
215 serial:
216 description: Serial number of the unit
217 returned: always
218 type: str
219 sample: "FGVMEVYYQT3AB5352"
220 status:
221 description: Indication of the operation's result
222 returned: always
223 type: str
224 sample: "success"
225 vdom:
226 description: Virtual domain used
227 returned: always
228 type: str
229 sample: "root"
230 version:
231 description: Version of the FortiGate
232 returned: always
233 type: str
234 sample: "v5.6.3"
235 """
236 from ansible.module_utils.basic import AnsibleModule
237 from ansible.module_utils.connection import Connection
238 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
239 FortiOSHandler,
240 )
241 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
242 check_legacy_fortiosapi,
243 )
244 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
245 schema_to_module_spec,
246 )
247 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
248 check_schema_versioning,
249 )
250 from ansible_collections.fortinet.fortios.plugins.module_utils.fortimanager.common import (
251 FAIL_SOCKET_MSG,
252 )
253 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.data_post_processor import (
254 remove_invalid_fields,
255 )
256 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
257 is_same_comparison,
258 )
259 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
260 serialize,
261 )
262 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
263 find_current_values,
264 )
265 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
266 unify_data_format,
267 )
268
269
270 def filter_icap_server_data(json):
271 option_list = [
272 "addr_type",
273 "fqdn",
274 "healthcheck",
275 "healthcheck_service",
276 "ip_address",
277 "ip_version",
278 "ip6_address",
279 "max_connections",
280 "name",
281 "port",
282 "secure",
283 "ssl_cert",
284 ]
285
286 json = remove_invalid_fields(json)
287 dictionary = {}
288
289 for attribute in option_list:
290 if attribute in json and json[attribute] is not None:
291 dictionary[attribute] = json[attribute]
292
293 return dictionary
294
295
296 def underscore_to_hyphen(data):
297 new_data = None
298 if isinstance(data, list):
299 new_data = []
300 for i, elem in enumerate(data):
301 new_data.append(underscore_to_hyphen(elem))
302 elif isinstance(data, dict):
303 new_data = {}
304 for k, v in data.items():
305 new_data[k.replace("_", "-")] = underscore_to_hyphen(v)
306 else:
307 return data
308 return new_data
309
310
311 def icap_server(data, fos, check_mode=False):
312
313 state = None
314 vdom = data["vdom"]
315 parameters = None
316 state = data.get("state", None)
317 icap_server_data = data["icap_server"]
318
319 filtered_data = filter_icap_server_data(icap_server_data)
320 converted_data = underscore_to_hyphen(filtered_data)
321
322 # check_mode starts from here
323 if check_mode:
324 diff = {
325 "before": "",
326 "after": filtered_data,
327 }
328 mkeyname = fos.get_mkeyname(None, None)
329 mkey = fos.get_mkey("icap", "server", filtered_data, vdom=vdom)
330 current_data = fos.get(
331 "icap", "server", vdom=vdom, mkey=mkey, parameters=parameters
332 )
333 is_existed = (
334 current_data
335 and current_data.get("http_status") == 200
336 and (
337 mkeyname
338 and isinstance(current_data.get("results"), list)
339 and len(current_data["results"]) > 0
340 or not mkeyname
341 and current_data["results"] # global object response
342 )
343 )
344
345 # 2. if it exists and the state is 'present' then compare current settings with desired
346 if state == "present" or state is True or state is None:
347 # for non global modules, mkeyname must exist and it's a new module when mkey is None
348 if mkeyname is not None and mkey is None:
349 return False, True, filtered_data, diff
350
351 # if mkey exists then compare each other
352 # record exits and they're matched or not
353 copied_filtered_data = filtered_data.copy()
354 copied_filtered_data.pop(mkeyname, None)
355 unified_filtered_data = unify_data_format(copied_filtered_data)
356
357 current_data_results = current_data.get("results", {})
358 current_config = (
359 current_data_results[0]
360 if mkeyname
361 and isinstance(current_data_results, list)
362 and len(current_data_results) > 0
363 else current_data_results
364 )
365 if is_existed:
366 unified_current_values = find_current_values(
367 unified_filtered_data,
368 unify_data_format(current_config),
369 )
370
371 is_same = is_same_comparison(
372 serialize(unified_current_values), serialize(unified_filtered_data)
373 )
374
375 return (
376 False,
377 not is_same,
378 filtered_data,
379 {"before": unified_current_values, "after": unified_filtered_data},
380 )
381
382 # record does not exist
383 return False, True, filtered_data, diff
384
385 if state == "absent":
386 if mkey is None:
387 return (
388 False,
389 False,
390 filtered_data,
391 {"before": current_data["results"][0], "after": ""},
392 )
393
394 if is_existed:
395 return (
396 False,
397 True,
398 filtered_data,
399 {"before": current_data["results"][0], "after": ""},
400 )
401 return False, False, filtered_data, {}
402
403 return True, False, {"reason: ": "Must provide state parameter"}, {}
404 # pass post processed data to member operations
405 # no need to do underscore_to_hyphen since do_member_operation handles it by itself
406 data_copy = data.copy()
407 data_copy["icap_server"] = filtered_data
408 fos.do_member_operation(
409 "icap",
410 "server",
411 data_copy,
412 )
413
414 if state == "present" or state is True:
415 return fos.set(
416 "icap", "server", data=converted_data, vdom=vdom, parameters=parameters
417 )
418
419 elif state == "absent":
420 return fos.delete(
421 "icap",
422 "server",
423 mkey=converted_data["name"],
424 vdom=vdom,
425 parameters=parameters,
426 )
427 else:
428 fos._module.fail_json(msg="state must be present or absent!")
429
430
431 def is_successful_status(resp):
432 return (
433 "status" in resp
434 and resp["status"] == "success"
435 or "http_status" in resp
436 and resp["http_status"] == 200
437 or "http_method" in resp
438 and resp["http_method"] == "DELETE"
439 and resp["http_status"] == 404
440 )
441
442
443 def fortios_icap(data, fos, check_mode):
444
445 if data["icap_server"]:
446 resp = icap_server(data, fos, check_mode)
447 else:
448 fos._module.fail_json(msg="missing task body: %s" % ("icap_server"))
449 if isinstance(resp, tuple) and len(resp) == 4:
450 return resp
451 return (
452 not is_successful_status(resp),
453 is_successful_status(resp)
454 and (resp["revision_changed"] if "revision_changed" in resp else True),
455 resp,
456 {},
457 )
458
459
460 versioned_schema = {
461 "type": "list",
462 "elements": "dict",
463 "children": {
464 "name": {"v_range": [["v6.0.0", ""]], "type": "string", "required": True},
465 "addr_type": {
466 "v_range": [["v7.2.0", ""]],
467 "type": "string",
468 "options": [{"value": "ip4"}, {"value": "ip6"}, {"value": "fqdn"}],
469 },
470 "ip_address": {"v_range": [["v6.0.0", ""]], "type": "string"},
471 "ip6_address": {"v_range": [["v6.0.0", ""]], "type": "string"},
472 "fqdn": {"v_range": [["v7.2.0", ""]], "type": "string"},
473 "port": {"v_range": [["v6.0.0", ""]], "type": "integer"},
474 "max_connections": {"v_range": [["v6.0.0", ""]], "type": "integer"},
475 "secure": {
476 "v_range": [["v7.0.0", ""]],
477 "type": "string",
478 "options": [{"value": "disable"}, {"value": "enable"}],
479 },
480 "ssl_cert": {"v_range": [["v7.0.0", ""]], "type": "string"},
481 "healthcheck": {
482 "v_range": [["v7.2.0", ""]],
483 "type": "string",
484 "options": [{"value": "disable"}, {"value": "enable"}],
485 },
486 "healthcheck_service": {"v_range": [["v7.2.0", ""]], "type": "string"},
487 "ip_version": {
488 "v_range": [["v6.0.0", "v7.0.12"]],
489 "type": "string",
490 "options": [{"value": "4"}, {"value": "6"}],
491 },
492 },
493 "v_range": [["v6.0.0", ""]],
494 }
495
496
497 def main():
498 module_spec = schema_to_module_spec(versioned_schema)
499 mkeyname = "name"
500 fields = {
501 "access_token": {"required": False, "type": "str", "no_log": True},
502 "enable_log": {"required": False, "type": "bool", "default": False},
503 "vdom": {"required": False, "type": "str", "default": "root"},
504 "member_path": {"required": False, "type": "str"},
505 "member_state": {
506 "type": "str",
507 "required": False,
508 "choices": ["present", "absent"],
509 },
510 "state": {"required": True, "type": "str", "choices": ["present", "absent"]},
511 "icap_server": {
512 "required": False,
513 "type": "dict",
514 "default": None,
515 "options": {},
516 },
517 }
518 for attribute_name in module_spec["options"]:
519 fields["icap_server"]["options"][attribute_name] = module_spec["options"][
520 attribute_name
521 ]
522 if mkeyname and mkeyname == attribute_name:
523 fields["icap_server"]["options"][attribute_name]["required"] = True
524
525 module = AnsibleModule(argument_spec=fields, supports_check_mode=True)
526 check_legacy_fortiosapi(module)
527
528 is_error = False
529 has_changed = False
530 result = None
531 diff = None
532
533 versions_check_result = None
534 if module._socket_path:
535 connection = Connection(module._socket_path)
536 if "access_token" in module.params:
537 connection.set_custom_option("access_token", module.params["access_token"])
538
539 if "enable_log" in module.params:
540 connection.set_custom_option("enable_log", module.params["enable_log"])
541 else:
542 connection.set_custom_option("enable_log", False)
543 fos = FortiOSHandler(connection, module, mkeyname, admin_passwd_header=False)
544 versions_check_result = check_schema_versioning(
545 fos, versioned_schema, "icap_server"
546 )
547
548 is_error, has_changed, result, diff = fortios_icap(
549 module.params, fos, module.check_mode
550 )
551
552 else:
553 module.fail_json(**FAIL_SOCKET_MSG)
554
555 if versions_check_result and versions_check_result["matched"] is False:
556 module.warn(
557 "Ansible has detected version mismatch between FortOS system and your playbook, see more details by specifying option -vvv"
558 )
559
560 if not is_error:
561 if versions_check_result and versions_check_result["matched"] is False:
562 module.exit_json(
563 changed=has_changed,
564 version_check_warning=versions_check_result,
565 meta=result,
566 diff=diff,
567 )
568 else:
569 module.exit_json(changed=has_changed, meta=result, diff=diff)
570 else:
571 if versions_check_result and versions_check_result["matched"] is False:
572 module.fail_json(
573 msg="Error in repo",
574 version_check_warning=versions_check_result,
575 meta=result,
576 )
577 else:
578 module.fail_json(msg="Error in repo", meta=result)
579
580
581 if __name__ == "__main__":
582 main()