Debian Codegraph @

ansible_collections/fortinet/fortios/plugins/modules/fortios_firewall_dnstranslation.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_firewall_dnstranslation
23 short_description: Configure DNS translation 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 firewall feature and dnstranslation 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 - We highly recommend using your own value as the id instead of 0, while '0' is a special placeholder that allows the backend to assign the latest
39 available number for the object, it does have limitations. Please find more details in Q&A.
40 - Legacy fortiosapi has been deprecated, httpapi is the preferred way to run playbooks
41
42 - The module supports check_mode.
43
44 requirements:
45 - ansible>=2.16
46 options:
47 access_token:
48 description:
49 - Token-based authentication.
50 Generated from GUI of Fortigate.
51 type: str
52 required: false
53 enable_log:
54 description:
55 - Enable/Disable logging for task.
56 type: bool
57 required: false
58 default: false
59 vdom:
60 description:
61 - Virtual domain, among those defined previously. A vdom is a
62 virtual instance of the FortiGate that can be configured and
63 used as a different unit.
64 type: str
65 default: root
66 member_path:
67 type: str
68 description:
69 - Member attribute path to operate on.
70 - Delimited by a slash character if there are more than one attribute.
71 - Parameter marked with member_path is legitimate for doing member operation.
72 member_state:
73 type: str
74 description:
75 - Add or delete a member under specified attribute path.
76 - When member_state is specified, the state option is ignored.
77 choices:
78 - 'present'
79 - 'absent'
80
81 state:
82 description:
83 - Indicates whether to create or remove the object.
84 type: str
85 required: true
86 choices:
87 - 'present'
88 - 'absent'
89 firewall_dnstranslation:
90 description:
91 - Configure DNS translation.
92 default: null
93 type: dict
94 suboptions:
95 dst:
96 description:
97 - IPv4 address or subnet on the external network to substitute for the resolved address in DNS query replies. Can be single IP address or
98 subnet on the external network, but number of addresses must equal number of mapped IP addresses in src.
99 type: str
100 id:
101 description:
102 - ID. see <a href='#notes'>Notes</a>.
103 required: true
104 type: int
105 netmask:
106 description:
107 - If src and dst are subnets rather than single IP addresses, enter the netmask for both src and dst.
108 type: str
109 src:
110 description:
111 - IPv4 address or subnet on the internal network to compare with the resolved address in DNS query replies. If the resolved address
112 matches, the resolved address is substituted with dst.
113 type: str
114 """
115
116 EXAMPLES = """
117 - name: Configure DNS translation.
118 fortinet.fortios.fortios_firewall_dnstranslation:
119 vdom: "{{ vdom }}"
120 state: "present"
121 access_token: "<your_own_value>"
122 firewall_dnstranslation:
123 dst: "<your_own_value>"
124 id: "4"
125 netmask: "<your_own_value>"
126 src: "<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_firewall_dnstranslation_data(json):
221 option_list = ["dst", "id", "netmask", "src"]
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 firewall_dnstranslation(data, fos, check_mode=False):
249
250 state = None
251 vdom = data["vdom"]
252 parameters = None
253 state = data.get("state", None)
254 firewall_dnstranslation_data = data["firewall_dnstranslation"]
255
256 filtered_data = filter_firewall_dnstranslation_data(firewall_dnstranslation_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("firewall", "dnstranslation", filtered_data, vdom=vdom)
267 current_data = fos.get(
268 "firewall", "dnstranslation", 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["firewall_dnstranslation"] = filtered_data
345 fos.do_member_operation(
346 "firewall",
347 "dnstranslation",
348 data_copy,
349 )
350
351 if state == "present" or state is True:
352 return fos.set(
353 "firewall",
354 "dnstranslation",
355 data=converted_data,
356 vdom=vdom,
357 parameters=parameters,
358 )
359
360 elif state == "absent":
361 return fos.delete(
362 "firewall",
363 "dnstranslation",
364 mkey=converted_data["id"],
365 vdom=vdom,
366 parameters=parameters,
367 )
368 else:
369 fos._module.fail_json(msg="state must be present or absent!")
370
371
372 def is_successful_status(resp):
373 return (
374 "status" in resp
375 and resp["status"] == "success"
376 or "http_status" in resp
377 and resp["http_status"] == 200
378 or "http_method" in resp
379 and resp["http_method"] == "DELETE"
380 and resp["http_status"] == 404
381 )
382
383
384 def fortios_firewall(data, fos, check_mode):
385
386 if data["firewall_dnstranslation"]:
387 resp = firewall_dnstranslation(data, fos, check_mode)
388 else:
389 fos._module.fail_json(msg="missing task body: %s" % ("firewall_dnstranslation"))
390 if isinstance(resp, tuple) and len(resp) == 4:
391 return resp
392 return (
393 not is_successful_status(resp),
394 is_successful_status(resp)
395 and (resp["revision_changed"] if "revision_changed" in resp else True),
396 resp,
397 {},
398 )
399
400
401 versioned_schema = {
402 "type": "list",
403 "elements": "dict",
404 "children": {
405 "id": {"v_range": [["v6.0.0", ""]], "type": "integer", "required": True},
406 "src": {"v_range": [["v6.0.0", ""]], "type": "string"},
407 "dst": {"v_range": [["v6.0.0", ""]], "type": "string"},
408 "netmask": {"v_range": [["v6.0.0", ""]], "type": "string"},
409 },
410 "v_range": [["v6.0.0", ""]],
411 }
412
413
414 def main():
415 module_spec = schema_to_module_spec(versioned_schema)
416 mkeyname = "id"
417 fields = {
418 "access_token": {"required": False, "type": "str", "no_log": True},
419 "enable_log": {"required": False, "type": "bool", "default": False},
420 "vdom": {"required": False, "type": "str", "default": "root"},
421 "member_path": {"required": False, "type": "str"},
422 "member_state": {
423 "type": "str",
424 "required": False,
425 "choices": ["present", "absent"],
426 },
427 "state": {"required": True, "type": "str", "choices": ["present", "absent"]},
428 "firewall_dnstranslation": {
429 "required": False,
430 "type": "dict",
431 "default": None,
432 "options": {},
433 },
434 }
435 for attribute_name in module_spec["options"]:
436 fields["firewall_dnstranslation"]["options"][attribute_name] = module_spec[
437 "options"
438 ][attribute_name]
439 if mkeyname and mkeyname == attribute_name:
440 fields["firewall_dnstranslation"]["options"][attribute_name][
441 "required"
442 ] = True
443
444 module = AnsibleModule(argument_spec=fields, supports_check_mode=True)
445 check_legacy_fortiosapi(module)
446
447 is_error = False
448 has_changed = False
449 result = None
450 diff = None
451
452 versions_check_result = None
453 if module._socket_path:
454 connection = Connection(module._socket_path)
455 if "access_token" in module.params:
456 connection.set_custom_option("access_token", module.params["access_token"])
457
458 if "enable_log" in module.params:
459 connection.set_custom_option("enable_log", module.params["enable_log"])
460 else:
461 connection.set_custom_option("enable_log", False)
462 fos = FortiOSHandler(connection, module, mkeyname, admin_passwd_header=False)
463 versions_check_result = check_schema_versioning(
464 fos, versioned_schema, "firewall_dnstranslation"
465 )
466
467 is_error, has_changed, result, diff = fortios_firewall(
468 module.params, fos, module.check_mode
469 )
470
471 else:
472 module.fail_json(**FAIL_SOCKET_MSG)
473
474 if versions_check_result and versions_check_result["matched"] is False:
475 module.warn(
476 "Ansible has detected version mismatch between FortOS system and your playbook, see more details by specifying option -vvv"
477 )
478
479 if not is_error:
480 if versions_check_result and versions_check_result["matched"] is False:
481 module.exit_json(
482 changed=has_changed,
483 version_check_warning=versions_check_result,
484 meta=result,
485 diff=diff,
486 )
487 else:
488 module.exit_json(changed=has_changed, meta=result, diff=diff)
489 else:
490 if versions_check_result and versions_check_result["matched"] is False:
491 module.fail_json(
492 msg="Error in repo",
493 version_check_warning=versions_check_result,
494 meta=result,
495 )
496 else:
497 module.fail_json(msg="Error in repo", meta=result)
498
499
500 if __name__ == "__main__":
501 main()