Debian Codegraph @

ansible_collections/dellemc/openmanage/plugins/modules/ome_active_directory.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 from __future__ import (absolute_import, division, print_function)
13
14 __metaclass__ = type
15
16 DOCUMENTATION = """
17 ---
18 module: ome_active_directory
19 short_description: Configure Active Directory groups to be used with Directory Services
20 description: "This module allows to add, modify, and delete OpenManage Enterprise connection with Active Directory
21 Service."
22 version_added: "4.0.0"
23 author:
24 - Jagadeesh N V(@jagadeeshnv)
25 - Bhavneet Sharma (@Bhavneet-Sharma)
26 extends_documentation_fragment:
27 - dellemc.openmanage.ome_auth_options
28 options:
29 domain_server:
30 type: list
31 elements: str
32 description:
33 - Enter the domain name or FQDN or IP address of the domain controller.
34 - If I(domain_controller_lookup) is C(DNS), enter the domain name to query DNS for the domain controllers.
35 - "If I(domain_controller_lookup) is C(MANUAL), enter the FQDN or the IP address of the domain controller.
36 The maximum number of Active Directory servers that can be added is three."
37 domain_controller_lookup:
38 type: str
39 description:
40 - Select the Domain Controller Lookup method.
41 choices:
42 - DNS
43 - MANUAL
44 default: DNS
45 domain_controller_port:
46 type: int
47 description:
48 - Domain controller port.
49 - By default, Global Catalog Address port number 3269 is populated.
50 - For the Domain Controller Access, enter 636 as the port number.
51 - C(NOTE), Only LDAPS ports are supported.
52 default: 3269
53 group_domain:
54 type: str
55 description:
56 - Provide the group domain in the format C(example.com) or C(ou=org, dc=example, dc=com).
57 id:
58 type: int
59 description:
60 - Provide the ID of the existing Active Directory service connection.
61 - This is applicable for modification and deletion.
62 - This is mutually exclusive with I(name).
63 name:
64 type: str
65 description:
66 - Provide a name for the Active Directory connection.
67 - This is applicable for creation and deletion.
68 - This is mutually exclusive with I(name).
69 network_timeout:
70 type: int
71 description:
72 - Enter the network timeout duration in seconds.
73 - The supported timeout duration range is 15 to 300 seconds.
74 default: 120
75 search_timeout:
76 type: int
77 description:
78 - Enter the search timeout duration in seconds.
79 - The supported timeout duration range is 15 to 300 seconds.
80 default: 120
81 state:
82 type: str
83 description:
84 - C(present) allows to create or modify an Active Directory service.
85 - C(absent) allows to delete a Active Directory service.
86 choices:
87 - present
88 - absent
89 default: present
90 test_connection:
91 type: bool
92 description:
93 - Enables testing the connection to the domain controller.
94 - The connection to the domain controller is tested with the provided Active Directory service details.
95 - If test fails, module will error out.
96 - If C(true), I(domain_username) and I(domain_password) has to be provided.
97 default: false
98 domain_password:
99 type: str
100 description:
101 - Provide the domain password.
102 - This is applicable when I(test_connection) is C(true).
103 domain_username:
104 type: str
105 description:
106 - Provide the domain username either in the UPN (username@domain) or NetBIOS (domain\\\\username) format.
107 - This is applicable when I(test_connection) is C(true).
108 validate_certificate:
109 type: bool
110 description:
111 - Enables validation of SSL certificate of the domain controller.
112 - The module will always report change when this is C(true).
113 default: false
114 certificate_file:
115 type: path
116 description:
117 - Provide the full path of the SSL certificate.
118 - The certificate should be a Root CA Certificate encoded in Base64 format.
119 - This is applicable when I(validate_certificate) is C(true).
120 requirements:
121 - "python >= 3.9.6"
122 notes:
123 - The module will always report change when I(validate_certificate) is C(true).
124 - Run this module from a system that has direct access to OpenManage Enterprise.
125 - This module supports C(check_mode).
126 """
127
128 EXAMPLES = """
129 ---
130 - name: Add Active Directory service using DNS lookup along with the test connection
131 dellemc.openmanage.ome_active_directory:
132 hostname: "192.168.0.1"
133 username: "username"
134 password: "password"
135 ca_path: "/path/to/ca_cert.pem"
136 name: my_ad1
137 domain_server:
138 - domainname.com
139 group_domain: domainname.com
140 test_connection: true
141 domain_username: user@domainname
142 domain_password: domain_password
143
144 - name: Add Active Directory service using IP address of the domain controller with certificate validation
145 dellemc.openmanage.ome_active_directory:
146 hostname: "192.168.0.1"
147 username: "username"
148 password: "password"
149 ca_path: "/path/to/ca_cert.pem"
150 name: my_ad2
151 domain_controller_lookup: MANUAL
152 domain_server:
153 - 192.68.20.181
154 group_domain: domainname.com
155 validate_certificate: true
156 certificate_file: "/path/to/certificate/file.cer"
157
158 - name: Modify domain controller IP address, network_timeout and group_domain
159 dellemc.openmanage.ome_active_directory:
160 hostname: "192.168.0.1"
161 username: "username"
162 password: "password"
163 ca_path: "/path/to/ca_cert.pem"
164 name: my_ad2
165 domain_controller_lookup: MANUAL
166 domain_server:
167 - 192.68.20.189
168 group_domain: newdomain.in
169 network_timeout: 150
170
171 - name: Delete Active Directory service
172 dellemc.openmanage.ome_active_directory:
173 hostname: "192.168.0.1"
174 username: "username"
175 password: "password"
176 ca_path: "/path/to/ca_cert.pem"
177 name: my_ad2
178 state: absent
179
180 - name: Test connection to existing Active Directory service with certificate validation
181 dellemc.openmanage.ome_active_directory:
182 hostname: "192.168.0.1"
183 username: "username"
184 password: "password"
185 ca_path: "/path/to/ca_cert.pem"
186 name: my_ad2
187 test_connection: true
188 domain_username: user@domainname
189 domain_password: domain_password
190 validate_certificate: true
191 certificate_file: "/path/to/certificate/file.cer"
192 """
193
194 RETURN = """
195 ---
196 msg:
197 type: str
198 description: Overall status of the Active Directory operation.
199 returned: always
200 sample: "Successfully renamed the slot(s)."
201 active_directory:
202 type: dict
203 description: The Active Directory that was added, modified or deleted by this module.
204 returned: on change
205 sample: {
206 "Name": "ad_test",
207 "Id": 21789,
208 "ServerType": "MANUAL",
209 "ServerName": ["192.168.20.181"],
210 "DnsServer": [],
211 "GroupDomain": "dellemcdomain.com",
212 "NetworkTimeOut": 120,
213 "Password": null,
214 "SearchTimeOut": 120,
215 "ServerPort": 3269,
216 "CertificateValidation": false
217 }
218 error_info:
219 description: Details of the HTTP Error.
220 returned: on HTTP error
221 type: dict
222 sample: {
223 "error_info": {
224 "error": {
225 "@Message.ExtendedInfo": [
226 {
227 "Message": "Unable to connect to the LDAP or AD server because the entered credentials are invalid.",
228 "MessageArgs": [],
229 "MessageId": "CSEC5002",
230 "RelatedProperties": [],
231 "Resolution": "Make sure the server input configuration are valid and retry the operation.",
232 "Severity": "Critical"
233 }
234 ],
235 "code": "Base.1.0.GeneralError",
236 "message": "A general error has occurred. See ExtendedInfo for more information."
237 }
238 }
239 }
240 """
241
242 import json
243 import os
244 from ssl import SSLError
245 from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError
246 from ansible.module_utils.urls import ConnectionError
247 from ansible_collections.dellemc.openmanage.plugins.module_utils.ome import RestOME, OmeAnsibleModule
248 from ansible.module_utils.common.dict_transformations import recursive_diff
249
250 AD_URI = "AccountService/ExternalAccountProvider/ADAccountProvider"
251 TEST_CONNECTION = "AccountService/ExternalAccountProvider/Actions/ExternalAccountProvider.TestADConnection"
252 DELETE_AD = "AccountService/ExternalAccountProvider/Actions/ExternalAccountProvider.DeleteExternalAccountProvider"
253 NO_CHANGES_MSG = "No changes found to be applied."
254 CHANGES_FOUND = "Changes found to be applied."
255 MAX_AD_MSG = "Unable to add the account provider because the maximum number of configurations allowed for an" \
256 " Active Directory service is {0}."
257 CREATE_SUCCESS = "Successfully added the Active Directory service."
258 MODIFY_SUCCESS = "Successfully modified the Active Directory service."
259 DELETE_SUCCESS = "Successfully deleted the Active Directory service."
260 DOM_SERVER_MSG = "Specify the domain server. Domain server is required to create an Active Directory service."
261 GRP_DOM_MSG = "Specify the group domain. Group domain is required to create an Active Directory service."
262 CERT_INVALID = "The provided certificate file path is invalid or not readable."
263 DOMAIN_ALLOWED_COUNT = "Maximum entries allowed for {0} lookup type is {1}."
264 TEST_CONNECTION_SUCCESS = "Test Connection is successful. "
265 TEST_CONNECTION_FAIL = "Test Connection has failed. "
266 ERR_READ_FAIL = "Unable to retrieve the error details."
267 INVALID_ID = "The provided Active Directory ID is invalid."
268 TIMEOUT_RANGE = "The {0} value is not in the range of {1} to {2}."
269 MAX_AD = 2
270 MIN_TIMEOUT = 15
271 MAX_TIMEOUT = 300
272
273
274 def get_ad(module, rest_obj):
275 ad = {}
276 prm = module.params
277 resp = rest_obj.invoke_request('GET', AD_URI)
278 ad_list = resp.json_data.get('value')
279 ad_cnt = len(ad_list)
280 ky = 'Name'
281 vl = 'name'
282 if prm.get('id'):
283 ky = 'Id'
284 vl = 'id'
285 for adx in ad_list:
286 if str(adx.get(ky)).lower() == str(prm.get(vl)).lower():
287 ad = adx
288 break
289 return ad, ad_cnt
290
291
292 def test_http_error_fail(module, err):
293 try:
294 error_info = json.load(err)
295 err_list = error_info.get('error', {}).get('@Message.ExtendedInfo',
296 [ERR_READ_FAIL])
297 if err_list:
298 err_rsn = err_list[0].get("Message")
299 except Exception:
300 err_rsn = ERR_READ_FAIL
301 module.exit_json(msg="{0}{1}".format(TEST_CONNECTION_FAIL, err_rsn),
302 error_info=error_info, failed=True)
303
304
305 def test_connection(module, rest_obj, create_payload):
306 try:
307 create_payload['UserName'] = module.params.get('domain_username')
308 create_payload['Password'] = module.params.get('domain_password')
309 rest_obj.invoke_request('POST', TEST_CONNECTION, data=create_payload,
310 api_timeout=create_payload['NetworkTimeOut'])
311 create_payload.pop('UserName', None)
312 create_payload.pop('Password', None)
313 except HTTPError as err:
314 test_http_error_fail(module, err)
315 except SSLError as err:
316 module.exit_json(msg="{0}{1}".format(TEST_CONNECTION_FAIL, str(err)),
317 failed=True)
318 except Exception as err:
319 module.exit_json(msg="{0}{1}".format(TEST_CONNECTION_FAIL, str(err)),
320 failed=True)
321
322
323 def make_payload(prm):
324 dc_type = {'DNS': 'DnsServer', 'MANUAL': 'ServerName'}
325 tmplt_ad = {'name': 'Name', 'domain_controller_port': 'ServerPort', 'domain_controller_lookup': 'ServerType',
326 'domain_server': dc_type[prm.get('domain_controller_lookup')], 'group_domain': 'GroupDomain',
327 'network_timeout': 'NetworkTimeOut', 'search_timeout': 'SearchTimeOut',
328 'validate_certificate': 'CertificateValidation'}
329 payload = dict([(v, prm.get(k)) for k, v in tmplt_ad.items() if prm.get(k) is not None])
330 return payload
331
332
333 def validate_n_testconnection(module, rest_obj, payload):
334 dc_cnt = {'DNS': 1, 'MANUAL': 3}
335 dc_type = {'DNS': 'DnsServer', 'MANUAL': 'ServerName'}
336 dc_lookup = payload.get('ServerType')
337 if len(payload.get(dc_type[dc_lookup])) > dc_cnt[dc_lookup]:
338 module.exit_json(msg=DOMAIN_ALLOWED_COUNT.format(
339 dc_lookup, dc_cnt[dc_lookup]), failed=True)
340 t_list = ['NetworkTimeOut', 'SearchTimeOut']
341 for tx in t_list:
342 if payload.get(tx) not in range(MIN_TIMEOUT, MAX_TIMEOUT + 1):
343 module.exit_json(msg=TIMEOUT_RANGE.format(
344 tx, MIN_TIMEOUT, MAX_TIMEOUT), failed=True)
345 payload['CertificateFile'] = ""
346 if payload.get('CertificateValidation'):
347 cert_path = module.params.get('certificate_file')
348 if os.path.exists(cert_path):
349 with open(cert_path, 'r') as certfile:
350 cert_data = certfile.read()
351 payload['CertificateFile'] = cert_data
352 else:
353 module.exit_json(msg=CERT_INVALID, failed=True)
354 msg = ""
355 if module.params.get('test_connection'):
356 test_connection(module, rest_obj, payload)
357 msg = TEST_CONNECTION_SUCCESS
358 return msg
359
360
361 def create_ad(module, rest_obj):
362 prm = module.params
363 if not prm.get('domain_server'):
364 module.exit_json(msg=DOM_SERVER_MSG, failed=True)
365 if not prm.get('group_domain'):
366 module.exit_json(msg=GRP_DOM_MSG, failed=True)
367 create_payload = make_payload(prm)
368 msg = validate_n_testconnection(module, rest_obj, create_payload)
369 if module.check_mode:
370 module.exit_json(msg="{0}{1}".format(msg, CHANGES_FOUND), changed=True)
371 resp = rest_obj.invoke_request('POST', AD_URI, data=create_payload)
372 ad = resp.json_data
373 ad.pop('CertificateFile', "")
374 module.exit_json(msg="{0}{1}".format(msg, CREATE_SUCCESS), active_directory=ad, changed=True)
375
376
377 def modify_ad(module, rest_obj, ad):
378 prm = module.params
379 modify_payload = make_payload(prm)
380 ad = rest_obj.strip_substr_dict(ad)
381 if ad.get('ServerName'):
382 (ad.get('ServerName')).sort()
383 if modify_payload.get('ServerName'):
384 (modify_payload.get('ServerName')).sort()
385 diff = recursive_diff(modify_payload, ad)
386 is_change = False
387 if diff and diff[0]:
388 is_change = True
389 ad.update(modify_payload)
390 msg = validate_n_testconnection(module, rest_obj, ad)
391 if not is_change and not ad.get('CertificateValidation'):
392 module.exit_json(msg="{0}{1}".format(msg, NO_CHANGES_MSG), active_directory=ad)
393 if module.check_mode:
394 module.exit_json(msg="{0}{1}".format(msg, CHANGES_FOUND), changed=True)
395 resp = rest_obj.invoke_request('PUT', "{0}({1})".format(AD_URI, ad['Id']), data=ad)
396 ad = resp.json_data
397 ad.pop('CertificateFile', "")
398 module.exit_json(msg="{0}{1}".format(msg, MODIFY_SUCCESS), active_directory=ad, changed=True)
399
400
401 def delete_ad(module, rest_obj, ad):
402 ad = rest_obj.strip_substr_dict(ad)
403 if module.check_mode:
404 module.exit_json(msg=CHANGES_FOUND, active_directory=ad, changed=True)
405 rest_obj.invoke_request('POST', DELETE_AD, data={"AccountProviderIds": [int(ad['Id'])]})
406 module.exit_json(msg=DELETE_SUCCESS, active_directory=ad, changed=True)
407
408
409 def _go_for_create_modify(module, rest_obj, ad, ad_cnt):
410 if ad:
411 modify_ad(module, rest_obj, ad)
412 else:
413 if module.params.get('id'):
414 module.exit_json(msg=INVALID_ID, failed=True)
415 if ad_cnt < MAX_AD:
416 create_ad(module, rest_obj)
417 module.exit_json(msg=MAX_AD_MSG.format(MAX_AD), failed=True)
418
419
420 def main():
421 specs = {
422 "state": {"type": 'str', "choices": ["present", "absent"], "default": 'present'},
423 "name": {"type": 'str'},
424 "id": {"type": 'int'},
425 "domain_controller_lookup": {"type": 'str', "choices": ['MANUAL', 'DNS'], "default": 'DNS'},
426 "domain_server": {"type": 'list', "elements": 'str'},
427 "group_domain": {"type": 'str'},
428 "domain_controller_port": {"type": 'int', "default": 3269},
429 "network_timeout": {"type": 'int', "default": 120},
430 "search_timeout": {"type": 'int', "default": 120},
431 "validate_certificate": {"type": 'bool', "default": False},
432 "certificate_file": {"type": 'path'},
433 "test_connection": {"type": 'bool', "default": False},
434 "domain_username": {"type": 'str'},
435 "domain_password": {"type": 'str', "no_log": True}
436 }
437
438 module = OmeAnsibleModule(
439 argument_spec=specs,
440 required_one_of=[('name', 'id')],
441 required_if=[
442 ('test_connection', True, ('domain_username', 'domain_password',)),
443 ('validate_certificate', True, ('certificate_file',))],
444 mutually_exclusive=[('name', 'id')],
445 supports_check_mode=True)
446 try:
447 with RestOME(module.params, req_session=True) as rest_obj:
448 ad, ad_cnt = get_ad(module, rest_obj)
449 if module.params.get('state') == 'present':
450 _go_for_create_modify(module, rest_obj, ad, ad_cnt)
451 else:
452 if ad:
453 delete_ad(module, rest_obj, ad)
454 module.exit_json(msg=NO_CHANGES_MSG)
455 except HTTPError as err:
456 module.exit_json(msg=str(err), error_info=json.load(err), failed=True)
457 except URLError as err:
458 module.exit_json(msg=str(err), unreachable=True, failed=True)
459 except (
460 IOError, ValueError, TypeError, ConnectionError, AttributeError, IndexError, KeyError,
461 OSError) as err:
462 module.exit_json(msg=str(err), failed=True)
463
464
465 if __name__ == '__main__':
466 main()