Debian Codegraph @

ansible_collections/dellemc/openmanage/plugins/modules/ome_domain_user_groups.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 #
5 # Dell OpenManage Ansible Modules
6 # Version 9.12.4
7 # Copyright (C) 2021-2025 Dell Inc. or its subsidiaries. All Rights Reserved.
8
9 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
10 #
11
12
13 from __future__ import (absolute_import, division, print_function)
14 __metaclass__ = type
15
16 DOCUMENTATION = r"""
17 ---
18 module: ome_domain_user_groups
19 short_description: Create, modify, or delete an Active Directory/LDAP user group on
20 OpenManage Enterprise and OpenManage Enterprise Modular
21 version_added: "4.0.0"
22 description: This module allows to create, modify, or delete an Active Directory/LDAP user group on
23 OpenManage Enterprise and OpenManage Enterprise Modular.
24 extends_documentation_fragment:
25 - dellemc.openmanage.ome_auth_options
26 options:
27 state:
28 type: str
29 description:
30 - C(present) imports or modifies the Active Directory/LDAP user group.
31 - C(absent) deletes an existing Active Directory/LDAP user group.
32 choices: [present, absent]
33 default: present
34 group_name:
35 type: str
36 required: true
37 description:
38 - The desired Active Directory/LDAP user group name to be imported or removed.
39 - "Examples for user group name: Administrator or Account Operators or Access Control Assistance Operator."
40 - I(group_name) value is case insensitive.
41 role:
42 type: str
43 description:
44 - The desired roles and privilege for the imported Active Directory/LDAP user group.
45 - "OpenManage Enterprise Modular Roles: CHASSIS ADMINISTRATOR, COMPUTE MANAGER, STORAGE MANAGER,
46 FABRIC MANAGER, VIEWER."
47 - "OpenManage Enterprise Roles: ADMINISTRATOR, DEVICE MANAGER, VIEWER."
48 - I(role) value is case insensitive.
49 directory_name:
50 type: str
51 description:
52 - The directory name set while adding the Active Directory/LDAP.
53 - I(directory_name) is mutually exclusive with I(directory_id).
54 directory_type:
55 type: str
56 description:
57 - Type of the account.
58 choices: ['AD', 'LDAP']
59 default: 'AD'
60 directory_id:
61 type: int
62 description:
63 - The ID of the Active Directory/LDAP.
64 - I(directory_id) is mutually exclusive with I(directory_name).
65 domain_username:
66 type: str
67 description:
68 - Active Directory/LDAP domain username.
69 - "Example: username@domain or domain\\username."
70 domain_password:
71 type: str
72 description:
73 - Active Directory/LDAP domain password.
74 requirements:
75 - "python >= 3.9.6"
76 author:
77 - "Felix Stephen (@felixs88)"
78 - "Abhishek Sinha (@Abhishek-Dell)"
79 notes:
80 - This module supports C(check_mode) and idempotency.
81 - Run this module from a system that has direct access to OpenManage Enterprise
82 or OpenManage Enterprise Modular.
83 """
84
85 EXAMPLES = r"""
86 ---
87 - name: Create Active Directory user group
88 dellemc.openmanage.ome_domain_user_groups:
89 hostname: "192.168.0.1"
90 username: "username"
91 password: "password"
92 ca_path: "/path/to/ca_cert.pem"
93 state: present
94 group_name: account operators
95 directory_name: directory_name
96 role: administrator
97 domain_username: username@domain
98 domain_password: domain_password
99
100 - name: Update Active Directory user group
101 dellemc.openmanage.ome_domain_user_groups:
102 hostname: "192.168.0.1"
103 username: "username"
104 password: "password"
105 ca_path: "/path/to/ca_cert.pem"
106 state: present
107 group_name: account operators
108 role: viewer
109
110 - name: Delete active directory user group
111 dellemc.openmanage.ome_domain_user_groups:
112 hostname: "192.168.0.1"
113 username: "username"
114 password: "password"
115 ca_path: "/path/to/ca_cert.pem"
116 state: absent
117 group_name: administrators
118
119 - name: Import LDAP directory group.
120 dellemc.openmanage.ome_domain_user_groups:
121 hostname: "192.168.0.1"
122 username: "username"
123 password: "password"
124 ca_path: "/path/to/ca_cert.pem"
125 directory_type: LDAP
126 state: present
127 group_name: account operators
128 directory_name: directory_name
129 role: administrator
130 domain_username: username@domain
131 domain_password: domain_password
132
133 - name: Remove LDAP directory group.
134 dellemc.openmanage.ome_domain_user_groups:
135 hostname: "192.168.0.1"
136 username: "username"
137 password: "password"
138 ca_path: "/path/to/ca_cert.pem"
139 state: absent
140 group_name: account operators
141 """
142
143 RETURN = r"""
144 ---
145 msg:
146 type: str
147 description: Overall status of the Active Directory/LDAP user group operation.
148 returned: always
149 sample: Successfully imported the Active Directory/LDAP user group.
150 domain_user_status:
151 description: Details of the domain user operation, when I(state) is C(present).
152 returned: When I(state) is C(present).
153 type: dict
154 sample: {
155 "Description": null,
156 "DirectoryServiceId": 16097,
157 "Enabled": true,
158 "Id": "16617",
159 "IsBuiltin": false,
160 "IsVisible": true,
161 "Locked": false,
162 "Name": "Account Operators",
163 "ObjectGuid": "a491859c-031e-42a3-ae5e-0ab148ecf1d6",
164 "ObjectSid": null,
165 "Oem": null,
166 "Password": null,
167 "PlainTextPassword": null,
168 "RoleId": "16",
169 "UserName": "Account Operators",
170 "UserTypeId": 2
171 }
172 error_info:
173 description: Details of the HTTP Error.
174 returned: on HTTP error
175 type: dict
176 sample: {
177 "error": {
178 "code": "Base.1.0.GeneralError",
179 "message": "A general error has occurred. See ExtendedInfo for more information.",
180 "@Message.ExtendedInfo": [
181 {
182 "MessageId": "GEN1234",
183 "RelatedProperties": [],
184 "Message": "Unable to process the request because an error occurred.",
185 "MessageArgs": [],
186 "Severity": "Critical",
187 "Resolution": "Retry the operation. If the issue persists, contact your system administrator."
188 }
189 ]
190 }
191 }
192 """
193
194
195 import json
196 from ssl import SSLError
197 from ansible_collections.dellemc.openmanage.plugins.module_utils.ome import RestOME, OmeAnsibleModule
198 from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError
199 from ansible.module_utils.urls import ConnectionError, SSLValidationError
200 ROLE_URI = "AccountService/Roles"
201 ACCOUNT_URI = "AccountService/Accounts"
202 GET_AD_ACC = "AccountService/ExternalAccountProvider/ADAccountProvider"
203 GET_LDAP_ACC = "AccountService/ExternalAccountProvider/LDAPAccountProvider"
204 IMPORT_ACC_PRV = "AccountService/Actions/AccountService.ImportExternalAccountProvider"
205 SEARCH_GROUPS = "AccountService/ExternalAccountProvider/Actions/ExternalAccountProvider.SearchGroups"
206 NO_CHANGES_MSG = "No changes found to be applied."
207 CHANGES_FOUND = "Changes found to be applied."
208
209
210 def get_directory(module, rest_obj):
211 user_dir_name = module.params.get("directory_name")
212 user_dir_id = module.params.get("directory_id")
213 key = "name" if user_dir_name is not None else "id"
214 value = user_dir_name if user_dir_name is not None else user_dir_id
215 dir_id = None
216 if user_dir_name is None and user_dir_id is None:
217 module.exit_json(msg="missing required arguments: directory_name or directory_id", failed=True)
218 URI = GET_AD_ACC if module.params.get("directory_type") == "AD" else GET_LDAP_ACC
219 directory_resp = rest_obj.invoke_request("GET", URI)
220 for dire in directory_resp.json_data["value"]:
221 if user_dir_name is not None and dire["Name"] == user_dir_name:
222 dir_id = dire["Id"]
223 break
224 if user_dir_id is not None and dire["Id"] == user_dir_id:
225 dir_id = dire["Id"]
226 break
227 else:
228 module.exit_json(msg="Unable to complete the operation because the entered "
229 "directory {0} '{1}' does not exist.".format(key, value), failed=True)
230 return dir_id
231
232
233 def search_directory(module, rest_obj, dir_id):
234 group_name, obj_gui_id, common_name = module.params["group_name"], None, None
235 payload = {"DirectoryServerId": dir_id,
236 "Type": module.params["directory_type"],
237 "UserName": module.params["domain_username"],
238 "Password": module.params["domain_password"],
239 "CommonName": group_name}
240 try:
241 resp = rest_obj.invoke_request("POST", SEARCH_GROUPS, data=payload)
242 for key in resp.json_data:
243 if key["CommonName"].lower() == group_name.lower():
244 obj_gui_id = key["ObjectGuid"]
245 common_name = key["CommonName"]
246 break
247 else:
248 module.exit_json(msg="Unable to complete the operation because the entered "
249 "group name '{0}' does not exist.".format(group_name), failed=True)
250 except HTTPError as err:
251 error = json.load(err)
252 if error['error']['@Message.ExtendedInfo'][0]['MessageId'] in ["CGEN1004", "CSEC5022"]:
253 module.exit_json(msg="Unable to complete the operation because the entered "
254 "domain username or domain password are invalid.", failed=True)
255 return obj_gui_id, common_name
256
257
258 def directory_user(module, rest_obj):
259 user = get_directory_user(module, rest_obj)
260 new_role_id = get_role(module, rest_obj)
261 dir_id = get_directory(module, rest_obj)
262 domain_resp, local_msg, msg = None, '', ''
263 if user is None:
264 obj_gui_id, common_name = search_directory(module, rest_obj, dir_id)
265 if module.check_mode:
266 module.exit_json(msg=CHANGES_FOUND, changed=True)
267 payload = [
268 {"UserTypeId": 2, "DirectoryServiceId": dir_id, "Description": None,
269 "Name": common_name, "Password": "", "UserName": common_name, "RoleId": new_role_id, "Locked": False,
270 "IsBuiltin": False, "Enabled": True, "ObjectGuid": obj_gui_id}
271 ]
272 domain_resp = rest_obj.invoke_request("POST", IMPORT_ACC_PRV, data=payload)
273 local_msg, msg = 'import', 'imported'
274 else:
275 if (int(user["RoleId"]) == new_role_id):
276 user = rest_obj.strip_substr_dict(user)
277 module.exit_json(msg=NO_CHANGES_MSG, domain_user_status=user)
278 else:
279 payload = {"Id": str(user["Id"]), "UserTypeId": 2, "DirectoryServiceId": dir_id,
280 "UserName": user["UserName"], "RoleId": str(new_role_id), "Enabled": user["Enabled"]}
281 update_uri = "{0}('{1}')".format(ACCOUNT_URI, user['Id'])
282 if module.check_mode:
283 module.exit_json(msg=CHANGES_FOUND, changed=True, domain_user_status=payload)
284 domain_resp = rest_obj.invoke_request("PUT", update_uri, data=payload)
285 local_msg, msg = 'update', 'updated'
286 if domain_resp is None:
287 module.exit_json(msg="Unable to {0} the domain user group.".format(local_msg), failed=True)
288 return domain_resp.json_data, msg
289
290
291 def get_role(module, rest_obj):
292 role_name, role_id = module.params.get("role"), None
293 if role_name is None:
294 module.exit_json(msg="missing required arguments: role", failed=True)
295 resp_role = rest_obj.invoke_request("GET", ROLE_URI)
296 role_list = resp_role.json_data["value"]
297 for role in role_list:
298 if role["Name"] == role_name.upper().replace(" ", "_"):
299 role_id = int(role["Id"])
300 break
301 else:
302 module.exit_json(msg="Unable to complete the operation because the entered "
303 "role name '{0}' does not exist.".format(role_name), failed=True)
304 return role_id
305
306
307 def get_directory_user(module, rest_obj):
308 user_group_name, user = module.params.get("group_name"), None
309 state = module.params["state"]
310 if user_group_name is None:
311 module.exit_json(msg="missing required arguments: group_name", failed=True)
312 user_resp = rest_obj.invoke_request('GET', ACCOUNT_URI)
313 for usr in user_resp.json_data["value"]:
314 if usr["UserName"].lower() == user_group_name.lower() and usr["UserTypeId"] == 2:
315 user = usr
316 if module.check_mode and state == "absent":
317 user = rest_obj.strip_substr_dict(usr)
318 module.exit_json(msg=CHANGES_FOUND, changed=True, domain_user_status=user)
319 break
320 else:
321 if state == "absent":
322 module.exit_json(msg=NO_CHANGES_MSG)
323 return user
324
325
326 def delete_directory_user(rest_obj, user_id):
327 delete_uri, changed = "{0}('{1}')".format(ACCOUNT_URI, user_id), False
328 msg = "Invalid domain user group name provided."
329 resp = rest_obj.invoke_request('DELETE', delete_uri)
330 if resp.status_code == 204:
331 changed = True
332 msg = "Successfully deleted the domain user group."
333 return msg, changed
334
335
336 def main():
337 specs = {
338 "state": {"required": False, "type": 'str', "default": "present",
339 "choices": ['present', 'absent']},
340 "group_name": {"required": True, "type": 'str'},
341 "role": {"required": False, "type": 'str'},
342 "directory_name": {"required": False, "type": 'str'},
343 "directory_type": {"type": 'str', "choices": ['AD', 'LDAP'], "default": "AD"},
344 "directory_id": {"required": False, "type": 'int'},
345 "domain_username": {"required": False, "type": 'str'},
346 "domain_password": {"required": False, "type": 'str', "no_log": True},
347 }
348
349 module = OmeAnsibleModule(
350 argument_spec=specs,
351 mutually_exclusive=[['directory_name', 'directory_id'], ],
352 supports_check_mode=True)
353 try:
354 with RestOME(module.params, req_session=True) as rest_obj:
355 if module.params["state"] == "present":
356 resp, msg = directory_user(module, rest_obj)
357 if isinstance(resp, list):
358 resp = resp[0]
359 module.exit_json(
360 msg="Successfully {0} the domain user group.".format(msg),
361 domain_user_status=resp, changed=True
362 )
363 else:
364 user = get_directory_user(module, rest_obj)
365 msg, changed = delete_directory_user(rest_obj, int(user["Id"]))
366 user = rest_obj.strip_substr_dict(user)
367 module.exit_json(msg=msg, changed=changed, domain_user_status=user)
368 except HTTPError as err:
369 module.exit_json(msg=str(err), error_info=json.load(err), failed=True)
370 except URLError as err:
371 module.exit_json(msg=str(err), unreachable=True)
372 except (IOError, ValueError, TypeError, SSLError, ConnectionError, SSLValidationError, OSError) as err:
373 module.exit_json(msg=str(err), failed=True)
374
375
376 if __name__ == '__main__':
377 main()