PageRenderTime 39ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/ec2-delete-old-snapshots.php

https://github.com/edasque/ec2-manage-snapshots
PHP | 199 lines | 114 code | 47 blank | 38 comment | 30 complexity | 8fcb2197ca4738c277ff5f5e568e5431 MD5 | raw file
  1. <?php
  2. /**
  3. * Modified from code by:
  4. * Oren Solomianik’s
  5. * http://orensol.com/2009/02/12/how-to-delete-those-old-ec2-ebs-snapshots/
  6. * New region. ENV vars and no-op code from
  7. * @author Erik Dasque
  8. * @version 0.7
  9. * @copyright Erik Dasque, 3 March, 2010
  10. * @package default
  11. **/
  12. /**
  13. * Define DocBlock
  14. **/
  15. // Your EC2 credentials
  16. $AWS_ACCESS_KEY_ID = '';
  17. $AWS_SECRET_ACCESS_KEY='';
  18. define ('SYNTAX','Usage: php ec2-delete-old-snapshots.php -v vol-id [-v vol-id ...] -o days [--region region] [--noop]\n\n');
  19. // uncomment the next line and comment the one after so the application is always in NO-OP mode (no delete)
  20. //define("NOOP", "1");
  21. define("NOOP", "0");
  22. date_default_timezone_set('UTC');
  23. if ((empty($AWS_ACCESS_KEY_ID) ) && (!(strlen(getenv('AWS_ACCESS_KEY_ID'))==0)))
  24. { $AWS_ACCESS_KEY_ID=getenv('AWS_ACCESS_KEY_ID'); }
  25. if ((empty($AWS_SECRET_ACCESS_KEY) ) && (!(strlen(getenv('AWS_SECRET_ACCESS_KEY'))==0)))
  26. { $AWS_SECRET_ACCESS_KEY=getenv('AWS_SECRET_ACCESS_KEY'); }
  27. // parse options (vol-ids, older-than)
  28. $opts = getopt("v:o:",array("region:","noop"));
  29. if (($opts['v']) && !is_array($opts['v']))
  30. $volumes = array($opts['v']);
  31. else
  32. $volumes = $opts['v'];
  33. // to Debug getopt
  34. // var_dump($opts);
  35. if (isset($opts['noop'])) $noop=true; else $noop=false;
  36. if ($opts['region'])
  37. {
  38. if (is_array($opts['region']))
  39. die("\n\nRegion cannot have more than one value\n".SYNTAX);
  40. else
  41. $region = $opts['region'];
  42. }
  43. else { echo "No region specified, defaulting to us-east-1\n"; $region = "us-east-1"; }
  44. $ServiceURL = "https://".$region.".ec2.amazonaws.com";
  45. if (!is_array($opts['o']))
  46. {
  47. $now = time();
  48. $days = $opts['o'];
  49. $older_than = $now - $days * 24 * 60 * 60;
  50. }
  51. if ((!$volumes) || (!$older_than))
  52. die("\n\nDid not provide vol-id or older-than-time.\n".SYNTAX);
  53. echo "\n";
  54. foreach ($volumes as $volume)
  55. {
  56. echo "Will try to bulk delete for " . $volume ." in region ".$region." older than " . date("Y/m/d H:i:s", $older_than) . "\n";
  57. }
  58. echo "\n";
  59. // include required EC2 library elements
  60. require_once("Amazon/EC2/Client.php");
  61. require_once("Amazon/EC2/Model/DescribeSnapshotsRequest.php");
  62. require_once("Amazon/EC2/Model/DescribeVolumesRequest.php");
  63. require_once("Amazon/EC2/Model/DeleteSnapshotRequest.php");
  64. //$ec2Config = array ('ServiceURL' => 'https://us-east-1.ec2.amazonaws.com');
  65. $ec2Config = array ('ServiceURL' => $ServiceURL);
  66. // instantiate EC2 client
  67. // was:
  68. //$service = new Amazon_EC2_Client(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY);
  69. // with support for a different zone than US we do the following:
  70. $service = new Amazon_EC2_Client($AWS_ACCESS_KEY_ID, $AWS_SECRET_ACCESS_KEY, $ec2Config);
  71. // Modify for Europe
  72. // $ec2Config = array ('ServiceURL' => 'https://eu-west-1.ec2.amazonaws.com');
  73. // $ec2 = new Amazon_EC2_Client($accessKeyId, $secretAccessKey, $ec2Config);
  74. // for US-East:
  75. // $ec2Config = array ('ServiceURL' => 'https://us-east-1.ec2.amazonaws.com');
  76. // get all volumes
  77. $request_v = new Amazon_EC2_Model_DescribeVolumesRequest();
  78. try {
  79. $response_v = $service->describeVolumes($request);
  80. } catch (Amazon_EC2_Exception $e) {
  81. echo 'Error: ' .$e->getMessage()."\n";
  82. die ("\nExiting application\n\n");
  83. }
  84. $result_v = $response_v->getDescribeVolumesResult();
  85. $volumes_found = $result_v->getVolume();
  86. if (!is_array($volumes_found) || empty($volumes_found)) die ("No volumes found in region ".$region."\n\n");
  87. $a_match=false;
  88. foreach ($volumes_found as $volume_in_region)
  89. {
  90. foreach ($volumes as $volume_in_request)
  91. {
  92. $a_match = ($volume_in_request==$volume_in_region->getVolumeId());
  93. // echo $volume_in_request." may match (".$a_match.") ".$volume_in_region->getVolumeId()."\n";
  94. }
  95. if ($a_match) break;
  96. }
  97. if (!$a_match) die ("None of these volumes were found in region ".$region."\n\n");
  98. // get all snapshots
  99. $request = new Amazon_EC2_Model_DescribeSnapshotsRequest();
  100. $response = $service->describeSnapshots($request);
  101. $result = $response->getDescribeSnapshotsResult();
  102. $snaps = $result->getSnapshot();
  103. if (is_array($snaps))
  104. {
  105. // first check we have at least 1 newer snapshot for every vol-id we got
  106. // we don't want to delete all snapshots of a vol and be left with no snapshots,
  107. // this guarantees it. so we build a "go_ahead_volumes" array.
  108. foreach ($volumes as $volume)
  109. {
  110. foreach ($snaps as $snap)
  111. {
  112. $snapTimestamp = strtotime($snap->getStartTime());
  113. $snapStatus = $snap->getStatus();
  114. if (($snapTimestamp >= $older_than) && ($snapStatus=="completed"))
  115. {
  116. if ($snap->getVolumeId() == $volume)
  117. {
  118. $go_ahead_volumes[] = $volume;
  119. echo "Ready for deletion of snapshots older than ".date("Y/m/d H:i:s e", $older_than). " for volume[".$volume."] in region ".$region;
  120. echo ",\nfound newer snapshot [" . $snap->getSnapshotId() . "] taken on " . date('m/d/y \a\t H:i:s e',strtotime($snap->getStartTime())) . "\n";
  121. break;
  122. }
  123. }
  124. }
  125. }
  126. if (empty($go_ahead_volumes)) die ("No snapshots found for these volumes in region ".$region."\n\n");
  127. echo "\n";
  128. // now go over all snaps, if encounter a snap for a go_ahead_volume which
  129. // is older than, well, older_than, delete it.
  130. $dodelete = true;
  131. if (NOOP) { $dodelete = false; echo "WARNING: the global NOOP is set in the source code for debbugging purpose so we won't be actually performing deletions\n\n"; }
  132. else if ($noop) { $dodelete = false; echo "WARNING: not actually deleting, you specified --noop\n\n"; }
  133. foreach ($snaps as $snap)
  134. {
  135. $snapTimestamp = strtotime($snap->getStartTime());
  136. if ( (in_array($snap->getVolumeId(), $go_ahead_volumes)) && ($snapTimestamp < $older_than) )
  137. {
  138. echo "Deleting volume " . $snap->getVolumeId() . " snapshot " . $snap->getSnapshotId() . " created on: " . date('m/d/y \a\t H:i:s e',strtotime($snap->getStartTime())) ."\n";
  139. // and now really delete using EC2 library
  140. $request = new Amazon_EC2_Model_DeleteSnapshotRequest();
  141. $request->setSnapshotId($snap->getSnapshotId());
  142. if ($dodelete) $response = $service->deleteSnapshot($request);
  143. }
  144. }
  145. echo "\n\n";
  146. }
  147. else
  148. {
  149. die ("\n\nNo snapshots found, quitting.\n\n");
  150. }