Debian Codegraph @

ansible_collections/fortinet/fortios/plugins/modules/fortios_system_ddns.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_ddns
23 short_description: Configure DDNS 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 ddns 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 ddnsid 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 system_ddns:
90 description:
91 - Configure DDNS.
92 default: null
93 type: dict
94 suboptions:
95 addr_type:
96 description:
97 - Address type of interface address in DDNS update.
98 type: str
99 choices:
100 - 'ipv4'
101 - 'ipv6'
102 bound_ip:
103 description:
104 - Bound IP address.
105 type: str
106 clear_text:
107 description:
108 - Enable/disable use of clear text connections.
109 type: str
110 choices:
111 - 'disable'
112 - 'enable'
113 ddns_auth:
114 description:
115 - Enable/disable TSIG authentication for your DDNS server.
116 type: str
117 choices:
118 - 'disable'
119 - 'tsig'
120 ddns_domain:
121 description:
122 - Your fully qualified domain name. For example, yourname.ddns.com.
123 type: str
124 ddns_key:
125 description:
126 - DDNS update key (base 64 encoding).
127 type: str
128 ddns_keyname:
129 description:
130 - DDNS update key name.
131 type: str
132 ddns_password:
133 description:
134 - DDNS password.
135 type: str
136 ddns_server:
137 description:
138 - Select a DDNS service provider.
139 type: str
140 choices:
141 - 'dyndns.org'
142 - 'dyns.net'
143 - 'tzo.com'
144 - 'vavic.com'
145 - 'dipdns.net'
146 - 'now.net.cn'
147 - 'dhs.org'
148 - 'easydns.com'
149 - 'genericDDNS'
150 - 'FortiGuardDDNS'
151 - 'noip.com'
152 ddns_server_addr:
153 description:
154 - Generic DDNS server IP/FQDN list.
155 type: list
156 elements: dict
157 suboptions:
158 addr:
159 description:
160 - IP address or FQDN of the server.
161 required: true
162 type: str
163 ddns_server_ip:
164 description:
165 - Generic DDNS server IP.
166 type: str
167 ddns_sn:
168 description:
169 - DDNS Serial Number.
170 type: str
171 ddns_ttl:
172 description:
173 - Time-to-live for DDNS packets.
174 type: int
175 ddns_username:
176 description:
177 - DDNS user name.
178 type: str
179 ddns_zone:
180 description:
181 - Zone of your domain name (for example, DDNS.com).
182 type: str
183 ddnsid:
184 description:
185 - DDNS ID. see <a href='#notes'>Notes</a>.
186 required: true
187 type: int
188 monitor_interface:
189 description:
190 - Monitored interface.
191 type: list
192 elements: dict
193 suboptions:
194 interface_name:
195 description:
196 - Interface name. Source system.interface.name.
197 required: true
198 type: str
199 server_type:
200 description:
201 - Address type of the DDNS server.
202 type: str
203 choices:
204 - 'ipv4'
205 - 'ipv6'
206 ssl_certificate:
207 description:
208 - Name of local certificate for SSL connections. Source certificate.local.name.
209 type: str
210 update_interval:
211 description:
212 - DDNS update interval (60 - 2592000 sec, 0 means default).
213 type: int
214 use_public_ip:
215 description:
216 - Enable/disable use of public IP address.
217 type: str
218 choices:
219 - 'disable'
220 - 'enable'
221 """
222
223 EXAMPLES = """
224 - name: Configure DDNS.
225 fortinet.fortios.fortios_system_ddns:
226 vdom: "{{ vdom }}"
227 state: "present"
228 access_token: "<your_own_value>"
229 system_ddns:
230 addr_type: "ipv4"
231 bound_ip: "<your_own_value>"
232 clear_text: "disable"
233 ddns_auth: "disable"
234 ddns_domain: "<your_own_value>"
235 ddns_key: "<your_own_value>"
236 ddns_keyname: "<your_own_value>"
237 ddns_password: "<your_own_value>"
238 ddns_server: "dyndns.org"
239 ddns_server_addr:
240 -
241 addr: "<your_own_value>"
242 ddns_server_ip: "<your_own_value>"
243 ddns_sn: "<your_own_value>"
244 ddns_ttl: "300"
245 ddns_username: "<your_own_value>"
246 ddns_zone: "<your_own_value>"
247 ddnsid: "<you_own_value>"
248 monitor_interface:
249 -
250 interface_name: "<your_own_value> (source system.interface.name)"
251 server_type: "ipv4"
252 ssl_certificate: "<your_own_value> (source certificate.local.name)"
253 update_interval: "300"
254 use_public_ip: "disable"
255 """
256
257 RETURN = """
258 build:
259 description: Build number of the fortigate image
260 returned: always
261 type: str
262 sample: '1547'
263 http_method:
264 description: Last method used to provision the content into FortiGate
265 returned: always
266 type: str
267 sample: 'PUT'
268 http_status:
269 description: Last result given by FortiGate on last operation applied
270 returned: always
271 type: str
272 sample: "200"
273 mkey:
274 description: Master key (id) used in the last call to FortiGate
275 returned: success
276 type: str
277 sample: "id"
278 name:
279 description: Name of the table used to fulfill the request
280 returned: always
281 type: str
282 sample: "urlfilter"
283 path:
284 description: Path of the table used to fulfill the request
285 returned: always
286 type: str
287 sample: "webfilter"
288 revision:
289 description: Internal revision number
290 returned: always
291 type: str
292 sample: "17.0.2.10658"
293 serial:
294 description: Serial number of the unit
295 returned: always
296 type: str
297 sample: "FGVMEVYYQT3AB5352"
298 status:
299 description: Indication of the operation's result
300 returned: always
301 type: str
302 sample: "success"
303 vdom:
304 description: Virtual domain used
305 returned: always
306 type: str
307 sample: "root"
308 version:
309 description: Version of the FortiGate
310 returned: always
311 type: str
312 sample: "v5.6.3"
313 """
314 from ansible.module_utils.basic import AnsibleModule
315 from ansible.module_utils.connection import Connection
316 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
317 FortiOSHandler,
318 )
319 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
320 check_legacy_fortiosapi,
321 )
322 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
323 schema_to_module_spec,
324 )
325 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
326 check_schema_versioning,
327 )
328 from ansible_collections.fortinet.fortios.plugins.module_utils.fortimanager.common import (
329 FAIL_SOCKET_MSG,
330 )
331 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.data_post_processor import (
332 remove_invalid_fields,
333 )
334 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
335 is_same_comparison,
336 )
337 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
338 serialize,
339 )
340 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
341 find_current_values,
342 )
343 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
344 unify_data_format,
345 )
346
347
348 def filter_system_ddns_data(json):
349 option_list = [
350 "addr_type",
351 "bound_ip",
352 "clear_text",
353 "ddns_auth",
354 "ddns_domain",
355 "ddns_key",
356 "ddns_keyname",
357 "ddns_password",
358 "ddns_server",
359 "ddns_server_addr",
360 "ddns_server_ip",
361 "ddns_sn",
362 "ddns_ttl",
363 "ddns_username",
364 "ddns_zone",
365 "ddnsid",
366 "monitor_interface",
367 "server_type",
368 "ssl_certificate",
369 "update_interval",
370 "use_public_ip",
371 ]
372
373 json = remove_invalid_fields(json)
374 dictionary = {}
375
376 for attribute in option_list:
377 if attribute in json and json[attribute] is not None:
378 dictionary[attribute] = json[attribute]
379
380 return dictionary
381
382
383 def underscore_to_hyphen(data):
384 new_data = None
385 if isinstance(data, list):
386 new_data = []
387 for i, elem in enumerate(data):
388 new_data.append(underscore_to_hyphen(elem))
389 elif isinstance(data, dict):
390 new_data = {}
391 for k, v in data.items():
392 new_data[k.replace("_", "-")] = underscore_to_hyphen(v)
393 else:
394 return data
395 return new_data
396
397
398 def system_ddns(data, fos, check_mode=False):
399
400 state = None
401 vdom = data["vdom"]
402 parameters = None
403 state = data.get("state", None)
404 system_ddns_data = data["system_ddns"]
405
406 filtered_data = filter_system_ddns_data(system_ddns_data)
407 converted_data = underscore_to_hyphen(filtered_data)
408
409 # check_mode starts from here
410 if check_mode:
411 diff = {
412 "before": "",
413 "after": filtered_data,
414 }
415 mkeyname = fos.get_mkeyname(None, None)
416 mkey = fos.get_mkey("system", "ddns", filtered_data, vdom=vdom)
417 current_data = fos.get(
418 "system", "ddns", vdom=vdom, mkey=mkey, parameters=parameters
419 )
420 is_existed = (
421 current_data
422 and current_data.get("http_status") == 200
423 and (
424 mkeyname
425 and isinstance(current_data.get("results"), list)
426 and len(current_data["results"]) > 0
427 or not mkeyname
428 and current_data["results"] # global object response
429 )
430 )
431
432 # 2. if it exists and the state is 'present' then compare current settings with desired
433 if state == "present" or state is True or state is None:
434 # for non global modules, mkeyname must exist and it's a new module when mkey is None
435 if mkeyname is not None and mkey is None:
436 return False, True, filtered_data, diff
437
438 # if mkey exists then compare each other
439 # record exits and they're matched or not
440 copied_filtered_data = filtered_data.copy()
441 copied_filtered_data.pop(mkeyname, None)
442 unified_filtered_data = unify_data_format(copied_filtered_data)
443
444 current_data_results = current_data.get("results", {})
445 current_config = (
446 current_data_results[0]
447 if mkeyname
448 and isinstance(current_data_results, list)
449 and len(current_data_results) > 0
450 else current_data_results
451 )
452 if is_existed:
453 unified_current_values = find_current_values(
454 unified_filtered_data,
455 unify_data_format(current_config),
456 )
457
458 is_same = is_same_comparison(
459 serialize(unified_current_values), serialize(unified_filtered_data)
460 )
461
462 return (
463 False,
464 not is_same,
465 filtered_data,
466 {"before": unified_current_values, "after": unified_filtered_data},
467 )
468
469 # record does not exist
470 return False, True, filtered_data, diff
471
472 if state == "absent":
473 if mkey is None:
474 return (
475 False,
476 False,
477 filtered_data,
478 {"before": current_data["results"][0], "after": ""},
479 )
480
481 if is_existed:
482 return (
483 False,
484 True,
485 filtered_data,
486 {"before": current_data["results"][0], "after": ""},
487 )
488 return False, False, filtered_data, {}
489
490 return True, False, {"reason: ": "Must provide state parameter"}, {}
491 # pass post processed data to member operations
492 # no need to do underscore_to_hyphen since do_member_operation handles it by itself
493 data_copy = data.copy()
494 data_copy["system_ddns"] = filtered_data
495 fos.do_member_operation(
496 "system",
497 "ddns",
498 data_copy,
499 )
500
501 if state == "present" or state is True:
502 return fos.set(
503 "system", "ddns", data=converted_data, vdom=vdom, parameters=parameters
504 )
505
506 elif state == "absent":
507 return fos.delete(
508 "system",
509 "ddns",
510 mkey=converted_data["ddnsid"],
511 vdom=vdom,
512 parameters=parameters,
513 )
514 else:
515 fos._module.fail_json(msg="state must be present or absent!")
516
517
518 def is_successful_status(resp):
519 return (
520 "status" in resp
521 and resp["status"] == "success"
522 or "http_status" in resp
523 and resp["http_status"] == 200
524 or "http_method" in resp
525 and resp["http_method"] == "DELETE"
526 and resp["http_status"] == 404
527 )
528
529
530 def fortios_system(data, fos, check_mode):
531
532 if data["system_ddns"]:
533 resp = system_ddns(data, fos, check_mode)
534 else:
535 fos._module.fail_json(msg="missing task body: %s" % ("system_ddns"))
536 if isinstance(resp, tuple) and len(resp) == 4:
537 return resp
538 return (
539 not is_successful_status(resp),
540 is_successful_status(resp)
541 and (resp["revision_changed"] if "revision_changed" in resp else True),
542 resp,
543 {},
544 )
545
546
547 versioned_schema = {
548 "type": "list",
549 "elements": "dict",
550 "children": {
551 "ddnsid": {"v_range": [["v6.0.0", ""]], "type": "integer", "required": True},
552 "ddns_server": {
553 "v_range": [["v6.0.0", ""]],
554 "type": "string",
555 "options": [
556 {"value": "dyndns.org"},
557 {"value": "dyns.net"},
558 {"value": "tzo.com"},
559 {"value": "vavic.com"},
560 {"value": "dipdns.net"},
561 {"value": "now.net.cn"},
562 {"value": "dhs.org"},
563 {"value": "easydns.com"},
564 {"value": "genericDDNS"},
565 {"value": "FortiGuardDDNS"},
566 {"value": "noip.com"},
567 ],
568 },
569 "addr_type": {
570 "v_range": [["v7.0.0", ""]],
571 "type": "string",
572 "options": [{"value": "ipv4"}, {"value": "ipv6"}],
573 },
574 "server_type": {
575 "v_range": [["v7.0.0", ""]],
576 "type": "string",
577 "options": [{"value": "ipv4"}, {"value": "ipv6"}],
578 },
579 "ddns_server_addr": {
580 "type": "list",
581 "elements": "dict",
582 "children": {
583 "addr": {
584 "v_range": [["v7.0.0", ""]],
585 "type": "string",
586 "required": True,
587 }
588 },
589 "v_range": [["v7.0.0", ""]],
590 },
591 "ddns_zone": {"v_range": [["v6.0.0", ""]], "type": "string"},
592 "ddns_ttl": {"v_range": [["v6.0.0", ""]], "type": "integer"},
593 "ddns_auth": {
594 "v_range": [["v6.0.0", ""]],
595 "type": "string",
596 "options": [{"value": "disable"}, {"value": "tsig"}],
597 },
598 "ddns_keyname": {"v_range": [["v6.0.0", ""]], "type": "string"},
599 "ddns_key": {"v_range": [["v6.0.0", ""]], "type": "string"},
600 "ddns_domain": {"v_range": [["v6.0.0", ""]], "type": "string"},
601 "ddns_username": {"v_range": [["v6.0.0", ""]], "type": "string"},
602 "ddns_sn": {"v_range": [["v6.0.0", ""]], "type": "string"},
603 "ddns_password": {"v_range": [["v6.0.0", ""]], "type": "string"},
604 "use_public_ip": {
605 "v_range": [["v6.0.0", ""]],
606 "type": "string",
607 "options": [{"value": "disable"}, {"value": "enable"}],
608 },
609 "update_interval": {"v_range": [["v6.0.0", ""]], "type": "integer"},
610 "clear_text": {
611 "v_range": [["v6.0.0", ""]],
612 "type": "string",
613 "options": [{"value": "disable"}, {"value": "enable"}],
614 },
615 "ssl_certificate": {"v_range": [["v6.0.0", ""]], "type": "string"},
616 "monitor_interface": {
617 "type": "list",
618 "elements": "dict",
619 "children": {
620 "interface_name": {
621 "v_range": [["v6.0.0", ""]],
622 "type": "string",
623 "required": True,
624 }
625 },
626 "v_range": [["v6.0.0", ""]],
627 },
628 "bound_ip": {
629 "v_range": [["v6.0.0", "v7.0.5"], ["v7.2.0", "v7.2.0"]],
630 "type": "string",
631 },
632 "ddns_server_ip": {"v_range": [["v6.0.0", "v6.4.4"]], "type": "string"},
633 },
634 "v_range": [["v6.0.0", ""]],
635 }
636
637
638 def main():
639 module_spec = schema_to_module_spec(versioned_schema)
640 mkeyname = "ddnsid"
641 fields = {
642 "access_token": {"required": False, "type": "str", "no_log": True},
643 "enable_log": {"required": False, "type": "bool", "default": False},
644 "vdom": {"required": False, "type": "str", "default": "root"},
645 "member_path": {"required": False, "type": "str"},
646 "member_state": {
647 "type": "str",
648 "required": False,
649 "choices": ["present", "absent"],
650 },
651 "state": {"required": True, "type": "str", "choices": ["present", "absent"]},
652 "system_ddns": {
653 "required": False,
654 "type": "dict",
655 "default": None,
656 "options": {},
657 },
658 }
659 for attribute_name in module_spec["options"]:
660 fields["system_ddns"]["options"][attribute_name] = module_spec["options"][
661 attribute_name
662 ]
663 if mkeyname and mkeyname == attribute_name:
664 fields["system_ddns"]["options"][attribute_name]["required"] = True
665
666 module = AnsibleModule(argument_spec=fields, supports_check_mode=True)
667 check_legacy_fortiosapi(module)
668
669 is_error = False
670 has_changed = False
671 result = None
672 diff = None
673
674 versions_check_result = None
675 if module._socket_path:
676 connection = Connection(module._socket_path)
677 if "access_token" in module.params:
678 connection.set_custom_option("access_token", module.params["access_token"])
679
680 if "enable_log" in module.params:
681 connection.set_custom_option("enable_log", module.params["enable_log"])
682 else:
683 connection.set_custom_option("enable_log", False)
684 fos = FortiOSHandler(connection, module, mkeyname, admin_passwd_header=False)
685 versions_check_result = check_schema_versioning(
686 fos, versioned_schema, "system_ddns"
687 )
688
689 is_error, has_changed, result, diff = fortios_system(
690 module.params, fos, module.check_mode
691 )
692
693 else:
694 module.fail_json(**FAIL_SOCKET_MSG)
695
696 if versions_check_result and versions_check_result["matched"] is False:
697 module.warn(
698 "Ansible has detected version mismatch between FortOS system and your playbook, see more details by specifying option -vvv"
699 )
700
701 if not is_error:
702 if versions_check_result and versions_check_result["matched"] is False:
703 module.exit_json(
704 changed=has_changed,
705 version_check_warning=versions_check_result,
706 meta=result,
707 diff=diff,
708 )
709 else:
710 module.exit_json(changed=has_changed, meta=result, diff=diff)
711 else:
712 if versions_check_result and versions_check_result["matched"] is False:
713 module.fail_json(
714 msg="Error in repo",
715 version_check_warning=versions_check_result,
716 meta=result,
717 )
718 else:
719 module.fail_json(msg="Error in repo", meta=result)
720
721
722 if __name__ == "__main__":
723 main()