'is there a way to automate VMware snapshot deletion by setting a schedule through Ansible or rest API

I am trying to figure out if there is a way to automate VMware snapshot deletion through Ansible.

I have found vmware_guest_powerstate.py"to be closest to it and tried to modified it but it's failing with "Failed to create scheduled task present as specifications given are invalid: A specified parameter was not correct: spec.action"

            pstate = {
                'present': vim.VirtualMachine.CreateSnapshot,
                'absent': vim.VirtualMachine.RemoveAllSnapshots,
            }
            dt = ""
            try:
                dt = datetime.strptime(scheduled_at, "%d/%m/%Y %H:%M")
            except ValueError as e:
                module.fail_json(
                    msg="Failed to convert given date and time string to Python datetime object,"
                    "please specify string in 'dd/mm/yyyy hh:mm' format: %s"
                    % to_native(e)
                )
            schedule_task_spec = vim.scheduler.ScheduledTaskSpec()
            schedule_task_name = module.params["schedule_task_name"] or "task_%s" % str(
                randint(10000, 99999)
            )
            schedule_task_desc = module.params["schedule_task_description"]
            if schedule_task_desc is None:
                schedule_task_desc = (
                    "Schedule task for vm %s for "
                    "operation %s at %s"
                    % (vm.name, scheduled_at)
                )
            schedule_task_spec.name = schedule_task_name
            schedule_task_spec.description = schedule_task_desc
            schedule_task_spec.scheduler = vim.scheduler.OnceTaskScheduler()
            schedule_task_spec.scheduler.runAt = dt
            schedule_task_spec.action = vim.action.MethodAction()
            schedule_task_spec.action.name = pstate[module.params['state']]
            schedule_task_spec.enabled = module.params["schedule_task_enabled"]



Solution 1:[1]

Suggest trying "vim.VirtualMachine.CreateSnapshot_Task" and "RemoveAllSnapshots_Task" instead of "vim.VirtualMachine.CreateSnapshot" and "vim.VirtualMachine.RemoveAllSnapshots" to see if that works.

pstate = {'present': vim.VirtualMachine.CreateSnapshot_Task,'absent': vim.VirtualMachine.RemoveAllSnapshots_Task}
    
....
                
schedule_task_spec.name = schedule_task_name
schedule_task_spec.description = schedule_task_desc
schedule_task_spec.scheduler = vim.scheduler.OnceTaskScheduler()
schedule_task_spec.scheduler.runAt = dt
schedule_task_spec.action = vim.action.MethodAction()
schedule_task_spec.action.name = pstate[module.params['state']]
schedule_task_spec.enabled = module.params["schedule_task_enabled"]
print(schedule_task_spec.action)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 paulyang0125