Debian Codegraph @

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