Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2018, Abhijeet Kasurde <[email protected]>
5 # Copyright: (c) 2018, Christian Kotte <[email protected]>
6 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
7 # SPDX-License-Identifier: GPL-3.0-or-later
8
9 from __future__ import absolute_import, division, print_function
10 __metaclass__ = type
11
12
13 DOCUMENTATION = r'''
14 ---
15 module: vmware_host_ntp
16 short_description: Manage NTP server configuration of an ESXi host
17 description:
18 - This module can be used to configure, add or remove NTP servers from an ESXi host.
19 - If O(state) is not given, the NTP servers will be configured in the exact sequence.
20 - User can specify an ESXi hostname or Cluster name. In case of cluster name, all ESXi hosts are updated.
21 author:
22 - Abhijeet Kasurde (@Akasurde)
23 - Christian Kotte (@ckotte)
24 options:
25 esxi_hostname:
26 description:
27 - Name of the host system to work with.
28 - This parameter is required if O(cluster_name) is not specified.
29 type: str
30 cluster_name:
31 description:
32 - Name of the cluster from which all host systems will be used.
33 - This parameter is required if O(esxi_hostname) is not specified.
34 type: str
35 ntp_servers:
36 description:
37 - "IP or FQDN of NTP server(s)."
38 - This accepts a list of NTP servers. For multiple servers, please look at the examples.
39 type: list
40 required: true
41 elements: str
42 state:
43 description:
44 - "V(present): Add NTP server(s), if specified server(s) are absent else do nothing."
45 - "V(absent): Remove NTP server(s), if specified server(s) are present else do nothing."
46 - Specified NTP server(s) will be configured if O(state) isn't specified.
47 choices: [ present, absent ]
48 type: str
49 verbose:
50 description:
51 - Verbose output of the configuration change.
52 - Explains if an NTP server was added, removed, or if the NTP server sequence was changed.
53 type: bool
54 required: false
55 default: false
56 extends_documentation_fragment:
57 - vmware.vmware.base_options
58
59 '''
60
61 EXAMPLES = r'''
62 - name: Configure NTP servers for an ESXi Host
63 community.vmware.vmware_host_ntp:
64 hostname: vcenter01.example.local
65 username: [email protected]
66 password: SuperSecretPassword
67 esxi_hostname: esx01.example.local
68 ntp_servers:
69 - 0.pool.ntp.org
70 - 1.pool.ntp.org
71 delegate_to: localhost
72
73 - name: Set NTP servers for all ESXi Host in given Cluster
74 community.vmware.vmware_host_ntp:
75 hostname: '{{ vcenter_hostname }}'
76 username: '{{ vcenter_username }}'
77 password: '{{ vcenter_password }}'
78 cluster_name: '{{ cluster_name }}'
79 state: present
80 ntp_servers:
81 - 0.pool.ntp.org
82 - 1.pool.ntp.org
83 delegate_to: localhost
84
85 - name: Set NTP servers for an ESXi Host
86 community.vmware.vmware_host_ntp:
87 hostname: '{{ vcenter_hostname }}'
88 username: '{{ vcenter_username }}'
89 password: '{{ vcenter_password }}'
90 esxi_hostname: '{{ esxi_hostname }}'
91 state: present
92 ntp_servers:
93 - 0.pool.ntp.org
94 - 1.pool.ntp.org
95 delegate_to: localhost
96
97 - name: Remove NTP servers for an ESXi Host
98 community.vmware.vmware_host_ntp:
99 hostname: '{{ vcenter_hostname }}'
100 username: '{{ vcenter_username }}'
101 password: '{{ vcenter_password }}'
102 esxi_hostname: '{{ esxi_hostname }}'
103 state: absent
104 ntp_servers:
105 - bad.server.ntp.org
106 delegate_to: localhost
107 '''
108
109 RETURN = r'''
110 host_ntp_status:
111 description: metadata about host system's NTP configuration
112 returned: always
113 type: dict
114 sample: {
115 "esx01.example.local": {
116 "ntp_servers_changed": ["time1.example.local", "time2.example.local", "time3.example.local", "time4.example.local"],
117 "ntp_servers": ["time3.example.local", "time4.example.local"],
118 "ntp_servers_previous": ["time1.example.local", "time2.example.local"],
119 },
120 "esx02.example.local": {
121 "ntp_servers_changed": ["time3.example.local"],
122 "ntp_servers_current": ["time1.example.local", "time2.example.local", "time3.example.local"],
123 "state": "present",
124 "ntp_servers_previous": ["time1.example.local", "time2.example.local"],
125 },
126 }
127 '''
128
129 try:
130 from pyVmomi import vim
131 except ImportError:
132 pass
133
134 from ansible.module_utils.basic import AnsibleModule
135 from ansible_collections.community.vmware.plugins.module_utils.vmware import PyVmomi
136 from ansible_collections.vmware.vmware.plugins.module_utils.argument_spec import base_argument_spec
137 from ansible.module_utils.common.text.converters import to_native
138
139
140 class VmwareNtpConfigManager(PyVmomi):
141 """Class to manage configured NTP servers"""
142
143 def __init__(self, module):
144 super(VmwareNtpConfigManager, self).__init__(module)
145 cluster_name = self.params.get('cluster_name', None)
146 esxi_host_name = self.params.get('esxi_hostname', None)
147 self.ntp_servers = self.params.get('ntp_servers', list())
148 self.hosts = self.get_all_host_objs(cluster_name=cluster_name, esxi_host_name=esxi_host_name)
149 if not self.hosts:
150 self.module.fail_json(msg="Failed to find host system.")
151 self.results = {}
152 self.desired_state = self.params.get('state', None)
153 self.verbose = module.params.get('verbose', False)
154
155 def update_ntp_servers(self, host, ntp_servers_configured, ntp_servers_to_change, operation='overwrite'):
156 """Update NTP server configuration"""
157 host_date_time_manager = host.configManager.dateTimeSystem
158 if host_date_time_manager:
159 # Prepare new NTP server list
160 if operation == 'overwrite':
161 new_ntp_servers = list(ntp_servers_to_change)
162 else:
163 new_ntp_servers = list(ntp_servers_configured)
164 if operation == 'add':
165 new_ntp_servers = new_ntp_servers + ntp_servers_to_change
166 elif operation == 'delete':
167 for server in ntp_servers_to_change:
168 if server in new_ntp_servers:
169 new_ntp_servers.remove(server)
170
171 # build verbose message
172 if self.verbose:
173 message = self.build_changed_message(
174 ntp_servers_configured,
175 new_ntp_servers,
176 ntp_servers_to_change,
177 operation
178 )
179
180 ntp_config_spec = vim.host.NtpConfig()
181 ntp_config_spec.server = new_ntp_servers
182 date_config_spec = vim.host.DateTimeConfig()
183 date_config_spec.ntpConfig = ntp_config_spec
184 try:
185 if not self.module.check_mode:
186 host_date_time_manager.UpdateDateTimeConfig(date_config_spec)
187 if self.verbose:
188 self.results[host.name]['msg'] = message
189 except vim.fault.HostConfigFault as config_fault:
190 self.module.fail_json(
191 msg="Failed to configure NTP for host '%s' due to : %s" %
192 (host.name, to_native(config_fault.msg))
193 )
194
195 return new_ntp_servers
196
197 def check_host_state(self):
198 """Check ESXi host configuration"""
199 change_list = []
200 changed = False
201 for host in self.hosts:
202 self.results[host.name] = dict()
203 if host.runtime.connectionState == "connected":
204 ntp_servers_configured, ntp_servers_to_change = self.check_ntp_servers(host=host)
205 # add/remove NTP servers
206 if self.desired_state:
207 self.results[host.name]['state'] = self.desired_state
208 if ntp_servers_to_change:
209 self.results[host.name]['ntp_servers_changed'] = ntp_servers_to_change
210 operation = 'add' if self.desired_state == 'present' else 'delete'
211 new_ntp_servers = self.update_ntp_servers(
212 host=host,
213 ntp_servers_configured=ntp_servers_configured,
214 ntp_servers_to_change=ntp_servers_to_change,
215 operation=operation
216 )
217 self.results[host.name]['ntp_servers_current'] = new_ntp_servers
218 self.results[host.name]['changed'] = True
219 change_list.append(True)
220 else:
221 self.results[host.name]['ntp_servers_current'] = ntp_servers_configured
222 if self.verbose:
223 self.results[host.name]['msg'] = (
224 "NTP servers already added" if self.desired_state == 'present'
225 else "NTP servers already removed"
226 )
227 self.results[host.name]['changed'] = False
228 change_list.append(False)
229 # overwrite NTP servers
230 else:
231 self.results[host.name]['ntp_servers'] = self.ntp_servers
232 if ntp_servers_to_change:
233 self.results[host.name]['ntp_servers_changed'] = self.get_differt_entries(
234 ntp_servers_configured,
235 ntp_servers_to_change
236 )
237 self.update_ntp_servers(
238 host=host,
239 ntp_servers_configured=ntp_servers_configured,
240 ntp_servers_to_change=ntp_servers_to_change,
241 operation='overwrite'
242 )
243 self.results[host.name]['changed'] = True
244 change_list.append(True)
245 else:
246 if self.verbose:
247 self.results[host.name]['msg'] = "NTP servers already configured"
248 self.results[host.name]['changed'] = False
249 change_list.append(False)
250 else:
251 self.results[host.name]['changed'] = False
252 self.results[host.name]['msg'] = "Host %s is disconnected and cannot be changed." % host.name
253
254 if any(change_list):
255 changed = True
256 self.module.exit_json(changed=changed, host_ntp_status=self.results)
257
258 def check_ntp_servers(self, host):
259 """Check configured NTP servers"""
260 update_ntp_list = []
261 host_datetime_system = host.configManager.dateTimeSystem
262 if host_datetime_system:
263 ntp_servers_configured = host_datetime_system.dateTimeInfo.ntpConfig.server
264 # add/remove NTP servers
265 if self.desired_state:
266 for ntp_server in self.ntp_servers:
267 if self.desired_state == 'present' and ntp_server not in ntp_servers_configured:
268 update_ntp_list.append(ntp_server)
269 if self.desired_state == 'absent' and ntp_server in ntp_servers_configured:
270 update_ntp_list.append(ntp_server)
271 # overwrite NTP servers
272 else:
273 if ntp_servers_configured != self.ntp_servers:
274 for ntp_server in self.ntp_servers:
275 update_ntp_list.append(ntp_server)
276 if update_ntp_list:
277 self.results[host.name]['ntp_servers_previous'] = ntp_servers_configured
278
279 return ntp_servers_configured, update_ntp_list
280
281 def build_changed_message(self, ntp_servers_configured, new_ntp_servers, ntp_servers_to_change, operation):
282 """Build changed message"""
283 check_mode = 'would be ' if self.module.check_mode else ''
284 if operation == 'overwrite':
285 # get differences
286 add = self.get_not_in_list_one(new_ntp_servers, ntp_servers_configured)
287 remove = self.get_not_in_list_one(ntp_servers_configured, new_ntp_servers)
288 diff_servers = list(ntp_servers_configured)
289 if add and remove:
290 for server in add:
291 diff_servers.append(server)
292 for server in remove:
293 diff_servers.remove(server)
294 if new_ntp_servers != diff_servers:
295 message = (
296 "NTP server %s %sadded and %s %sremoved and the server sequence %schanged as well" %
297 (self.array_to_string(add), check_mode, self.array_to_string(remove), check_mode, check_mode)
298 )
299 else:
300 if new_ntp_servers != ntp_servers_configured:
301 message = (
302 "NTP server %s %sreplaced with %s" %
303 (self.array_to_string(remove), check_mode, self.array_to_string(add))
304 )
305 else:
306 message = (
307 "NTP server %s %sremoved and %s %sadded" %
308 (self.array_to_string(remove), check_mode, self.array_to_string(add), check_mode)
309 )
310 elif add:
311 for server in add:
312 diff_servers.append(server)
313 if new_ntp_servers != diff_servers:
314 message = (
315 "NTP server %s %sadded and the server sequence %schanged as well" %
316 (self.array_to_string(add), check_mode, check_mode)
317 )
318 else:
319 message = "NTP server %s %sadded" % (self.array_to_string(add), check_mode)
320 elif remove:
321 for server in remove:
322 diff_servers.remove(server)
323 if new_ntp_servers != diff_servers:
324 message = (
325 "NTP server %s %sremoved and the server sequence %schanged as well" %
326 (self.array_to_string(remove), check_mode, check_mode)
327 )
328 else:
329 message = "NTP server %s %sremoved" % (self.array_to_string(remove), check_mode)
330 else:
331 message = "NTP server sequence %schanged" % check_mode
332 elif operation == 'add':
333 message = "NTP server %s %sadded" % (self.array_to_string(ntp_servers_to_change), check_mode)
334 elif operation == 'delete':
335 message = "NTP server %s %sremoved" % (self.array_to_string(ntp_servers_to_change), check_mode)
336
337 return message
338
339 @staticmethod
340 def get_not_in_list_one(list1, list2):
341 """Return entries that ore not in list one"""
342 return [x for x in list1 if x not in set(list2)]
343
344 @staticmethod
345 def array_to_string(array):
346 """Return string from array"""
347 if len(array) > 2:
348 string = (
349 ', '.join("'{0}'".format(element) for element in array[:-1]) + ', and '
350 + "'{0}'".format(str(array[-1]))
351 )
352 elif len(array) == 2:
353 string = ' and '.join("'{0}'".format(element) for element in array)
354 elif len(array) == 1:
355 string = "'{0}'".format(array[0])
356 return string
357
358 @staticmethod
359 def get_differt_entries(list1, list2):
360 """Return different entries of two lists"""
361 return [a for a in list1 + list2 if (a not in list1) or (a not in list2)]
362
363
364 def main():
365 """Main"""
366 argument_spec = base_argument_spec()
367 argument_spec.update(
368 cluster_name=dict(type='str', required=False),
369 esxi_hostname=dict(type='str', required=False),
370 ntp_servers=dict(type='list', required=True, elements='str'),
371 state=dict(type='str', choices=['absent', 'present']),
372 verbose=dict(type='bool', default=False, required=False)
373 )
374
375 module = AnsibleModule(
376 argument_spec=argument_spec,
377 required_one_of=[
378 ['cluster_name', 'esxi_hostname'],
379 ],
380 supports_check_mode=True
381 )
382
383 vmware_host_ntp_config = VmwareNtpConfigManager(module)
384 vmware_host_ntp_config.check_host_state()
385
386
387 if __name__ == "__main__":
388 main()