Search code examples
windowsbatch-filejenkinsvmwarevmrun

Jenkins: Start remote VM and keep it running


I am trying to get Jenkins to start a virtual machine on a Jenkins slave. The VM itself will then act as a Jenkins slave. In order to do so I need to boot the VM and keep it running, even after the Jenkins job terminates. I have tried to create a freestyle project which runs a batch script on the slave and checks if the VM is running:

"C:\Program Files (x86)\VMware\VMware Workstation\vmrun.exe" -T ws start "D:\VM\MyVM.vmx"

"C:\Program Files (x86)\VMware\VMware Workstation\vmrun.exe" list

The second command shows me that the VM is actually up and running, but apparently it directly shuts down again since I can't see the node that corresponds to the VM as online.

The Jenkins Slave agent is installed as a Windows service on the VM's host and logs in as a domain user.

If I switch the first command to

"C:\Program Files (x86)\VMware\VMware Workstation\vmware.exe" -x "D:\VM\MyVM.vmx"

the VM powers on, the node gets connected to Jenkins. This is because somehow the batch script gets stuck after this command and does not terminate, so the VM remains powered on. However, if I log on the host with the same user the Jenkins service uses, I cannot see the VM running.

Ironically, I can in fact power OFF any virtual machine that I have started locally on the host from Jenkins by creating a project with the batch command

"C:\Program Files (x86)\VMware\VMware Workstation\vmrun.exe" -T ws stop "D:\VM\MyVM.vmx" soft

So, to summarize: I want to create a Jenkins job that powers on a VM so I can use it as a slave agent. The VM has to remain powered on even after the job is done, I will shut it down with a different job as needed. But only the shutdown job is working as intended.


Solution

  • After playing around with VMs and Jenkins today I learned that vmrun works perfectly if the Jenkins slave does not run as a Windows service but is launched via the Java Webstart application.

    Besides, one can prevent processes from getting killed by altering the BUILD_ID env. variable since Jenkins is using this variable to track the processes the build launched. So by changing the value of BUILD_ID before spawning processes they won't get killed after the Job finishes.