Debian Codegraph @

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