Tuesday, December 30, 2008

how to run EBS(create snapshot) by using cron

previously I have shown you how to integrate EBS and create snapshot of that volume where EBS is running.

sometime it is necessary to take the snapshot using cron. which is very much easy just save the following code into a file. and run the with the cron job and you are done. remember that in that case you have to installed EC2-api-tools on the Ec2 instance. and need to configure all environment variable. this codes i have found from Eric Hammond's blog.



#!/usr/bin/perl -w
#
# ec2-snapshot-xfs-mysql - EBS snapshot XFS file system with MySQL database
#
# Usage:
#
# ec2-snapshot-xfs-mysql XFSMOUNTPOINT VOLUMEID
#
# Requires:
#
# Amazon EC2 API tools should be installed on the instance,
# especially /usr/local/bin/ec2-create-snapshot
#
# MySQL username and password are stored in $HOME/.my.cnf in the
# usual manner following this format:
#
# [client]
# user=MYUSERNAME
# password=MYPASSWORD


use strict;
use DBI;

BEGIN {
$ENV{PATH} = '/bin:/usr/bin:/usr/local/bin';
}

my ($mountpoint, $volume_id) = @ARGV;
die "Usage: $0 XFSMOUNTPOINT VOLUMEID" unless $mountpoint && $volume_id;

# Get the MySQL username/password from $HOME/.my.cnf and connect
my ($username, $password);
open(FH, "$ENV{HOME}/.my.cnf") or die "Unable to open .my.cnf: $!";
while ( defined (my $line = ) ) {
$username = $1 if $line =~ m%^\s*user\s*=\s*(\S+)%;
$password = $1 if $line =~ m%^\s*password\s*=\s*(\S+)%;
}
close(FH);
my $dbh = DBI->connect('DBI:mysql:;host=localhost', $username, $password);

# Flush, lock, freeze
$dbh->do(q{ FLUSH TABLES WITH READ LOCK });
my ($logfile, $position) = $dbh->selectrow_array(q{ SHOW MASTER STATUS });
system('sudo', 'xfs_freeze', '-f', $mountpoint);

# Snapshot
my $snapshot_output = `ec2-create-snapshot $volume_id`;
my ($snapshot_id) = ($snapshot_output =~ m%(snap-[0-9a-f]{8})%);

# Thaw, unlock
system('sudo', 'xfs_freeze', '-u', $mountpoint);
$dbh->do(q{ UNLOCK TABLES });

print $snapshot_id ?
"$snapshot_id (master_log_file=\"$logfile\", master_log_pos=$position)\n"
:
"snapshot FAILED\n";


In my next post "problem you may find during running the corn of EBS" you will get issues you may find during running the corn job for EBS.

No comments: