Using PowerCLI to Replicate Templates to Multiple Clusters

Share on:

We have multiple clusters within our vCenters that are defined as a rack. Each rack has its own storage, so storage is not shared between clusters. I needed to develop a way to easily replicate templates between clusters, so a local copy existed on each cluster to take advantage of VAAI.

I really wanted to utilize the vSphere Content Libary for these, but there is currently no publicly available documentation on how to deploy a VM from a Content Library via a Script. I am hoping when that is available, I will update this post.

Pre-Requsites

Preparing to Execute the Script

The script is pretty straight forward, just need to define a few variables seen below and then you execute the script. I will walk you through the process.

This script assumes the datastore you would like to deploy to is a datastore cluster. Mine are named cluster-dsc so this script was easily scaleable.

 1#Import PowerCLI Module
 2Add-PSSnapin VMware.VimAutomation.Core
 3
 4#Define Variables
 5$Credential = Get-Credential
 6$vCenter = "vcenter.lab.local"
 7$clusters = "Cluster01","Cluster02"
 8$location = "Templates"
 9$templates = "Template1","Template2"
10
11#Connect to vCenter
12Connect-VIServer $vCenter -Credential $Credential
13
14foreach ($template in $templates){
15  foreach ($cluster in $clusters){
16    #Check if Template exists
17    Try{Get-Template $template-$cluster -ErrorAction Stop;$TemplateExists = $true}Catch {$TemplateExists = $false}
18    #Create VM
19    If($TemplateExists -eq $true){
20        #Remove Old Template
21        Get-Template -Name $template-$cluster |Remove-Template -DeletePermanently -Confirm:$false
22        #Clone the Template
23        New-VM -Name $template-$cluster -Template $template -ResourcePool $cluster -Datastore $cluster-DSC -Location $location
24        #Convert to Template
25        Set-VM -VM $template-$cluster -ToTemplate -Confirm:$false
26    }
27    ElseIf($TemplateExists -eq $false){
28        #Clone the Template
29        New-VM -Name $template-$cluster -Template $template -ResourcePool $cluster -Datastore $cluster-DSC -Location $location
30        #Convert to Template
31        Set-VM -VM $template-$cluster -ToTemplate -Confirm:$false
32    }
33  }
34}
35#Disconnect from vCenter
36Disconnect-VIServer $vCenter -Force -Confirm:$false

Execute the Script

  • Run .\CloneTemplateToClusters.ps1
comments powered by Disqus

See Also