Skip to content

Instantly share code, notes, and snippets.

@btmash
Created May 9, 2014 22:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save btmash/ee1188400cdfd1c3e239 to your computer and use it in GitHub Desktop.
Save btmash/ee1188400cdfd1c3e239 to your computer and use it in GitHub Desktop.
Using awscli to manage ec2 snapshots (creation, cleanup) with php.
<?php
// Using awscli for this. Would probably be better in python but this was quick and simple.
date_default_timezone_set ('UTC');
/**
* Executes aws command and returns output as PHP array.
*/
function _exec_aws_command($command) {
exec($command, $value);
return json_decode(implode($value, "\n"));
}
function create_snapshots($options) {
$volumes = _exec_aws_command('aws ec2 describe-volumes');
foreach ($volumes->Volumes as $volume) {
if ($volume->State == 'in-use') {
_exec_aws_command('aws ec2 create-snapshot --volume-id ' . $volume->VolumeId . ' --description "' . $options['filter'] . ' snapshot - ' . date('c') . '"');
}
}
}
function cleanup_snapshots($options) {
$volumes = _exec_aws_command('aws ec2 describe-volumes');
foreach ($volumes->Volumes as $volume) {
$snapshots = _exec_aws_command('aws ec2 describe-snapshots --filter Name=volume-id,Values=' . $volume->VolumeId);
$snaps = array();
foreach ($snapshots->Snapshots as $snapshot) {
if (strpos($snapshot->Description, $options['filter']) !== FALSE) {
$timestamp = strtotime($snapshot->StartTime);
$snaps[$snapshot->SnapshotId] = $timestamp;
}
}
arsort($snaps);
$current = 0;
foreach ($snaps as $snapshot_id => $values) {
$current++;
if ($current > $options['limit']) {
_exec_aws_command('aws ec2 delete-snapshot --snapshot-id ' . $snapshot_id);
print "Delete snapshot id {$snapshot_id}.";
}
}
}
}
function main() {
$defaults = array(
'action' => 'create',
'filter' => 'daily',
'limit' => '4',
);
$options = getopt('', array('action::', 'filter::', 'limit::'));
$options = array_merge($defaults, $options);
if ($options['action'] == 'create') {
create_snapshots($options);
}
else if ($options['action'] == 'cleanup') {
cleanup_snapshots($options);
}
else {
print ("No such action exists.");
}
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment