Monday, May 4, 2009

MSBuild VMWare VI Revert Machine

For nightly deploys I thought it would be best to revert our VM testing machine which is hosted on a VirtualInfrastructure server (can be ESX), but it proved to be kind of a bitch. Heres what I did to get it to work:

1. Install PowerShell (http://www.microsoft.com/windowsserver2003/technologies/management/powershell/download.mspx)

2. Install VI Toolkit (http://www.vmware.com/sdk/vitk_win/index.html)

3. Copy Initialize-VIToolkitEnvironment.ps1 located in the VI Toolkits folder, to something like revert_machine.ps1 and put it in a common place, I put mine with the build scripts.

4. Add this garbage to the ps1 file:

connect-viserver restore -Protocol https -User USERNAME -Password "PASSWORD"
stop-vm VMNAME -confirm:$false

set-vm VMNAME -Snapshot (get-snapshot -vm VMNAME -name "IMAGE NAME") -confirm:$false
start-vm VMNAME -confirm:$false
sleep 90
exit

Only put -Protocol https if its https
Username is a user that has rights to revert
Password is their pass, needs quotes I think
VMNAME is the name of the Virtual Machine
IMAGE NAME is the name of the Snapshot to revert to, keep in mind that you should only have one snapshot with this name otherwise it returns a list or something and it all fails.

You can change the sleep or get rid of it, 90 seconds was about how long it took for the machine to start up and auto login plus a little padding.

5. Add this task to a target
<Exec Command='powershell.exe -psc "C:\Program Files\VMware\Infrastructure\VIToolkitForWindows\vim.psc1" -c ". \".\revert_VMMACHINE.ps1\""' />

Just sub in the correct name and path of the ps1 file you created.

I'm sure theres a bunch of ways to do this but this was quick and it works. Only time I had problems was when i didnt specify the User and pass for connecting to the VI server and when I accidently made a snapshot with the same name. Other than that its worked fine. Enjoy.

2 comments: