Created
December 22, 2014 15:10
-
-
Save chrissiefken/aa08a2633edb0ea9e993 to your computer and use it in GitHub Desktop.
PHP to delete EBS snapshots in a rolling window
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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"; | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See also creating automated snapshots:
https://gist.github.com/chrissiefken/bdda397583416cd59547