Debian Codegraph @

ansible_collections/fortinet/fortios/plugins/modules/fortios_user_device.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_device
23 short_description: Configure devices 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 device 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_device:
88 description:
89 - Configure devices.
90 default: null
91 type: dict
92 suboptions:
93 alias:
94 description:
95 - Device alias.
96 required: true
97 type: str
98 avatar:
99 description:
100 - Image file for avatar (maximum 4K base64 encoded).
101 type: str
102 category:
103 description:
104 - Family.
105 type: str
106 choices:
107 - 'none'
108 - 'amazon-device'
109 - 'android-device'
110 - 'blackberry-device'
111 - 'fortinet-device'
112 - 'ios-device'
113 - 'windows-device'
114 comment:
115 description:
116 - Comment.
117 type: str
118 mac:
119 description:
120 - Device MAC address.
121 type: str
122 master_device:
123 description:
124 - Master device (optional). Source user.device.alias.
125 type: str
126 tagging:
127 description:
128 - Config object tagging.
129 type: list
130 elements: dict
131 suboptions:
132 category:
133 description:
134 - Tag category. Source system.object-tagging.category.
135 type: str
136 name:
137 description:
138 - Tagging entry name.
139 required: true
140 type: str
141 tags:
142 description:
143 - Tags.
144 type: list
145 elements: dict
146 suboptions:
147 name:
148 description:
149 - Tag name. Source system.object-tagging.tags.name.
150 required: true
151 type: str
152 type:
153 description:
154 - Type.
155 type: str
156 choices:
157 - 'unknown'
158 - 'android-phone'
159 - 'android-tablet'
160 - 'blackberry-phone'
161 - 'blackberry-playbook'
162 - 'forticam'
163 - 'fortifone'
164 - 'fortinet-device'
165 - 'gaming-console'
166 - 'ip-phone'
167 - 'ipad'
168 - 'iphone'
169 - 'linux-pc'
170 - 'mac'
171 - 'media-streaming'
172 - 'printer'
173 - 'router-nat-device'
174 - 'windows-pc'
175 - 'windows-phone'
176 - 'windows-tablet'
177 - 'other-network-device'
178 user:
179 description:
180 - User name.
181 type: str
182 """
183
184 EXAMPLES = """
185 - name: Configure devices.
186 fortinet.fortios.fortios_user_device:
187 vdom: "{{ vdom }}"
188 state: "present"
189 access_token: "<your_own_value>"
190 user_device:
191 alias: "<your_own_value>"
192 avatar: "<your_own_value>"
193 category: "none"
194 comment: "Comment."
195 mac: "<your_own_value>"
196 master_device: "<your_own_value> (source user.device.alias)"
197 tagging:
198 -
199 category: "<your_own_value> (source system.object-tagging.category)"
200 name: "default_name_11"
201 tags:
202 -
203 name: "default_name_13 (source system.object-tagging.tags.name)"
204 type: "unknown"
205 user: "<your_own_value>"
206 """
207
208 RETURN = """
209 build:
210 description: Build number of the fortigate image
211 returned: always
212 type: str
213 sample: '1547'
214 http_method:
215 description: Last method used to provision the content into FortiGate
216 returned: always
217 type: str
218 sample: 'PUT'
219 http_status:
220 description: Last result given by FortiGate on last operation applied
221 returned: always
222 type: str
223 sample: "200"
224 mkey:
225 description: Master key (id) used in the last call to FortiGate
226 returned: success
227 type: str
228 sample: "id"
229 name:
230 description: Name of the table used to fulfill the request
231 returned: always
232 type: str
233 sample: "urlfilter"
234 path:
235 description: Path of the table used to fulfill the request
236 returned: always
237 type: str
238 sample: "webfilter"
239 revision:
240 description: Internal revision number
241 returned: always
242 type: str
243 sample: "17.0.2.10658"
244 serial:
245 description: Serial number of the unit
246 returned: always
247 type: str
248 sample: "FGVMEVYYQT3AB5352"
249 status:
250 description: Indication of the operation's result
251 returned: always
252 type: str
253 sample: "success"
254 vdom:
255 description: Virtual domain used
256 returned: always
257 type: str
258 sample: "root"
259 version:
260 description: Version of the FortiGate
261 returned: always
262 type: str
263 sample: "v5.6.3"
264 """
265 from ansible.module_utils.basic import AnsibleModule
266 from ansible.module_utils.connection import Connection
267 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
268 FortiOSHandler,
269 )
270 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
271 check_legacy_fortiosapi,
272 )
273 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
274 schema_to_module_spec,
275 )
276 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
277 check_schema_versioning,
278 )
279 from ansible_collections.fortinet.fortios.plugins.module_utils.fortimanager.common import (
280 FAIL_SOCKET_MSG,
281 )
282 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.data_post_processor import (
283 remove_invalid_fields,
284 )
285 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
286 is_same_comparison,
287 )
288 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
289 serialize,
290 )
291 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
292 find_current_values,
293 )
294 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
295 unify_data_format,
296 )
297
298
299 def filter_user_device_data(json):
300 option_list = [
301 "alias",
302 "avatar",
303 "category",
304 "comment",
305 "mac",
306 "master_device",
307 "tagging",
308 "type",
309 "user",
310 ]
311
312 json = remove_invalid_fields(json)
313 dictionary = {}
314
315 for attribute in option_list:
316 if attribute in json and json[attribute] is not None:
317 dictionary[attribute] = json[attribute]
318
319 return dictionary
320
321
322 def underscore_to_hyphen(data):
323 new_data = None
324 if isinstance(data, list):
325 new_data = []
326 for i, elem in enumerate(data):
327 new_data.append(underscore_to_hyphen(elem))
328 elif isinstance(data, dict):
329 new_data = {}
330 for k, v in data.items():
331 new_data[k.replace("_", "-")] = underscore_to_hyphen(v)
332 else:
333 return data
334 return new_data
335
336
337 def user_device(data, fos, check_mode=False):
338
339 state = None
340 vdom = data["vdom"]
341 parameters = None
342 state = data.get("state", None)
343 user_device_data = data["user_device"]
344
345 filtered_data = filter_user_device_data(user_device_data)
346 converted_data = underscore_to_hyphen(filtered_data)
347
348 # check_mode starts from here
349 if check_mode:
350 diff = {
351 "before": "",
352 "after": filtered_data,
353 }
354 mkeyname = fos.get_mkeyname(None, None)
355 mkey = fos.get_mkey("user", "device", filtered_data, vdom=vdom)
356 current_data = fos.get(
357 "user", "device", vdom=vdom, mkey=mkey, parameters=parameters
358 )
359 is_existed = (
360 current_data
361 and current_data.get("http_status") == 200
362 and (
363 mkeyname
364 and isinstance(current_data.get("results"), list)
365 and len(current_data["results"]) > 0
366 or not mkeyname
367 and current_data["results"] # global object response
368 )
369 )
370
371 # 2. if it exists and the state is 'present' then compare current settings with desired
372 if state == "present" or state is True or state is None:
373 # for non global modules, mkeyname must exist and it's a new module when mkey is None
374 if mkeyname is not None and mkey is None:
375 return False, True, filtered_data, diff
376
377 # if mkey exists then compare each other
378 # record exits and they're matched or not
379 copied_filtered_data = filtered_data.copy()
380 copied_filtered_data.pop(mkeyname, None)
381 unified_filtered_data = unify_data_format(copied_filtered_data)
382
383 current_data_results = current_data.get("results", {})
384 current_config = (
385 current_data_results[0]
386 if mkeyname
387 and isinstance(current_data_results, list)
388 and len(current_data_results) > 0
389 else current_data_results
390 )
391 if is_existed:
392 unified_current_values = find_current_values(
393 unified_filtered_data,
394 unify_data_format(current_config),
395 )
396
397 is_same = is_same_comparison(
398 serialize(unified_current_values), serialize(unified_filtered_data)
399 )
400
401 return (
402 False,
403 not is_same,
404 filtered_data,
405 {"before": unified_current_values, "after": unified_filtered_data},
406 )
407
408 # record does not exist
409 return False, True, filtered_data, diff
410
411 if state == "absent":
412 if mkey is None:
413 return (
414 False,
415 False,
416 filtered_data,
417 {"before": current_data["results"][0], "after": ""},
418 )
419
420 if is_existed:
421 return (
422 False,
423 True,
424 filtered_data,
425 {"before": current_data["results"][0], "after": ""},
426 )
427 return False, False, filtered_data, {}
428
429 return True, False, {"reason: ": "Must provide state parameter"}, {}
430 # pass post processed data to member operations
431 # no need to do underscore_to_hyphen since do_member_operation handles it by itself
432 data_copy = data.copy()
433 data_copy["user_device"] = filtered_data
434 fos.do_member_operation(
435 "user",
436 "device",
437 data_copy,
438 )
439
440 if state == "present" or state is True:
441 return fos.set(
442 "user", "device", data=converted_data, vdom=vdom, parameters=parameters
443 )
444
445 elif state == "absent":
446 return fos.delete(
447 "user",
448 "device",
449 mkey=converted_data["alias"],
450 vdom=vdom,
451 parameters=parameters,
452 )
453 else:
454 fos._module.fail_json(msg="state must be present or absent!")
455
456
457 def is_successful_status(resp):
458 return (
459 "status" in resp
460 and resp["status"] == "success"
461 or "http_status" in resp
462 and resp["http_status"] == 200
463 or "http_method" in resp
464 and resp["http_method"] == "DELETE"
465 and resp["http_status"] == 404
466 )
467
468
469 def fortios_user(data, fos, check_mode):
470
471 if data["user_device"]:
472 resp = user_device(data, fos, check_mode)
473 else:
474 fos._module.fail_json(msg="missing task body: %s" % ("user_device"))
475 if isinstance(resp, tuple) and len(resp) == 4:
476 return resp
477 return (
478 not is_successful_status(resp),
479 is_successful_status(resp)
480 and (resp["revision_changed"] if "revision_changed" in resp else True),
481 resp,
482 {},
483 )
484
485
486 versioned_schema = {
487 "type": "list",
488 "elements": "dict",
489 "children": {
490 "alias": {
491 "v_range": [["v6.0.0", "v6.0.11"], ["v6.2.3", "v6.2.3"]],
492 "type": "string",
493 "required": True,
494 },
495 "mac": {
496 "v_range": [["v6.0.0", "v6.0.11"], ["v6.2.3", "v6.2.3"]],
497 "type": "string",
498 },
499 "user": {
500 "v_range": [["v6.0.0", "v6.0.11"], ["v6.2.3", "v6.2.3"]],
501 "type": "string",
502 },
503 "master_device": {
504 "v_range": [["v6.0.0", "v6.0.11"], ["v6.2.3", "v6.2.3"]],
505 "type": "string",
506 },
507 "comment": {
508 "v_range": [["v6.0.0", "v6.0.11"], ["v6.2.3", "v6.2.3"]],
509 "type": "string",
510 },
511 "avatar": {
512 "v_range": [["v6.0.0", "v6.0.11"], ["v6.2.3", "v6.2.3"]],
513 "type": "string",
514 },
515 "tagging": {
516 "type": "list",
517 "elements": "dict",
518 "children": {
519 "name": {
520 "v_range": [["v6.0.0", "v6.0.11"], ["v6.2.3", "v6.2.3"]],
521 "type": "string",
522 "required": True,
523 },
524 "category": {
525 "v_range": [["v6.0.0", "v6.0.11"], ["v6.2.3", "v6.2.3"]],
526 "type": "string",
527 },
528 "tags": {
529 "type": "list",
530 "elements": "dict",
531 "children": {
532 "name": {
533 "v_range": [["v6.0.0", "v6.0.11"], ["v6.2.3", "v6.2.3"]],
534 "type": "string",
535 "required": True,
536 }
537 },
538 "v_range": [["v6.0.0", "v6.0.11"], ["v6.2.3", "v6.2.3"]],
539 },
540 },
541 "v_range": [["v6.0.0", "v6.0.11"], ["v6.2.3", "v6.2.3"]],
542 },
543 "type": {
544 "v_range": [["v6.0.0", "v6.0.11"], ["v6.2.3", "v6.2.3"]],
545 "type": "string",
546 "options": [
547 {"value": "unknown", "v_range": [["v6.0.0", "v6.0.11"]]},
548 {"value": "android-phone", "v_range": [["v6.0.0", "v6.0.11"]]},
549 {"value": "android-tablet", "v_range": [["v6.0.0", "v6.0.11"]]},
550 {"value": "blackberry-phone", "v_range": [["v6.0.0", "v6.0.11"]]},
551 {"value": "blackberry-playbook", "v_range": [["v6.0.0", "v6.0.11"]]},
552 {"value": "forticam", "v_range": [["v6.0.0", "v6.0.11"]]},
553 {"value": "fortifone", "v_range": [["v6.0.0", "v6.0.11"]]},
554 {"value": "fortinet-device", "v_range": [["v6.0.0", "v6.0.11"]]},
555 {"value": "gaming-console", "v_range": [["v6.0.0", "v6.0.11"]]},
556 {"value": "ip-phone", "v_range": [["v6.0.0", "v6.0.11"]]},
557 {"value": "ipad", "v_range": [["v6.0.0", "v6.0.11"]]},
558 {"value": "iphone", "v_range": [["v6.0.0", "v6.0.11"]]},
559 {"value": "linux-pc", "v_range": [["v6.0.0", "v6.0.11"]]},
560 {"value": "mac", "v_range": [["v6.0.0", "v6.0.11"]]},
561 {"value": "media-streaming", "v_range": [["v6.0.0", "v6.0.11"]]},
562 {"value": "printer", "v_range": [["v6.0.0", "v6.0.11"]]},
563 {"value": "router-nat-device", "v_range": [["v6.0.0", "v6.0.11"]]},
564 {"value": "windows-pc", "v_range": [["v6.0.0", "v6.0.11"]]},
565 {"value": "windows-phone", "v_range": [["v6.0.0", "v6.0.11"]]},
566 {"value": "windows-tablet", "v_range": [["v6.0.0", "v6.0.11"]]},
567 {"value": "other-network-device", "v_range": [["v6.0.0", "v6.0.11"]]},
568 ],
569 },
570 "category": {
571 "v_range": [["v6.0.0", "v6.0.11"], ["v6.2.3", "v6.2.3"]],
572 "type": "string",
573 "options": [
574 {"value": "none", "v_range": [["v6.0.0", "v6.0.11"]]},
575 {"value": "amazon-device", "v_range": [["v6.0.0", "v6.0.11"]]},
576 {"value": "android-device", "v_range": [["v6.0.0", "v6.0.11"]]},
577 {"value": "blackberry-device", "v_range": [["v6.0.0", "v6.0.11"]]},
578 {"value": "fortinet-device", "v_range": [["v6.0.0", "v6.0.11"]]},
579 {"value": "ios-device", "v_range": [["v6.0.0", "v6.0.11"]]},
580 {"value": "windows-device", "v_range": [["v6.0.0", "v6.0.11"]]},
581 ],
582 },
583 },
584 "v_range": [["v6.0.0", "v6.0.11"], ["v6.2.3", "v6.2.3"]],
585 }
586
587
588 def main():
589 module_spec = schema_to_module_spec(versioned_schema)
590 mkeyname = "alias"
591 fields = {
592 "access_token": {"required": False, "type": "str", "no_log": True},
593 "enable_log": {"required": False, "type": "bool", "default": False},
594 "vdom": {"required": False, "type": "str", "default": "root"},
595 "member_path": {"required": False, "type": "str"},
596 "member_state": {
597 "type": "str",
598 "required": False,
599 "choices": ["present", "absent"],
600 },
601 "state": {"required": True, "type": "str", "choices": ["present", "absent"]},
602 "user_device": {
603 "required": False,
604 "type": "dict",
605 "default": None,
606 "options": {},
607 },
608 }
609 for attribute_name in module_spec["options"]:
610 fields["user_device"]["options"][attribute_name] = module_spec["options"][
611 attribute_name
612 ]
613 if mkeyname and mkeyname == attribute_name:
614 fields["user_device"]["options"][attribute_name]["required"] = True
615
616 module = AnsibleModule(argument_spec=fields, supports_check_mode=True)
617 check_legacy_fortiosapi(module)
618
619 is_error = False
620 has_changed = False
621 result = None
622 diff = None
623
624 versions_check_result = None
625 if module._socket_path:
626 connection = Connection(module._socket_path)
627 if "access_token" in module.params:
628 connection.set_custom_option("access_token", module.params["access_token"])
629
630 if "enable_log" in module.params:
631 connection.set_custom_option("enable_log", module.params["enable_log"])
632 else:
633 connection.set_custom_option("enable_log", False)
634 fos = FortiOSHandler(connection, module, mkeyname, admin_passwd_header=False)
635 versions_check_result = check_schema_versioning(
636 fos, versioned_schema, "user_device"
637 )
638
639 is_error, has_changed, result, diff = fortios_user(
640 module.params, fos, module.check_mode
641 )
642
643 else:
644 module.fail_json(**FAIL_SOCKET_MSG)
645
646 if versions_check_result and versions_check_result["matched"] is False:
647 module.warn(
648 "Ansible has detected version mismatch between FortOS system and your playbook, see more details by specifying option -vvv"
649 )
650
651 if not is_error:
652 if versions_check_result and versions_check_result["matched"] is False:
653 module.exit_json(
654 changed=has_changed,
655 version_check_warning=versions_check_result,
656 meta=result,
657 diff=diff,
658 )
659 else:
660 module.exit_json(changed=has_changed, meta=result, diff=diff)
661 else:
662 if versions_check_result and versions_check_result["matched"] is False:
663 module.fail_json(
664 msg="Error in repo",
665 version_check_warning=versions_check_result,
666 meta=result,
667 )
668 else:
669 module.fail_json(msg="Error in repo", meta=result)
670
671
672 if __name__ == "__main__":
673 main()