Home > vSphere API > How to Delete Virtual Machine With vSphere API?

How to Delete Virtual Machine With vSphere API?

January 18th, 2011 Leave a comment Go to comments

This question was asked at VI Java API forum recently and has been answered by the community.

There should be a “Destroy_Task()”-Method for each Managed Object, so also Virtual Machines…. Cheers, Joerg

Time to learn how to "Google" and manage your VMware and clouds in a fast and secure


As  Jörg Lew has correctly pointed out the solution, I would like to elaborate a bit more here.

If you are using VI Java API, the method name is destroy_Task(). The code is as simple as:

VirtualMachine vm = null;
//get object assigned to vm

To run the code, the user must have “VirtualMachine.Inventory.Delete” privilege on the virtual machine object. For other types of objects, the required privileges are different even though the method called is exactly the same. For the data center, for example, it’s “Datacenter.Delete.” You can check out the full table in the API reference.

Using destroy_Task() method can be a dangerous because it deletes everything of a VM, which cannot be reversed. If you call the method by mistake, then you’re screwed.

To play safe, you have another method to call: unregisterVM() method defined in VirtualMachine. When it’s called, the virtual machine disappears from the inventory tree, but all the files are still there. If you regret what you just called, you can add the virtual machine any time by calling the registerVM_Task() defined in Folder managed object.

The downside of this approach is you haven’t really released the disk space. If you have many of such virtual machines, you may find your data store out of space easily. To deal with it, you can run a script that scan for unregistered VM and remove them once in a while.

In the end, I have a fun question for you: what happens if you call destroy_Task() on a HostSystem? Will it destroy your ESX or ESXi?

  1. January 18th, 2011 at 05:33 | #1

    For the last question:
    I think, disabling HostSystem.config.service.service[“DCUI”] and HostSystem.enterLockdownMode() will do the job if you loose the connection between vCenter and ESXi permanently :-)

  2. timo2145
    April 2nd, 2014 at 13:24 | #2

    Leaves an orphaned server in the VCenter. Why does this code suck so bad.

  3. April 2nd, 2014 at 14:45 | #3

    That is probably you delete a VM by running the code with ESX(i) without knowledge of vCenter. Next time, connect to vCenter.

  1. No trackbacks yet.