Debian Codegraph @

ansible_collections/fortinet/fortios/plugins/modules/fortios_wanopt_webcache.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_wanopt_webcache
23 short_description: Configure global Web cache settings 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 wanopt feature and webcache 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 wanopt_webcache:
80 description:
81 - Configure global Web cache settings.
82 default: null
83 type: dict
84 suboptions:
85 always_revalidate:
86 description:
87 - Enable/disable revalidation of requested cached objects, which have content on the server, before serving it to the client.
88 type: str
89 choices:
90 - 'enable'
91 - 'disable'
92 cache_by_default:
93 description:
94 - Enable/disable caching content that lacks explicit caching policies from the server.
95 type: str
96 choices:
97 - 'enable'
98 - 'disable'
99 cache_cookie:
100 description:
101 - Enable/disable caching cookies. Since cookies contain information for or about individual users, they not usually cached.
102 type: str
103 choices:
104 - 'enable'
105 - 'disable'
106 cache_expired:
107 description:
108 - Enable/disable caching type-1 objects that are already expired on arrival.
109 type: str
110 choices:
111 - 'enable'
112 - 'disable'
113 default_ttl:
114 description:
115 - Default object expiry time . This only applies to those objects that do not have an expiry time set by the web server.
116 type: int
117 external:
118 description:
119 - Enable/disable external Web caching.
120 type: str
121 choices:
122 - 'enable'
123 - 'disable'
124 fresh_factor:
125 description:
126 - Frequency that the server is checked to see if any objects have expired (1 - 100). The higher the fresh factor, the less often the
127 checks occur.
128 type: int
129 host_validate:
130 description:
131 - 'Enable/disable validating "Host:" with original server IP.'
132 type: str
133 choices:
134 - 'enable'
135 - 'disable'
136 ignore_conditional:
137 description:
138 - Enable/disable controlling the behavior of cache-control HTTP 1.1 header values.
139 type: str
140 choices:
141 - 'enable'
142 - 'disable'
143 ignore_ie_reload:
144 description:
145 - 'Enable/disable ignoring the PNC-interpretation of Internet Explorer"s Accept: / header.'
146 type: str
147 choices:
148 - 'enable'
149 - 'disable'
150 ignore_ims:
151 description:
152 - Enable/disable ignoring the if-modified-since (IMS) header.
153 type: str
154 choices:
155 - 'enable'
156 - 'disable'
157 ignore_pnc:
158 description:
159 - Enable/disable ignoring the pragma no-cache (PNC) header.
160 type: str
161 choices:
162 - 'enable'
163 - 'disable'
164 max_object_size:
165 description:
166 - Maximum cacheable object size in kB (1 - 2147483 kb (2GB). All objects that exceed this are delivered to the client but not stored in
167 the web cache.
168 type: int
169 max_ttl:
170 description:
171 - Maximum time an object can stay in the web cache without checking to see if it has expired on the server .
172 type: int
173 min_ttl:
174 description:
175 - Minimum time an object can stay in the web cache without checking to see if it has expired on the server .
176 type: int
177 neg_resp_time:
178 description:
179 - Time in minutes to cache negative responses or errors (0 - 4294967295).
180 type: int
181 reval_pnc:
182 description:
183 - Enable/disable revalidation of pragma-no-cache (PNC) to address bandwidth concerns.
184 type: str
185 choices:
186 - 'enable'
187 - 'disable'
188 """
189
190 EXAMPLES = """
191 - name: Configure global Web cache settings.
192 fortinet.fortios.fortios_wanopt_webcache:
193 vdom: "{{ vdom }}"
194 wanopt_webcache:
195 always_revalidate: "enable"
196 cache_by_default: "enable"
197 cache_cookie: "enable"
198 cache_expired: "enable"
199 default_ttl: "1440"
200 external: "enable"
201 fresh_factor: "100"
202 host_validate: "enable"
203 ignore_conditional: "enable"
204 ignore_ie_reload: "enable"
205 ignore_ims: "enable"
206 ignore_pnc: "enable"
207 max_object_size: "512000"
208 max_ttl: "7200"
209 min_ttl: "5"
210 neg_resp_time: "0"
211 reval_pnc: "enable"
212 """
213
214 RETURN = """
215 build:
216 description: Build number of the fortigate image
217 returned: always
218 type: str
219 sample: '1547'
220 http_method:
221 description: Last method used to provision the content into FortiGate
222 returned: always
223 type: str
224 sample: 'PUT'
225 http_status:
226 description: Last result given by FortiGate on last operation applied
227 returned: always
228 type: str
229 sample: "200"
230 mkey:
231 description: Master key (id) used in the last call to FortiGate
232 returned: success
233 type: str
234 sample: "id"
235 name:
236 description: Name of the table used to fulfill the request
237 returned: always
238 type: str
239 sample: "urlfilter"
240 path:
241 description: Path of the table used to fulfill the request
242 returned: always
243 type: str
244 sample: "webfilter"
245 revision:
246 description: Internal revision number
247 returned: always
248 type: str
249 sample: "17.0.2.10658"
250 serial:
251 description: Serial number of the unit
252 returned: always
253 type: str
254 sample: "FGVMEVYYQT3AB5352"
255 status:
256 description: Indication of the operation's result
257 returned: always
258 type: str
259 sample: "success"
260 vdom:
261 description: Virtual domain used
262 returned: always
263 type: str
264 sample: "root"
265 version:
266 description: Version of the FortiGate
267 returned: always
268 type: str
269 sample: "v5.6.3"
270 """
271 from ansible.module_utils.basic import AnsibleModule
272 from ansible.module_utils.connection import Connection
273 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
274 FortiOSHandler,
275 )
276 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
277 check_legacy_fortiosapi,
278 )
279 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
280 schema_to_module_spec,
281 )
282 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
283 check_schema_versioning,
284 )
285 from ansible_collections.fortinet.fortios.plugins.module_utils.fortimanager.common import (
286 FAIL_SOCKET_MSG,
287 )
288 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.data_post_processor import (
289 remove_invalid_fields,
290 )
291 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
292 is_same_comparison,
293 )
294 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
295 serialize,
296 )
297 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
298 find_current_values,
299 )
300 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
301 unify_data_format,
302 )
303
304
305 def filter_wanopt_webcache_data(json):
306 option_list = [
307 "always_revalidate",
308 "cache_by_default",
309 "cache_cookie",
310 "cache_expired",
311 "default_ttl",
312 "external",
313 "fresh_factor",
314 "host_validate",
315 "ignore_conditional",
316 "ignore_ie_reload",
317 "ignore_ims",
318 "ignore_pnc",
319 "max_object_size",
320 "max_ttl",
321 "min_ttl",
322 "neg_resp_time",
323 "reval_pnc",
324 ]
325
326 json = remove_invalid_fields(json)
327 dictionary = {}
328
329 for attribute in option_list:
330 if attribute in json and json[attribute] is not None:
331 dictionary[attribute] = json[attribute]
332
333 return dictionary
334
335
336 def underscore_to_hyphen(data):
337 new_data = None
338 if isinstance(data, list):
339 new_data = []
340 for i, elem in enumerate(data):
341 new_data.append(underscore_to_hyphen(elem))
342 elif isinstance(data, dict):
343 new_data = {}
344 for k, v in data.items():
345 new_data[k.replace("_", "-")] = underscore_to_hyphen(v)
346 else:
347 return data
348 return new_data
349
350
351 def wanopt_webcache(data, fos, check_mode=False):
352
353 state = None
354 vdom = data["vdom"]
355 parameters = None
356 state = data.get("state", None)
357 wanopt_webcache_data = data["wanopt_webcache"]
358
359 filtered_data = filter_wanopt_webcache_data(wanopt_webcache_data)
360 converted_data = underscore_to_hyphen(filtered_data)
361
362 # check_mode starts from here
363 if check_mode:
364 diff = {
365 "before": "",
366 "after": filtered_data,
367 }
368 mkeyname = fos.get_mkeyname(None, None)
369 mkey = fos.get_mkey("wanopt", "webcache", filtered_data, vdom=vdom)
370 current_data = fos.get(
371 "wanopt", "webcache", vdom=vdom, mkey=mkey, parameters=parameters
372 )
373 is_existed = (
374 current_data
375 and current_data.get("http_status") == 200
376 and (
377 mkeyname
378 and isinstance(current_data.get("results"), list)
379 and len(current_data["results"]) > 0
380 or not mkeyname
381 and current_data["results"] # global object response
382 )
383 )
384
385 # 2. if it exists and the state is 'present' then compare current settings with desired
386 if state == "present" or state is True or state is None:
387 # for non global modules, mkeyname must exist and it's a new module when mkey is None
388 if mkeyname is not None and mkey is None:
389 return False, True, filtered_data, diff
390
391 # if mkey exists then compare each other
392 # record exits and they're matched or not
393 copied_filtered_data = filtered_data.copy()
394 copied_filtered_data.pop(mkeyname, None)
395 unified_filtered_data = unify_data_format(copied_filtered_data)
396
397 current_data_results = current_data.get("results", {})
398 current_config = (
399 current_data_results[0]
400 if mkeyname
401 and isinstance(current_data_results, list)
402 and len(current_data_results) > 0
403 else current_data_results
404 )
405 if is_existed:
406 unified_current_values = find_current_values(
407 unified_filtered_data,
408 unify_data_format(current_config),
409 )
410
411 is_same = is_same_comparison(
412 serialize(unified_current_values), serialize(unified_filtered_data)
413 )
414
415 return (
416 False,
417 not is_same,
418 filtered_data,
419 {"before": unified_current_values, "after": unified_filtered_data},
420 )
421
422 # record does not exist
423 return False, True, filtered_data, diff
424
425 if state == "absent":
426 if mkey is None:
427 return (
428 False,
429 False,
430 filtered_data,
431 {"before": current_data["results"][0], "after": ""},
432 )
433
434 if is_existed:
435 return (
436 False,
437 True,
438 filtered_data,
439 {"before": current_data["results"][0], "after": ""},
440 )
441 return False, False, filtered_data, {}
442
443 return True, False, {"reason: ": "Must provide state parameter"}, {}
444 # pass post processed data to member operations
445 # no need to do underscore_to_hyphen since do_member_operation handles it by itself
446 data_copy = data.copy()
447 data_copy["wanopt_webcache"] = filtered_data
448 fos.do_member_operation(
449 "wanopt",
450 "webcache",
451 data_copy,
452 )
453
454 return fos.set(
455 "wanopt", "webcache", data=converted_data, vdom=vdom, parameters=parameters
456 )
457
458
459 def is_successful_status(resp):
460 return (
461 "status" in resp
462 and resp["status"] == "success"
463 or "http_status" in resp
464 and resp["http_status"] == 200
465 or "http_method" in resp
466 and resp["http_method"] == "DELETE"
467 and resp["http_status"] == 404
468 )
469
470
471 def fortios_wanopt(data, fos, check_mode):
472
473 if data["wanopt_webcache"]:
474 resp = wanopt_webcache(data, fos, check_mode)
475 else:
476 fos._module.fail_json(msg="missing task body: %s" % ("wanopt_webcache"))
477 if isinstance(resp, tuple) and len(resp) == 4:
478 return resp
479 return (
480 not is_successful_status(resp),
481 is_successful_status(resp)
482 and (resp["revision_changed"] if "revision_changed" in resp else True),
483 resp,
484 {},
485 )
486
487
488 versioned_schema = {
489 "v_range": [["v6.0.0", ""]],
490 "type": "dict",
491 "children": {
492 "max_object_size": {"v_range": [["v6.0.0", ""]], "type": "integer"},
493 "neg_resp_time": {"v_range": [["v6.0.0", ""]], "type": "integer"},
494 "fresh_factor": {"v_range": [["v6.0.0", ""]], "type": "integer"},
495 "max_ttl": {"v_range": [["v6.0.0", ""]], "type": "integer"},
496 "min_ttl": {"v_range": [["v6.0.0", ""]], "type": "integer"},
497 "default_ttl": {"v_range": [["v6.0.0", ""]], "type": "integer"},
498 "ignore_ims": {
499 "v_range": [["v6.0.0", ""]],
500 "type": "string",
501 "options": [{"value": "enable"}, {"value": "disable"}],
502 },
503 "ignore_conditional": {
504 "v_range": [["v6.0.0", ""]],
505 "type": "string",
506 "options": [{"value": "enable"}, {"value": "disable"}],
507 },
508 "ignore_pnc": {
509 "v_range": [["v6.0.0", ""]],
510 "type": "string",
511 "options": [{"value": "enable"}, {"value": "disable"}],
512 },
513 "ignore_ie_reload": {
514 "v_range": [["v6.0.0", ""]],
515 "type": "string",
516 "options": [{"value": "enable"}, {"value": "disable"}],
517 },
518 "cache_expired": {
519 "v_range": [["v6.0.0", ""]],
520 "type": "string",
521 "options": [{"value": "enable"}, {"value": "disable"}],
522 },
523 "cache_cookie": {
524 "v_range": [["v6.0.0", ""]],
525 "type": "string",
526 "options": [{"value": "enable"}, {"value": "disable"}],
527 },
528 "reval_pnc": {
529 "v_range": [["v6.0.0", ""]],
530 "type": "string",
531 "options": [{"value": "enable"}, {"value": "disable"}],
532 },
533 "always_revalidate": {
534 "v_range": [["v6.0.0", ""]],
535 "type": "string",
536 "options": [{"value": "enable"}, {"value": "disable"}],
537 },
538 "cache_by_default": {
539 "v_range": [["v6.0.0", ""]],
540 "type": "string",
541 "options": [{"value": "enable"}, {"value": "disable"}],
542 },
543 "host_validate": {
544 "v_range": [["v6.0.0", ""]],
545 "type": "string",
546 "options": [{"value": "enable"}, {"value": "disable"}],
547 },
548 "external": {
549 "v_range": [["v6.0.0", ""]],
550 "type": "string",
551 "options": [{"value": "enable"}, {"value": "disable"}],
552 },
553 },
554 }
555
556
557 def main():
558 module_spec = schema_to_module_spec(versioned_schema)
559 mkeyname = None
560 fields = {
561 "access_token": {"required": False, "type": "str", "no_log": True},
562 "enable_log": {"required": False, "type": "bool", "default": False},
563 "vdom": {"required": False, "type": "str", "default": "root"},
564 "member_path": {"required": False, "type": "str"},
565 "member_state": {
566 "type": "str",
567 "required": False,
568 "choices": ["present", "absent"],
569 },
570 "wanopt_webcache": {
571 "required": False,
572 "type": "dict",
573 "default": None,
574 "options": {},
575 },
576 }
577 for attribute_name in module_spec["options"]:
578 fields["wanopt_webcache"]["options"][attribute_name] = module_spec["options"][
579 attribute_name
580 ]
581 if mkeyname and mkeyname == attribute_name:
582 fields["wanopt_webcache"]["options"][attribute_name]["required"] = True
583
584 module = AnsibleModule(argument_spec=fields, supports_check_mode=True)
585 check_legacy_fortiosapi(module)
586
587 is_error = False
588 has_changed = False
589 result = None
590 diff = None
591
592 versions_check_result = None
593 if module._socket_path:
594 connection = Connection(module._socket_path)
595 if "access_token" in module.params:
596 connection.set_custom_option("access_token", module.params["access_token"])
597
598 if "enable_log" in module.params:
599 connection.set_custom_option("enable_log", module.params["enable_log"])
600 else:
601 connection.set_custom_option("enable_log", False)
602 fos = FortiOSHandler(connection, module, mkeyname, admin_passwd_header=False)
603 versions_check_result = check_schema_versioning(
604 fos, versioned_schema, "wanopt_webcache"
605 )
606
607 is_error, has_changed, result, diff = fortios_wanopt(
608 module.params, fos, module.check_mode
609 )
610
611 else:
612 module.fail_json(**FAIL_SOCKET_MSG)
613
614 if versions_check_result and versions_check_result["matched"] is False:
615 module.warn(
616 "Ansible has detected version mismatch between FortOS system and your playbook, see more details by specifying option -vvv"
617 )
618
619 if not is_error:
620 if versions_check_result and versions_check_result["matched"] is False:
621 module.exit_json(
622 changed=has_changed,
623 version_check_warning=versions_check_result,
624 meta=result,
625 diff=diff,
626 )
627 else:
628 module.exit_json(changed=has_changed, meta=result, diff=diff)
629 else:
630 if versions_check_result and versions_check_result["matched"] is False:
631 module.fail_json(
632 msg="Error in repo",
633 version_check_warning=versions_check_result,
634 meta=result,
635 )
636 else:
637 module.fail_json(msg="Error in repo", meta=result)
638
639
640 if __name__ == "__main__":
641 main()