This is the playbook that I have for VM deletion in vCenter.
My requirement here is to add a validation to check if the VM is in "poweredoff" state before proceeding for VM deletion, the task of VM deletion should trigger only if the "VM to be removed" is in "poweredoff" state.
If the "VM to be removed" is in "poweredon" state then it should display an message saying "VM is in powered on state."
Need help in adding validation to playbook, Thanks in advance.
---
# VM Automation Playbook
- name: Remove VM
hosts: localhost
connection: local
gather_facts: no
tasks:
- name: Remove VM
vmware_guest:
hostname: '{{ vcenter_hostname }}' #The hostname or IP address of the vSphere vCenter or ESXi server.
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
validate_certs: False
datacenter: '{{ datacenter_name }}' #Destination datacenter for the deploy operation.
name: '{{ vm_name }}' #Name of the VM to be created.
force: yes
state: absent #Specify the state the virtual machine should be in.
According the Ansible Collection documentation of Community.Vmware you may use the module vmware_vm_info
to return basic info pertaining to a VMware machine guest
- name: Get virtual machine info
vmware_vm_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
folder: '{{ of_datacenter }}'
validate_certs: no
vm_type: vm
delegate_to: localhost
register: vm_info
- name: Show 'power_state' of {{ vm_name }}
debug:
msg: "{{ item.power_state}}"
with_items:
- "{{ vm_info.virtual_machines | json_query(query) }}"
vars:
query: "[?guest_name=='{{ vm_name }}']"
as the Return Values will have a power_state
.
If the "VM to be removed" is in "poweredon" state then it should display an message saying "VM is in powered on state."
Based on that you could proceed further with the result in the module assert
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.