PowerCLI: Configuring NTP Service on ESXi Hosts

I was recently required to configure the time configuration on multiple ESXi hosts in a number of clusters, with the below requirements:

  • Set the NTP Server(s)
  • Enable firewall service to permit outbound connections for the NTP client.
  • Start the NTP Daemon service
  • Configure the NTP Daemon service startup policy to be ‘start and stop with host’

I was able to do the above using PowerCLI to retrieve a collection of hosts in either a single or multiple clusters and apply the configuration.

Firstly we will specify the mandatory parameters required to invoke the script block by specifying the vCenter server to establish a connection, the Cluster(s) required to retrieve a collection of hosts and finally the NTP server string.

Param ([Parameter(Mandatory=$true)][string] $vCenter,[Parameter(Mandatory=$true)][String[]] $Clusters, [Parameter(Mandatory=$true)][string] $NTPServer)

Now, we will add the snap-ins to the current powershell session for PowerCLI and establish a connection to the vCenter server.

if (-not (Get-PSSnapin VMware.VimAutomation.Core -ErrorAction SilentlyContinue)) 
    {
    Add-PSSnapin VMware.VimAutomation.Core | Out-Null 
    }
Connect-VIServer $vCenter

From the collection of clusters specified in the mandatory paramater we will retrieve a collection of hosts in each cluster.

ForEach ($Cluster in $Clusters)
    { 
    $VMHosts = Get-Cluster $Cluster | Get-VMHost

On the hosts retrieved in the collection, we will invoke the script block to modify the time configuration on each host as per the requirements above.

ForEach ($VMHost in $VMHosts)
        {
Get-VMHost $VMHost.Name | Add-VMHostNtpServer $NTPServer
Get-VmHostService -VMHost $VMHost.Name | Where-Object {$_.key -eq "ntpd"} | Start-VMHostService
Get-VmHostService -VMHost $VMHost.Name | Where-Object {$_.key -eq "ntpd"} | Set-VMHostService -policy "on"
        } 
    } 

The above can be invoked from a powershell session, as per the below example.

./Set-HostNTPConfiguration.ps1 -vCenter vcenter.domain.local -Clusters cluster1, cluster2 -NTPServer uk.pool.ntp.org 

The script in full can de downloaded from https://www.dropbox.com/s/6jy5zakrr00om9m/Set-HostNTPConfiguration.ps1.


One thought on “PowerCLI: Configuring NTP Service on ESXi Hosts

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 )

Twitter picture

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

Facebook photo

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

Connecting to %s