Debian Codegraph @

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