Debian Codegraph @

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