Programster's Blog

Tutorials focusing on Linux, programming, and open-source

KVM - Automated Snapshot Pruning Script

Below is a script you can use to automatically prune old snapshots. It will keep the "freshest" x number that you specify.

<?php

# Specify your settings here.
$guestName = "guest.mydomain.com";
$numSnapshotsToKeep = 7;

function getSnapshots(string $domain) : array
{
    $cmd = "virsh snapshot-list --tree {$domain}";
    $output = shell_exec($cmd);
    $lines = explode(PHP_EOL, $output);
    $snapshotNames = array();

    foreach ($lines as $line)
    {
        $trimmedLine = trim($line);

        if ($trimmedLine === "|")
        {
            continue;
        }

        $strippedLine = str_replace("+- ", "", $trimmedLine);

        if (strlen($strippedLine) > 0)
        {
            $snapshotNames[] = $strippedLine;
        }
    }

    return $snapshotNames;
}


function pruneSnapshotsForDomain($domain, $numSnapshotsToKeep)
{
    $snapshots = getSnapshots($domain);

    while(count($snapshots) > $numSnapshotsToKeep)
    {
        $snapshotToDelete = array_shift($snapshots);
        $cmd = "virsh snapshot-delete $domain '$snapshotToDelete'";
        shell_exec($cmd);
    }
}

pruneSnapshotsForDomain($guestName, $numSnapshotsToKeep);
Last updated: 9th May 2020
First published: 23rd January 2020