Skip to content

Instantly share code, notes, and snippets.

@klynch
Created June 27, 2013 15:21
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 klynch/5877370 to your computer and use it in GitHub Desktop.
Save klynch/5877370 to your computer and use it in GitHub Desktop.
Determines the volumes of a running EC2 instance and initiates a snapshot request. Requires DescribeVolumes and CreateSnapshot EC2 permissions.
#!/usr/bin/perl
use strict;
use warnings;
(our $Prog) = ($0 =~ m%([^/]+)$%);
use Getopt::Long;
use File::Slurp;
use Net::Amazon::EC2;
my $aws_access_key_id_file = $ENV{AWS_ACCESS_KEY_ID};
my $aws_secret_access_key_file = $ENV{AWS_SECRET_ACCESS_KEY};
Getopt::Long::config('no_ignore_case');
GetOptions(
'aws-access-key-id-file=s' => \$aws_access_key_id_file,
'aws-secret-access-key-file=s' => \$aws_secret_access_key_file,
);
#Read in the key files
my $aws_access_key_id = File::Slurp::read_file($aws_access_key_id_file);
my $aws_secret_access_key = File::Slurp::read_file($aws_secret_access_key_file);
chomp($aws_access_key_id);
chomp($aws_secret_access_key);
my $ec2 = Net::Amazon::EC2->new(
AWSAccessKeyId => $aws_access_key_id,
SecretAccessKey => $aws_secret_access_key,
);
my $instance = `curl -s http://169.254.169.254/latest/meta-data/instance-id`;
my $hostname = `hostname`;
my @attached = ();
#Iterate through all volumes to find the ones attached to us
my $volumes = $ec2->describe_volumes;
foreach my $vol (@$volumes) {
my $attachments = $vol->{'attachments'};
if (defined($attachments)) {
foreach my $attachment (@$attachments) {
if ($instance eq $attachment->{'instance_id'}) {
push(@attached, $vol->{'volume_id'});
}
}
}
}
#Now we are ready to call ec2-consistent-snapshot to actually perform the backup
system("ec2-consistent-snapshot --aws-access-key-id-file $aws_access_key_id_file --aws-secret-access-key-file $aws_secret_access_key_file --description '$hostname $instance' --freeze-filesystem / @attached");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment