Snapshots in VMware environments can be a double-edged sword: great for short-term recovery, but problematic if left unmanaged. In this post, I’ll show you how to use Ansible with a dynamic inventory to list all snapshots across your virtual machines (VMs) — and cleanly handle VMs without any snapshots.
We’ll be using the community.vmware.vmware_guest_snapshot_info
module to collect snapshot information from vSphere. The approach works perfectly for environments managed via a dynamic inventory, where VM-specific details like name
and folder
come from the inventory itself.
The Playbook
Here’s the playbook list_all_vm_snapshots.yaml
that does the work :
---
- name: Get a list of VM snapshots using dynamic inventory
hosts: all
gather_facts: no
tasks:
- name: Gather snapshot info
community.vmware.vmware_guest_snapshot_info:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
datacenter: "{{ datacenter_name }}"
name: "{{ hostvars[inventory_hostname].name }}"
folder: "{{ hostvars[inventory_hostname].path }}"
validate_certs: false
register: snapshot_info
delegate_to: localhost
- name: Output snapshot info if snapshots exist
debug:
msg: "Snapshots for VM {{ inventory_hostname }}: {{ snapshot_info.guest_snapshots.snapshots }}"
when: >
snapshot_info.guest_snapshots is defined
and snapshot_info.guest_snapshots.snapshots is defined
and snapshot_info.guest_snapshots.snapshots | length > 0
- name: Output if no snapshots exist
debug:
msg: "No snapshots found for {{ inventory_hostname }}"
when: >
snapshot_info.guest_snapshots is not defined
or snapshot_info.guest_snapshots.snapshots is not defined
or snapshot_info.guest_snapshots.snapshots | length == 0
Key Points
1. Dynamic Inventory Support
This playbook assumes that you’re using a dynamic inventory plugin like vmware_vm_inventory
, which provides VM-specific variables such as name
and path
.
2. Robust Snapshot Detection
Some VMs won’t have the guest_snapshots
attribute at all if no snapshots exist. To avoid errors, the when
condition checks whether:
guest_snapshots
is definedsnapshots
is defined within it- the
snapshots
list has entries
This ensures clean output and prevents undefined variable
errors.
3. Local Execution with delegate_to
Snapshot queries are run locally on the control node, not on the VM itself.
Example Output
Here’s what output might look like:
TASK [Output snapshot info if snapshots exist]
ok: [vm01] => {
"msg": "Snapshots for VM vm01: [{'name': 'PrePatch', 'description': 'Before Patch', ...}]"
}
TASK [Output if no snapshots exist]
ok: [vm02] => {
"msg": "No snapshots found for vm02"
}
Wrapping Up
This playbook provides a solid base for snapshot management in Ansible. You can expand it by:
- Sending reports via email
- Failing the play if snapshots are older than a certain threshold
- Automatically removing snapshots based on policies
📌 Want to automate cleanup? Stay tuned — the next blog post will cover that!
Schreibe einen Kommentar