Debian Codegraph @

ansible_collections/community/vmware/plugins/modules/vmware_host_active_directory.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2018, Christian Kotte <[email protected]>
5 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
6 # SPDX-License-Identifier: GPL-3.0-or-later
7
8 from __future__ import absolute_import, division, print_function
9 __metaclass__ = type
10
11
12 DOCUMENTATION = r'''
13 ---
14 module: vmware_host_active_directory
15 short_description: Joins an ESXi host system to an Active Directory domain or leaves it
16 description:
17 - This module can be used to join or leave an ESXi host to or from an Active Directory domain.
18 author:
19 - Christian Kotte (@ckotte)
20 options:
21 ad_domain:
22 description:
23 - AD Domain to join.
24 type: str
25 default: ''
26 aliases: [ domain, domain_name ]
27 ad_user:
28 description:
29 - Username for AD domain join.
30 type: str
31 default: ''
32 ad_password:
33 description:
34 - Password for AD domain join.
35 type: str
36 default: ''
37 ad_state:
38 description:
39 - Whether the ESXi host is joined to an AD domain or not.
40 type: str
41 choices: [ present, absent ]
42 default: 'absent'
43 aliases: [ state ]
44 esxi_hostname:
45 description:
46 - Name of the host system to work with.
47 - This parameter is required if O(cluster_name) is not specified.
48 type: str
49 cluster_name:
50 description:
51 - Name of the cluster from which all host systems will be used.
52 - This parameter is required if O(esxi_hostname) is not specified.
53 type: str
54 extends_documentation_fragment:
55 - vmware.vmware.base_options
56
57 '''
58
59 EXAMPLES = r'''
60 - name: Join an AD domain
61 community.vmware.vmware_host_active_directory:
62 hostname: '{{ vcenter_hostname }}'
63 username: '{{ vcenter_username }}'
64 password: '{{ vcenter_password }}'
65 esxi_hostname: '{{ esxi_hostname }}'
66 ad_domain: example.local
67 ad_user: adjoin
68 ad_password: Password123$
69 ad_state: present
70 delegate_to: localhost
71
72 - name: Join an AD domain in a specific OU
73 community.vmware.vmware_host_active_directory:
74 hostname: '{{ vcenter_hostname }}'
75 username: '{{ vcenter_username }}'
76 password: '{{ vcenter_password }}'
77 esxi_hostname: '{{ esxi_hostname }}'
78 ad_domain: "example.local/Some-OU/Some-SubOU/"
79 ad_user: adjoin
80 ad_password: Password123$
81 ad_state: present
82 delegate_to: localhost
83
84 - name: Leave AD domain
85 community.vmware.vmware_host_active_directory:
86 hostname: '{{ vcenter_hostname }}'
87 username: '{{ vcenter_username }}'
88 password: '{{ vcenter_password }}'
89 esxi_hostname: '{{ esxi_hostname }}'
90 ad_state: absent
91 delegate_to: localhost
92 '''
93
94 RETURN = r'''
95 results:
96 description: metadata about host system's AD domain join state
97 returned: always
98 type: dict
99 sample: {
100 "esxi01": {
101 "changed": true,
102 "domain": "example.local",
103 "membership_state": "ok",
104 "msg": "Host joined to AD domain",
105 "ad_state": "present",
106 "ad_state_current": "present",
107 "ad_state_previous": "absent",
108 },
109 }
110 '''
111
112 try:
113 from pyVmomi import vim
114 except ImportError:
115 pass
116
117 from ansible.module_utils.basic import AnsibleModule
118 from ansible_collections.community.vmware.plugins.module_utils.vmware import PyVmomi, TaskError, wait_for_task
119 from ansible_collections.vmware.vmware.plugins.module_utils.argument_spec import base_argument_spec
120 from ansible.module_utils.common.text.converters import to_native
121
122
123 class VmwareHostAdAuthentication(PyVmomi):
124 """Manage Active Directory Authentication for an ESXi host system"""
125
126 def __init__(self, module):
127 super(VmwareHostAdAuthentication, self).__init__(module)
128 cluster_name = self.params.get('cluster_name')
129 esxi_host_name = self.params.get('esxi_hostname')
130 self.hosts = self.get_all_host_objs(cluster_name=cluster_name, esxi_host_name=esxi_host_name)
131 if not self.hosts:
132 self.module.fail_json(msg="Failed to find host system.")
133
134 def ensure(self):
135 """Manage Active Directory Authentication for an ESXi host system"""
136 results = dict(changed=False, result=dict())
137 desired_state = self.params.get('ad_state')
138 domain = self.params.get('ad_domain')
139 ad_user = self.params.get('ad_user')
140 ad_password = self.params.get('ad_password')
141 host_change_list = []
142 for host in self.hosts:
143 changed = False
144 results['result'][host.name] = dict(msg='')
145
146 active_directory_info = self.get_ad_info(host)
147
148 results['result'][host.name]['ad_state'] = desired_state
149 results['result'][host.name]['ad_domain'] = domain
150 if desired_state == 'present':
151 # Don't do anything if already enabled and joined
152 if active_directory_info.enabled:
153 # Joined and no problems with the domain membership
154 if active_directory_info.domainMembershipStatus == 'ok':
155 results['result'][host.name]['changed'] = False
156 results['result'][host.name]['membership_state'] = active_directory_info.domainMembershipStatus
157 results['result'][host.name]['joined_domain'] = active_directory_info.joinedDomain
158 results['result'][host.name]['trusted_domains'] = active_directory_info.trustedDomain
159 results['result'][host.name]['msg'] = (
160 "Host is joined to AD domain and there are no problems with the domain membership"
161 )
162 # Joined, but problems with the domain membership
163 else:
164 changed = results['result'][host.name]['changed'] = True
165 results['result'][host.name]['membership_state'] = active_directory_info.domainMembershipStatus
166 results['result'][host.name]['joined_domain'] = active_directory_info.joinedDomain
167 results['result'][host.name]['trusted_domains'] = active_directory_info.trustedDomain
168 msg = host.name + " is joined to AD domain, but "
169 if active_directory_info.domainMembershipStatus == 'clientTrustBroken':
170 msg += "the client side of the trust relationship is broken"
171 elif active_directory_info.domainMembershipStatus == 'inconsistentTrust':
172 msg += "unexpected domain controller responded"
173 elif active_directory_info.domainMembershipStatus == 'noServers':
174 msg += "no domain controllers could be reached to confirm"
175 elif active_directory_info.domainMembershipStatus == 'serverTrustBroken':
176 msg += "the server side of the trust relationship is broken (or bad machine password)"
177 elif active_directory_info.domainMembershipStatus == 'otherProblem':
178 msg += "there are some problems with the domain membership"
179 elif active_directory_info.domainMembershipStatus == 'unknown':
180 msg += "the Active Directory integration provider does not support domain trust checks"
181 results['result'][host.name]['msg'] = msg
182 self.module.fail_json(msg=msg)
183 # Enable and join AD domain
184 else:
185 if self.module.check_mode:
186 changed = results['result'][host.name]['changed'] = True
187 results['result'][host.name]['ad_state_previous'] = "absent"
188 results['result'][host.name]['ad_state_current'] = "present"
189 results['result'][host.name]['msg'] = "Host would be joined to AD domain"
190 else:
191 ad_authentication = self.get_ad_auth_object(host)
192 try:
193 try:
194 task = ad_authentication.JoinDomain(
195 domainName=domain, userName=ad_user, password=ad_password
196 )
197 wait_for_task(task)
198 except TaskError as task_err:
199 self.module.fail_json(
200 msg="Failed to join domain : %s" % to_native(task_err)
201 )
202 changed = results['result'][host.name]['changed'] = True
203 results['result'][host.name]['ad_state_previous'] = "absent"
204 results['result'][host.name]['ad_state_current'] = "present"
205 results['result'][host.name]['msg'] = "Host joined to AD domain"
206 active_directory_info = self.get_ad_info(host)
207 results['result'][host.name]['membership_state'] = active_directory_info.domainMembershipStatus
208 except vim.fault.InvalidState as invalid_state:
209 self.module.fail_json(
210 msg="The host has already joined a domain : %s" % to_native(invalid_state.msg)
211 )
212 except vim.fault.HostConfigFault as host_fault:
213 self.module.fail_json(
214 msg="The host configuration prevents the join operation from succeeding : %s" %
215 to_native(host_fault.msg)
216 )
217 except vim.fault.InvalidLogin as invalid_login:
218 self.module.fail_json(
219 msg="Credentials aren't valid : %s" % to_native(invalid_login.msg)
220 )
221 except vim.fault.TaskInProgress as task_in_progress:
222 self.module.fail_json(
223 msg="The ActiveDirectoryAuthentication object is busy : %s" %
224 to_native(task_in_progress.msg)
225 )
226 except vim.fault.BlockedByFirewall as blocked_by_firewall:
227 self.module.fail_json(
228 msg="Ports needed by the join operation are blocked by the firewall : %s" %
229 to_native(blocked_by_firewall.msg)
230 )
231 except vim.fault.DomainNotFound as not_found:
232 self.module.fail_json(
233 msg="The domain controller can't be reached : %s" % to_native(not_found.msg)
234 )
235 except vim.fault.NoPermissionOnAD as no_permission:
236 self.module.fail_json(
237 msg="The specified user has no right to add hosts to the domain : %s" %
238 to_native(no_permission.msg)
239 )
240 except vim.fault.InvalidHostName as invalid_host:
241 self.module.fail_json(
242 msg="The domain part of the host's FQDN doesn't match the domain being joined : %s" %
243 to_native(invalid_host.msg)
244 )
245 except vim.fault.ClockSkew as clock_skew:
246 self.module.fail_json(
247 msg="The clocks of the host and the domain controller differ by more "
248 "than the allowed amount of time : %s" % to_native(clock_skew.msg)
249 )
250 except vim.fault.ActiveDirectoryFault as ad_fault:
251 self.module.fail_json(
252 msg="An error occurred during AD join : %s" %
253 to_native(ad_fault.msg)
254 )
255 elif desired_state == 'absent':
256 # Don't do anything not joined to any AD domain
257 if not active_directory_info.enabled:
258 results['result'][host.name]['changed'] = False
259 results['result'][host.name]['ad_state_current'] = "absent"
260 results['result'][host.name]['msg'] = "Host isn't joined to an AD domain"
261 # Disable and leave AD domain
262 else:
263 if self.module.check_mode:
264 changed = results['result'][host.name]['changed'] = True
265 results['result'][host.name]['ad_state_previous'] = "present"
266 results['result'][host.name]['ad_state_current'] = "absent"
267 results['result'][host.name]['msg'] = "Host would leave the AD domain '%s'" % \
268 active_directory_info.joinedDomain
269 else:
270 ad_authentication = self.get_ad_auth_object(host)
271 try:
272 try:
273 task = ad_authentication.LeaveCurrentDomain(force=True)
274 wait_for_task(task)
275 except TaskError as task_err:
276 self.module.fail_json(
277 msg="Failed to join domain : %s" % to_native(task_err)
278 )
279 changed = results['result'][host.name]['changed'] = True
280 results['result'][host.name]['ad_state_previous'] = "present"
281 results['result'][host.name]['ad_state_current'] = "absent"
282 results['result'][host.name]['msg'] = "Host left the AD domain '%s'" % \
283 active_directory_info.joinedDomain
284 except vim.fault.InvalidState as invalid_state:
285 self.module.fail_json(
286 msg="The host is not in a domain or there are active permissions for "
287 "Active Directory users : %s" % to_native(invalid_state.msg)
288 )
289 except vim.fault.AuthMinimumAdminPermission as admin_permission:
290 self.module.fail_json(
291 msg="This change would leave the system with no Administrator permission "
292 "on the root node : %s" % to_native(admin_permission.msg)
293 )
294 except vim.fault.TaskInProgress as task_in_progress:
295 self.module.fail_json(
296 msg="The ActiveDirectoryAuthentication object is busy : %s" %
297 to_native(task_in_progress.msg)
298 )
299 except vim.fault.NonADUserRequired as non_ad_user:
300 self.module.fail_json(
301 msg="Only non Active Directory users can initiate the leave domain operation : %s" %
302 to_native(non_ad_user.msg)
303 )
304 except vim.fault.ActiveDirectoryFault as ad_fault:
305 self.module.fail_json(
306 msg="An error occurred during AD leave : %s" %
307 to_native(ad_fault.msg)
308 )
309
310 host_change_list.append(changed)
311
312 if any(host_change_list):
313 results['changed'] = True
314 self.module.exit_json(**results)
315
316 def get_ad_info(self, host_object):
317 """Get info about AD membership"""
318 active_directory_info = None
319 authentication_store_info = host_object.config.authenticationManagerInfo.authConfig
320 for authentication_info in authentication_store_info:
321 if isinstance(authentication_info, vim.host.ActiveDirectoryInfo):
322 active_directory_info = authentication_info
323 break
324 if not active_directory_info:
325 self.module.fail_json(
326 msg="Failed to get Active Directory info from authentication manager"
327 )
328 return active_directory_info
329
330 def get_ad_auth_object(self, host_object):
331 """Get AD authentication managed object"""
332 ad_authentication = None
333 authentication_store_info = host_object.configManager.authenticationManager.supportedStore
334 for store_info in authentication_store_info:
335 if isinstance(store_info, vim.host.ActiveDirectoryAuthentication):
336 ad_authentication = store_info
337 break
338 if not ad_authentication:
339 self.module.fail_json(
340 msg="Failed to get Active Directory authentication managed object from authentication manager"
341 )
342 return ad_authentication
343
344
345 def main():
346 """Main"""
347 argument_spec = base_argument_spec()
348 argument_spec.update(
349 ad_domain=dict(type='str', default='', aliases=['domain', 'domain_name']),
350 ad_user=dict(type='str', default=''),
351 ad_password=dict(type='str', default='', no_log=True),
352 ad_state=dict(default='absent', choices=['present', 'absent'], aliases=['state']),
353 esxi_hostname=dict(type='str', required=False),
354 cluster_name=dict(type='str', required=False),
355 )
356
357 module = AnsibleModule(
358 argument_spec=argument_spec,
359 required_one_of=[
360 ['cluster_name', 'esxi_hostname'],
361 ],
362 required_if=[
363 ['ad_state', 'present', ['ad_domain', 'ad_user', 'ad_password']],
364 ],
365 supports_check_mode=True
366 )
367
368 ad_auth = VmwareHostAdAuthentication(module)
369 ad_auth.ensure()
370
371
372 if __name__ == '__main__':
373 main()