I recently talked about using termination dates on VMs in order to control VM sprawl in the datacenter with the help of using virtual machine type annotations (http://wp.me/p15Mdc-n1).
Now that we have identified the termination date and notified the user who requested the VM that it is approaching the end of its lifetime, how do we manage VMs that can now be marked as expired based on their termination date and which actions do we wish to invoke agaisnt them?
There are number of actions I will be looking at based on the below:
- Shut Down Guest
- Move the VM to a Resource Folder
- Remove the VM and delete from the datastore.
As I will be invoking the script as a scheduled task I will add the PowerCLI snap-ins to the current powershell and then connect to my vcenter server and build a collection of our VMs and loop through each VM in the collection to return virtual machine annotation types required to filter which VMs have exceeded their termination dates:
If (-not (Get-PSSnapin VMware.VimAutomation.Core -ErrorAction SilentlyContinue)) { Add-PSSnapin VMware.VimAutomation.Core } Connect-VIServer server1.domain.local $VMs=Get-VM ForEach ($VM in $VMs) { $Termination = (Get-VM $VM | Get-Annotation | Where-Object {$_.Name -eq "Termination Date"}).Value $RequestedBy = (Get-VM $VM | Get-Annotation | Where-Object {$_.Name -eq "Requested By"}).Value If ($Termination -gt (Get-Date)) {
Shut Down Guest
Firstly, we will look at simply shutting down the VM, as before we will build a collection of our VMs and loop through each VM in the collection to return virtual machine annotation types required to filter which VMs have exceeded their termination dates, we will simplify invoke the Shutdown-VMGuest cmdlet agasint the filtered VM and specify that the request does not require user confirmation.
Get-VM $VM | Shutdown-VMGuest -Confirm:$False } }
Move the VM to a Resource Folder
Now we look to moving a VM to a resource folder by invoking the Move-VM cmdlet agaisnt all VMs in the collection where the termination date was greater than the current date. In this example the VM is being moved to the resource folder ‘Archive’.
Move-VM-VM $VM -Destination "Archive" } }
Remove the VM
A slightly more risky and permanent action would be to completely remove the VM once the termination date was greater than the current using the Remove-VM cmdlet and specifying the ‘DeletePermanently’ parameter to remove the VM not only from the inventory but from the datastore as well.
Remove-VM $VM -DeletePermanently -Confirm:$false } }