VMware {code} Community
jrgalleg
Enthusiast
Enthusiast
Jump to solution

Want to create a Python script to delete snapshots

Hello @here,


I'm trying to create a Python script (with pyvmomi) to check if one specific VM has any snapshot and then delete all of them, by asking confirmation first... But it's not working for me, I feel frustrated:

If you can help me, really appreciate it. I attach the program with .txt instead .py.

Thx.

Tags (3)
0 Kudos
1 Solution

Accepted Solutions
sdtslmn
Enthusiast
Enthusiast
Jump to solution

after review 

  • Indentation errors need to be fixed
  • The SmartConnect method should include proper parameters and exception-handling
  • The process to remove all snapshots involves calling RemoveAllSnapshots_Task() on the VM object, not on the first snapshot. The script incorrectly attempts to call RemoveAllSnapshots_Task() on snapshots[0], which is not valid


    revised script


 

from pyVim import connect
from pyVmomi import vim
import getpass
import ssl

def connect_to_vcenter():
    vcenter_host = input("vCenter server name or IP address: ")
    username = input("username: ")
    password = getpass.getpass("password: ")

    try:
        # Create an SSL context for unverified SSL cert
        context = ssl.create_default_context()
        context.check_hostname = False
        context.verify_mode = ssl.CERT_NONE

        service_instance = connect.SmartConnectNoSSL(host=vcenter_host,
                                                     user=username,
                                                     pwd=password)
        return service_instance
    except Exception as e:
        print(f"Failed to connect to vCenter: {str(e)}")
        return None

def delete_snapshots(vm):
    if not isinstance(vm, vim.VirtualMachine):
        print("Invalid virtual machine object.")
        return

    if vm.snapshot:
        snapshots = vm.snapshot.rootSnapshotList
        print("Snapshots found for this virtual machine:")
        for snapshot in snapshots:
            print(snapshot.name)

        confirm = input("Do you want to delete all these snapshots? (yes/no): ").lower()
        if confirm == "yes":
            print("Deleting snapshots...")
            try:
                task = vm.RemoveAllSnapshots_Task()
                while task.info.state not in [vim.TaskInfo.State.success, vim.TaskInfo.State.error]:
                    continue
                if task.info.state == vim.TaskInfo.State.success:
                    print("Snapshots deleted successfully.")
                else:
                    print("Failed to delete snapshots.")
            except Exception as e:
                print(f"Failed to delete snapshots: {str(e)}")
        else:
            print("Snapshot deletion cancelled.")
    else:
        print("No snapshots found for this virtual machine.")

def main():
    service_instance = connect_to_vcenter()
    if not service_instance:
        return

    content = service_instance.RetrieveContent()
    container = content.viewManager.CreateContainerView(content.rootFolder, [vim.VirtualMachine], True)
    vm_name = input("Enter the name of the virtual machine: ")

    for vm in container.view:
        if vm.name == vm_name:
            delete_snapshots(vm)
            break
    else:
        print("Virtual machine not found.")

    connect.Disconnect(service_instance)

if __name__ == "__main__":
    main()
​

 

View solution in original post

2 Replies
sdtslmn
Enthusiast
Enthusiast
Jump to solution

after review 

  • Indentation errors need to be fixed
  • The SmartConnect method should include proper parameters and exception-handling
  • The process to remove all snapshots involves calling RemoveAllSnapshots_Task() on the VM object, not on the first snapshot. The script incorrectly attempts to call RemoveAllSnapshots_Task() on snapshots[0], which is not valid


    revised script


 

from pyVim import connect
from pyVmomi import vim
import getpass
import ssl

def connect_to_vcenter():
    vcenter_host = input("vCenter server name or IP address: ")
    username = input("username: ")
    password = getpass.getpass("password: ")

    try:
        # Create an SSL context for unverified SSL cert
        context = ssl.create_default_context()
        context.check_hostname = False
        context.verify_mode = ssl.CERT_NONE

        service_instance = connect.SmartConnectNoSSL(host=vcenter_host,
                                                     user=username,
                                                     pwd=password)
        return service_instance
    except Exception as e:
        print(f"Failed to connect to vCenter: {str(e)}")
        return None

def delete_snapshots(vm):
    if not isinstance(vm, vim.VirtualMachine):
        print("Invalid virtual machine object.")
        return

    if vm.snapshot:
        snapshots = vm.snapshot.rootSnapshotList
        print("Snapshots found for this virtual machine:")
        for snapshot in snapshots:
            print(snapshot.name)

        confirm = input("Do you want to delete all these snapshots? (yes/no): ").lower()
        if confirm == "yes":
            print("Deleting snapshots...")
            try:
                task = vm.RemoveAllSnapshots_Task()
                while task.info.state not in [vim.TaskInfo.State.success, vim.TaskInfo.State.error]:
                    continue
                if task.info.state == vim.TaskInfo.State.success:
                    print("Snapshots deleted successfully.")
                else:
                    print("Failed to delete snapshots.")
            except Exception as e:
                print(f"Failed to delete snapshots: {str(e)}")
        else:
            print("Snapshot deletion cancelled.")
    else:
        print("No snapshots found for this virtual machine.")

def main():
    service_instance = connect_to_vcenter()
    if not service_instance:
        return

    content = service_instance.RetrieveContent()
    container = content.viewManager.CreateContainerView(content.rootFolder, [vim.VirtualMachine], True)
    vm_name = input("Enter the name of the virtual machine: ")

    for vm in container.view:
        if vm.name == vm_name:
            delete_snapshots(vm)
            break
    else:
        print("Virtual machine not found.")

    connect.Disconnect(service_instance)

if __name__ == "__main__":
    main()
​

 

jrgalleg
Enthusiast
Enthusiast
Jump to solution

Hello,

Wowww it works, thanks a lot!!! Awsome!!!

It works for me with this modification:

service_instance = connect.SmartConnect(host=vcenter_host,
                                                                     user=username,
                                                                     pwd=password,
                                                                     disableSslCertValidation=bool)

 

The rest it's perfect. I can delete ALL the snapshots of one VM.

Really appreciate!!!

0 Kudos