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: 16th September 2021
First published: 23rd January 2020

This blog is created by Stuart Page

I'm a freelance web developer and technology consultant based in Surrey, UK, with over 10 years experience in web development, DevOps, Linux Administration, and IT solutions.

Need support with your infrastructure or web services?

Get in touch