Debian Codegraph @

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