Debian Codegraph @

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