Skip to content

Instantly share code, notes, and snippets.

@chrissiefken
Created December 22, 2014 15:10
Show Gist options
  • Select an option

  • Save chrissiefken/aa08a2633edb0ea9e993 to your computer and use it in GitHub Desktop.

Select an option

Save chrissiefken/aa08a2633edb0ea9e993 to your computer and use it in GitHub Desktop.
PHP to delete EBS snapshots in a rolling window
<?php
date_default_timezone_set('UCT');
require '/usr/share/pear/AWSSDKforPHP/aws.phar';
use Aws\Ec2\Ec2Client;
$daysToSave = 14; // set this to the number of days to keep
$zone = '<zone>';
$aws_creds = array(
'key' => '<key>',
'secret' => '<secret>',
'region' => $zone
);
$client = Ec2Client::factory($aws_creds);
$result = $client->describeSnapshots(array(
'DryRun' => false,
'Filters' => array(
array(
'Name' => 'description',
'Values' => array('auto-*'), //search for any snapshot starting with auto-
)
)
));
$snapshots = $result->get('Snapshots');
foreach ($snapshots as $snapshot){
$snaptime = strtotime($snapshot['StartTime']);
$delete_time = time() - ($daysToSave * 24 * 3600);
if ($snaptime >= $delete_time) {
echo "keep " . $snapshot['SnapshotId'] . "\n";;
} else {
$result = $client->deleteSnapshot(array(
'DryRun' => false,
'SnapshotId' => $snapshot['SnapshotId'],
));
echo "delete " . $snapshot['SnapshotId'] . "\n";
}
}
@chrissiefken
Copy link
Author

See also creating automated snapshots:
https://gist.github.com/chrissiefken/bdda397583416cd59547

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment