Debian Codegraph @

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