Debian Codegraph @

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