Debian Codegraph @

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