ESXi NTP Configuration with PowerShell

As part of a recent automation workflow, I had cause to configure NTP on ESXi hosts. I honestly thought this would be easier than it was, but a couple of issues led me to “roll my own” function which I’m sharing here.

PowerCLI & NTP

I usually avoid writing code when there is something vendor supplied that will do the job. In the case of PowerCLI, in order to configure NTP on a host, you need to use several CMDlets, something a little like this:

$vmHost = Get-VMHost -name "esx01"
$service = Get-VmHostService -VMHost $vmHost | Where-Object {$_.key -eq "ntpd"}
Stop-VMHostService -HostService $service
Set-VMHostService -HostService $service -policy "on"
Add-VMHostNtpServer -NtpServer 10.10.1.30 -VMHost $vmHost
Get-VMHostFirewallException -VMHost $vmHost | Where-Object {$_.Name -eq "NTP <code>client"} | Set-VMHostFirewallException -Enabled:$true
Get-VmHostService -VMhost $vmHost | Where-Object {$_.key -eq "ntpd"} | Start-VMHostService

A bit more involved than I expected for a simple NTP configuration, but not insurmountable. What swung it in the end was that I was looking for something a little more “idempotent”, i.e. the ability to append to an existing configuration or replace it with a desired state*

*As an aside, maybe you want to check out some proper DSC using the Desired State Configuration for VMware which includes an NTP resource.

Set-VMHostNTP Custom Function

This function will perform the following actions:

  • Takes an array input of NTP servers and will either append these to the existing NTP server list, or replace the existing NTP server list, depending on the parameter input. If append is used, it will ensure that there are no duplicate entries on the list.
  • Set the NTP service start-up policy as specified (default is On if not specified).
  • Set the NTP service running state to Start or Stopped (if not specified, the service will be started). If the service is already started, it will be restarted to apply the new configuration.
  • Enable host firewall exception for NTP service.

Let’s looks at a couple of usage examples, we’ll use verbose output for some more detail.

In this example, we have set ntp1 and ntp2 as the time sources, and told the function to replace any existing time sources.

In this second example, I’m using the function to append a new NTP time source to all hosts in the datacentre:

Conclusion

To me this was worth the effort rather than handling several CMDlets and additional logic in the workflow. Hopefully it’s of use to you too. The function is part of the tds-vSphere module (more on this later), but for now the function is available here.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: