Debian Codegraph @

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