Debian Codegraph @

ansible_collections/community/vmware/plugins/modules/vmware_host_dns.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_dns
15 short_description: Manage DNS configuration of an ESXi host system
16 description:
17 - This module can be used to configure DNS for the default TCP/IP stack on an ESXi host system.
18 author:
19 - Christian Kotte (@ckotte)
20 - Mario Lenz (@mariolenz)
21 options:
22 type:
23 description:
24 - Type of DNS assignment. Either V(dhcp) or V(static).
25 - A VMkernel adapter needs to be set to DHCP if set to V(dhcp).
26 type: str
27 choices: [ 'dhcp', 'static' ]
28 required: true
29 device:
30 description:
31 - The VMkernel network adapter to obtain DNS settings from.
32 - Needs to get its IP through DHCP, a static network configuration combined with a dynamic DNS configuration doesn't work.
33 - The parameter is only required in case of O(type=dhcp).
34 type: str
35 host_name:
36 description:
37 - The hostname to be used for the ESXi host.
38 - Cannot be used when configuring a complete cluster.
39 type: str
40 domain:
41 description:
42 - The domain name to be used for the ESXi host.
43 type: str
44 dns_servers:
45 description:
46 - A list of DNS servers to be used.
47 - The order of the DNS servers is important as they are used consecutively in order.
48 type: list
49 elements: str
50 search_domains:
51 description:
52 - A list of domains to be searched through by the resolver.
53 type: list
54 elements: str
55 verbose:
56 description:
57 - Verbose output of the DNS server configuration change.
58 - Explains if an DNS server was added, removed, or if the DNS server sequence was changed.
59 type: bool
60 default: false
61 esxi_hostname:
62 description:
63 - Name of the host system to work with.
64 - This parameter is required if O(cluster_name) is not specified and you connect to a vCenter.
65 - Cannot be used when you connect directly to an ESXi host.
66 type: str
67 cluster_name:
68 description:
69 - Name of the cluster from which all host systems will be used.
70 - This parameter is required if O(esxi_hostname) is not specified and you connect to a vCenter.
71 - Cannot be used when you connect directly to an ESXi host.
72 type: str
73 extends_documentation_fragment:
74 - vmware.vmware.base_options
75
76 '''
77
78 EXAMPLES = r'''
79 - name: Configure DNS for an ESXi host
80 community.vmware.vmware_host_dns:
81 hostname: '{{ vcenter_hostname }}'
82 username: '{{ vcenter_username }}'
83 password: '{{ vcenter_password }}'
84 esxi_hostname: '{{ esxi_hostname }}'
85 type: static
86 host_name: esx01
87 domain: example.local
88 dns_servers:
89 - 192.168.1.10
90 - 192.168.1.11
91 search_domains:
92 - subdomain.example.local
93 - example.local
94 delegate_to: localhost
95
96 - name: Configure DNS for all ESXi hosts of a cluster
97 community.vmware.vmware_host_dns:
98 hostname: '{{ vcenter_hostname }}'
99 username: '{{ vcenter_username }}'
100 password: '{{ vcenter_password }}'
101 cluster_name: '{{ cluster_name }}'
102 type: static
103 domain: example.local
104 dns_servers:
105 - 192.168.1.10
106 - 192.168.1.11
107 search_domains:
108 - subdomain.example.local
109 - example.local
110 delegate_to: localhost
111
112 - name: Configure DNS via DHCP for an ESXi host
113 community.vmware.vmware_host_dns:
114 hostname: '{{ vcenter_hostname }}'
115 username: '{{ vcenter_username }}'
116 password: '{{ vcenter_password }}'
117 esxi_hostname: '{{ esxi_hostname }}'
118 type: dhcp
119 device: vmk0
120 delegate_to: localhost
121 '''
122
123 RETURN = r'''
124 dns_config_result:
125 description: metadata about host system's DNS configuration
126 returned: always
127 type: dict
128 sample: {
129 "esx01.example.local": {
130 "changed": true,
131 "dns_servers_changed": ["192.168.1.12", "192.168.1.13"],
132 "dns_servers": ["192.168.1.10", "192.168.1.11"],
133 "dns_servers_previous": ["192.168.1.10", "192.168.1.11", "192.168.1.12", "192.168.1.13"],
134 "domain": "example.local",
135 "host_name": "esx01",
136 "msg": "DNS servers and Search domains changed",
137 "search_domains_changed": ["subdomain.example.local"],
138 "search_domains": ["subdomain.example.local", "example.local"],
139 "search_domains_previous": ["example.local"],
140 },
141 }
142 '''
143
144 try:
145 from pyVmomi import vim, vmodl
146 except ImportError:
147 pass
148
149 from ansible.module_utils.basic import AnsibleModule
150 from ansible_collections.community.vmware.plugins.module_utils.vmware import PyVmomi
151 from ansible_collections.vmware.vmware.plugins.module_utils.argument_spec import base_argument_spec
152 from ansible.module_utils.common.text.converters import to_native
153
154
155 class VmwareHostDNS(PyVmomi):
156 """Class to manage DNS configuration of an ESXi host system"""
157
158 def __init__(self, module):
159 super(VmwareHostDNS, self).__init__(module)
160 self.cluster_name = self.params.get('cluster_name')
161 self.esxi_host_name = self.params.get('esxi_hostname')
162 if self.is_vcenter():
163 if not self.cluster_name and not self.esxi_host_name:
164 self.module.fail_json(
165 msg="You connected to a vCenter but didn't specify the cluster_name or esxi_hostname you want to configure."
166 )
167 else:
168 if self.cluster_name:
169 self.module.warn(
170 "You connected directly to an ESXi host, cluster_name will be ignored."
171 )
172 if self.esxi_host_name:
173 self.module.warn(
174 "You connected directly to an ESXi host, esxi_host_name will be ignored."
175 )
176 self.hosts = self.get_all_host_objs(cluster_name=self.cluster_name, esxi_host_name=self.esxi_host_name)
177 if not self.hosts:
178 self.module.fail_json(msg="Failed to find host system(s).")
179 self.network_type = self.params.get('type')
180 self.vmkernel_device = self.params.get('device')
181 self.host_name = self.params.get('host_name')
182 self.domain = self.params.get('domain')
183 self.dns_servers = self.params.get('dns_servers')
184 self.search_domains = self.params.get('search_domains')
185
186 def ensure(self):
187 """Function to manage DNS configuration of an ESXi host system"""
188 results = dict(changed=False, dns_config_result=dict())
189 verbose = self.module.params.get('verbose', False)
190 host_change_list = []
191 for host in self.hosts:
192 initial_name = host.name
193 changed = False
194 changed_list = []
195 dns_servers_verbose_message = None
196 host_result = {'changed': '', 'msg': '', 'host_name': host.name}
197
198 host_netstack_config = host.config.network.netStackInstance
199 for instance in host_netstack_config:
200 if instance.key == 'defaultTcpipStack':
201 netstack_spec = vim.host.NetworkConfig.NetStackSpec()
202 netstack_spec.operation = 'edit'
203 netstack_spec.netStackInstance = vim.host.NetStackInstance()
204 netstack_spec.netStackInstance.key = 'defaultTcpipStack'
205 dns_config = vim.host.DnsConfig()
206 host_result['dns_config'] = self.network_type
207 host_result['search_domains'] = self.search_domains
208 if self.network_type == 'static':
209 if self.host_name:
210 if instance.dnsConfig.hostName != self.host_name:
211 host_result['host_name_previous'] = instance.dnsConfig.hostName
212 changed = True
213 changed_list.append("Host name")
214 dns_config.hostName = self.host_name
215 else:
216 dns_config.hostName = instance.dnsConfig.hostName
217
218 if self.search_domains is not None:
219 if instance.dnsConfig.searchDomain != self.search_domains:
220 host_result['search_domains_previous'] = instance.dnsConfig.searchDomain
221 host_result['search_domains_changed'] = (
222 self.get_differt_entries(instance.dnsConfig.searchDomain, self.search_domains)
223 )
224 changed = True
225 changed_list.append("Search domains")
226 dns_config.searchDomain = self.search_domains
227 else:
228 dns_config.searchDomain = instance.dnsConfig.searchDomain
229
230 if instance.dnsConfig.dhcp:
231 host_result['domain'] = self.domain
232 host_result['dns_servers'] = self.dns_servers
233 host_result['search_domains'] = self.search_domains
234 host_result['dns_config_previous'] = 'DHCP'
235 changed = True
236 changed_list.append("DNS configuration")
237 dns_config.dhcp = False
238 dns_config.virtualNicDevice = None
239 dns_config.domainName = self.domain
240 dns_config.address = self.dns_servers
241 dns_config.searchDomain = self.search_domains
242 else:
243 # Check host name
244
245 # Check domain
246 host_result['domain'] = self.domain
247 if self.domain is not None:
248 if instance.dnsConfig.domainName != self.domain:
249 host_result['domain_previous'] = instance.dnsConfig.domainName
250 changed = True
251 changed_list.append("Domain")
252 dns_config.domainName = self.domain
253 else:
254 dns_config.domainName = instance.dnsConfig.domainName
255
256 # Check DNS server(s)
257 host_result['dns_servers'] = self.dns_servers
258 if self.dns_servers is not None:
259 if instance.dnsConfig.address != self.dns_servers:
260 host_result['dns_servers_previous'] = instance.dnsConfig.address
261 host_result['dns_servers_changed'] = (
262 self.get_differt_entries(instance.dnsConfig.address, self.dns_servers)
263 )
264 changed = True
265 # build verbose message
266 if verbose:
267 dns_servers_verbose_message = self.build_changed_message(
268 instance.dnsConfig.address,
269 self.dns_servers
270 )
271 else:
272 changed_list.append("DNS servers")
273 dns_config.address = self.dns_servers
274 else:
275 dns_config.address = instance.dnsConfig.address
276
277 elif self.network_type == 'dhcp' and not instance.dnsConfig.dhcp:
278 host_result['device'] = self.vmkernel_device
279 host_result['dns_config_previous'] = 'static'
280 changed = True
281 changed_list.append("DNS configuration")
282 dns_config.dhcp = True
283 dns_config.virtualNicDevice = self.vmkernel_device
284 netstack_spec.netStackInstance.dnsConfig = dns_config
285 config = vim.host.NetworkConfig()
286 config.netStackSpec = [netstack_spec]
287
288 if changed:
289 if self.module.check_mode:
290 changed_suffix = ' would be changed'
291 else:
292 changed_suffix = ' changed'
293 if len(changed_list) > 2:
294 message = ', '.join(changed_list[:-1]) + ', and ' + str(changed_list[-1])
295 elif len(changed_list) == 2:
296 message = ' and '.join(changed_list)
297 elif len(changed_list) == 1:
298 message = changed_list[0]
299 if verbose and dns_servers_verbose_message:
300 if changed_list:
301 message = message + changed_suffix + '. ' + dns_servers_verbose_message + '.'
302 else:
303 message = dns_servers_verbose_message
304 else:
305 message += changed_suffix
306 host_result['changed'] = True
307 host_network_system = host.configManager.networkSystem
308 if not self.module.check_mode:
309 try:
310 host_network_system.UpdateNetworkConfig(config, 'modify')
311 except vim.fault.AlreadyExists:
312 self.module.fail_json(
313 msg="Network entity specified in the configuration already exist on host '%s'" % host.name
314 )
315 except vim.fault.NotFound:
316 self.module.fail_json(
317 msg="Network entity specified in the configuration doesn't exist on host '%s'" % host.name
318 )
319 except vim.fault.ResourceInUse:
320 self.module.fail_json(msg="Resource is in use on host '%s'" % host.name)
321 except vmodl.fault.InvalidArgument:
322 self.module.fail_json(
323 msg="An invalid parameter is passed in for one of the networking objects for host '%s'" %
324 host.name
325 )
326 except vmodl.fault.NotSupported as not_supported:
327 self.module.fail_json(
328 msg="Operation isn't supported for the instance on '%s' : %s" %
329 (host.name, to_native(not_supported.msg))
330 )
331 except vim.fault.HostConfigFault as config_fault:
332 self.module.fail_json(
333 msg="Failed to configure TCP/IP stacks for host '%s' due to : %s" %
334 (host.name, to_native(config_fault.msg))
335 )
336 else:
337 host_result['changed'] = False
338 message = 'All settings are already configured'
339
340 host_result['msg'] = message
341 results['dns_config_result'][initial_name] = host_result
342
343 host_change_list.append(changed)
344
345 if any(host_change_list):
346 results['changed'] = True
347 self.module.exit_json(**results)
348
349 def build_changed_message(self, dns_servers_configured, dns_servers_new):
350 """Build changed message"""
351 check_mode = 'would be ' if self.module.check_mode else ''
352 # get differences
353 add = self.get_not_in_list_one(dns_servers_new, dns_servers_configured)
354 remove = self.get_not_in_list_one(dns_servers_configured, dns_servers_new)
355 diff_servers = list(dns_servers_configured)
356 if add and remove:
357 for server in add:
358 diff_servers.append(server)
359 for server in remove:
360 diff_servers.remove(server)
361 if dns_servers_new != diff_servers:
362 message = (
363 "DNS server %s %sadded and %s %sremoved and the server sequence %schanged as well" %
364 (self.array_to_string(add), check_mode, self.array_to_string(remove), check_mode, check_mode)
365 )
366 else:
367 if dns_servers_new != dns_servers_configured:
368 message = (
369 "DNS server %s %sreplaced with %s" %
370 (self.array_to_string(remove), check_mode, self.array_to_string(add))
371 )
372 else:
373 message = (
374 "DNS server %s %sremoved and %s %sadded" %
375 (self.array_to_string(remove), check_mode, self.array_to_string(add), check_mode)
376 )
377 elif add:
378 for server in add:
379 diff_servers.append(server)
380 if dns_servers_new != diff_servers:
381 message = (
382 "DNS server %s %sadded and the server sequence %schanged as well" %
383 (self.array_to_string(add), check_mode, check_mode)
384 )
385 else:
386 message = "DNS server %s %sadded" % (self.array_to_string(add), check_mode)
387 elif remove:
388 for server in remove:
389 diff_servers.remove(server)
390 if dns_servers_new != diff_servers:
391 message = (
392 "DNS server %s %sremoved and the server sequence %schanged as well" %
393 (self.array_to_string(remove), check_mode, check_mode)
394 )
395 else:
396 message = "DNS server %s %sremoved" % (self.array_to_string(remove), check_mode)
397 else:
398 message = "DNS server sequence %schanged" % check_mode
399
400 return message
401
402 @staticmethod
403 def get_not_in_list_one(list1, list2):
404 """Return entries that ore not in list one"""
405 return [x for x in list1 if x not in set(list2)]
406
407 @staticmethod
408 def array_to_string(array):
409 """Return string from array"""
410 if len(array) > 2:
411 string = (
412 ', '.join("'{0}'".format(element) for element in array[:-1]) + ', and '
413 + "'{0}'".format(str(array[-1]))
414 )
415 elif len(array) == 2:
416 string = ' and '.join("'{0}'".format(element) for element in array)
417 elif len(array) == 1:
418 string = "'{0}'".format(array[0])
419 return string
420
421 @staticmethod
422 def get_differt_entries(list1, list2):
423 """Return different entries of two lists"""
424 return [a for a in list1 + list2 if (a not in list1) or (a not in list2)]
425
426
427 def main():
428 """Main"""
429 argument_spec = base_argument_spec()
430 argument_spec.update(
431 type=dict(required=True, type='str', choices=['dhcp', 'static']),
432 device=dict(type='str'),
433 host_name=dict(required=False, type='str'),
434 domain=dict(required=False, type='str'),
435 dns_servers=dict(required=False, type='list', default=None, elements='str'),
436 search_domains=dict(required=False, type='list', default=None, elements='str'),
437 esxi_hostname=dict(required=False, type='str'),
438 cluster_name=dict(required=False, type='str'),
439 verbose=dict(type='bool', default=False, required=False)
440 )
441
442 module = AnsibleModule(
443 argument_spec=argument_spec,
444 required_if=[
445 ['type', 'dhcp', ['device']],
446 ],
447 mutually_exclusive=[
448 ['cluster_name', 'host_name'],
449 ['cluster_name', 'esxi_hostname'],
450 ],
451 supports_check_mode=True
452 )
453
454 dns = VmwareHostDNS(module)
455 dns.ensure()
456
457
458 if __name__ == '__main__':
459 main()