Created
May 9, 2014 22:13
-
-
Save btmash/ee1188400cdfd1c3e239 to your computer and use it in GitHub Desktop.
Using awscli to manage ec2 snapshots (creation, cleanup) with php.
This file contains 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 | |
// 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