Automating Snapshot Lifecycle for Nutanix with Ansible

Introduction

Snapshots are critical for backup and recovery, but they must be managed correctly to avoid sprawl. With Ansible, you can automate the full snapshot lifecycle on Nutanix AHV, creating, listing, and deleting snapshots through playbooks. This article shows you how to set up reusable snapshot tasks and schedule them reliably.


My Personal Repository on GitHub

Nutanix Repository on GitHub


Diagram: Snapshot Lifecycle Flow


Use Case

  • Create a daily snapshot
  • Retain only 3 latest snapshots per VM
  • Delete older snapshots automatically

Required Files

  • inventory.yml
  • nutanix_credentials.yml (vault encrypted)
  • rotate_snapshots.yml (main playbook)

Sample Playbook: rotate_snapshots.yml

- name: Snapshot lifecycle for Nutanix VM
hosts: localhost
gather_facts: false
collections:
- nutanix.ncp
vars_files:
- nutanix_credentials.yml
vars:
vm_list:
- web01
- db01
max_snapshots: 3
tasks:

- name: Create snapshot for each VM
loop: "{{ vm_list }}"
loop_control:
loop_var: vm_name
nutanix.ncp.vm_snapshots:
vm_name: "{{ vm_name }}"
snapshot_name: "{{ vm_name }}_snap_{{ '%Y%m%d' | strftime(ansible_date_time.epoch) }}"
state: present

- name: Get snapshot list per VM
loop: "{{ vm_list }}"
loop_control:
loop_var: vm_name
nutanix.ncp.vm_snapshots_info:
vm_name: "{{ vm_name }}"
register: snap_outputs

- name: Delete old snapshots (retain max_snapshots)
loop: "{{ snap_outputs.results }}"
when: item.snapshots | length > max_snapshots
loop_control:
label: "{{ item.invocation.module_args.vm_name }}"
block:
- name: Sort and trim snapshots
set_fact:
to_delete: "{{ item.snapshots | sort(attribute='creation_time') | map(attribute='name') | list | slice(0, item.snapshots | length - max_snapshots) }}"

- name: Delete older snapshots
loop: "{{ to_delete }}"
loop_control:
loop_var: snap_name
nutanix.ncp.vm_snapshots:
vm_name: "{{ item.invocation.module_args.vm_name }}"
snapshot_name: "{{ snap_name }}"
state: absent

Run It

ansible-playbook rotate_snapshots.yml --ask-vault-pass -i inventory.yml

Scheduling with Cron

Use a daily job in the control server:

0 2 * * * /usr/local/bin/run_snapshot_rotate.sh

Where run_snapshot_rotate.sh wraps the Ansible call.


Summary

This playbook gives you complete control over Nutanix VM snapshots, ensuring consistency, compliance, and automation without cluttering storage. Adjust retention policies and VM targets as needed for any application tier.

External Documentation:

Leave a Reply

Discover more from Digital Thought Disruption

Subscribe now to keep reading and get access to the full archive.

Continue reading