Debian Codegraph @

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