@@ -664,7 +664,7 @@ def poweron_vms(self, vms):
664664 tasks = [vm .PowerOn () for vm in to_poweron_vms ]
665665 WaitForTasks (tasks , self ._si )
666666
667- def destroy_vms (self , vms ):
667+ def destroy_vms (self , vms , remove_disks = False ):
668668 """
669669 Destroys the VM's
670670
@@ -673,6 +673,14 @@ def destroy_vms(self, vms):
673673
674674 """
675675 self .poweroff_vms (vms )
676+ if remove_disks :
677+ for vm in vms :
678+ try :
679+ self .remove_disks_with_main_disk (vm )
680+ except Exception as e :
681+ logger .error (
682+ f"Failed to remove disks for VM { vm .name } with error { e } "
683+ )
676684 logger .info (f"Destroying VM's: { [vm .name for vm in vms ]} " )
677685 tasks = [vm .Destroy_Task () for vm in vms ]
678686 WaitForTasks (tasks , self ._si )
@@ -816,6 +824,36 @@ def get_used_unit_number(self, vm):
816824 if hasattr (device .backing , "fileName" ) and device .unitNumber != 0
817825 ]
818826
827+ def remove_disks_with_main_disk (self , vm ):
828+ """
829+ Removes all disks for a VM
830+
831+ Args:
832+ vm (vim.VirtualMachine): VM instance
833+
834+ """
835+ extra_disk_unit_numbers = self .get_used_unit_number_with_all_unit_number (vm )
836+ if extra_disk_unit_numbers :
837+ for each_disk_unit_number in extra_disk_unit_numbers :
838+ self .remove_disk (vm = vm , identifier = each_disk_unit_number )
839+
840+ def get_used_unit_number_with_all_unit_number (self , vm ):
841+ """
842+ Gets the used unit numbers including main disk for a VM
843+
844+ Args:
845+ vm (vim.VirtualMachine): VM instance
846+
847+ Returns:
848+ list: list of unit numbers
849+
850+ """
851+ return [
852+ device .unitNumber
853+ for device in vm .config .hardware .device
854+ if hasattr (device .backing , "fileName" )
855+ ]
856+
819857 def check_folder_exists (self , name , cluster , dc ):
820858 """
821859 Checks whether folder exists in Templates
@@ -1798,3 +1836,27 @@ def add_interface_to_compute_vms(
17981836 f"Task for configuring network for { vm .name } did not complete successfully."
17991837 )
18001838 logger .info (f"Network adapter added to { vm .name } successfully." )
1839+
1840+ def get_vms_by_string (self , str_to_match ):
1841+ """
1842+ Gets the VM's with search string
1843+
1844+ Args:
1845+ str_to_match (str): String to match VM's
1846+
1847+ Returns:
1848+ list: VM instance
1849+
1850+ """
1851+
1852+ content = self .get_content
1853+ container = content .rootFolder
1854+ view_type = [vim .VirtualMachine ]
1855+ recursive = True
1856+
1857+ container_view = content .viewManager .CreateContainerView (
1858+ container , view_type , recursive
1859+ )
1860+ vms = [vm for vm in container_view .view if str_to_match in vm .name ]
1861+ container_view .Destroy ()
1862+ return vms
0 commit comments