Last active
December 16, 2015 06:49
-
-
Save wokamoto/5394609 to your computer and use it in GitHub Desktop.
AWS で、稼働中のインスタンスで自身のEBSボリュームのスナップショットを作るためのシェルスクリプト
This file contains hidden or 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
#!/bin/sh | |
export JAVA_HOME="/usr/lib/jvm/jre" | |
export EC2_HOME="/usr/local/bin/ec2-api-tools" | |
export EC2_PRIVATE_KEY="~/ec2keys/pk-****.pem" | |
export EC2_CERT="~/ec2keys/cert-****.pem" | |
EC2_CMD="${EC2_HOME}/bin" | |
LOG_FILE="/var/log/create_snapshot.log" | |
LOG_SAVE_PERIOD=14 | |
SNAPSHOTS_PERIOD=2 | |
CREATE_MSG="Create Snapshot " | |
INSTANCE_ID=`curl -s http://169.254.169.254/latest/meta-data/instance-id` | |
REGION=ap-northeast-1 | |
print_msg() { | |
echo "`date '+%Y/%m/%d %H:%M:%S'` $1" | tee -a ${LOG_FILE} | |
} | |
print_msg "INF: START" | |
# log rotate | |
print_msg "INF: log rotate Start" | |
(( cnt=${LOG_SAVE_PERIOD} )) | |
while (( cnt > 0 )) | |
do | |
logfile1=${LOG_FILE}.$cnt | |
(( cnt=cnt-1 )) | |
logfile2=${LOG_FILE}.$cnt | |
if [ -f $logfile2 ]; then | |
mv $logfile2 $logfile1 | |
fi | |
done | |
if [ -f $LOG_FILE ]; then | |
mv ${LOG_FILE} ${LOG_FILE}.1 | |
fi | |
touch $LOG_FILE | |
print_msg "INF: log rotate End" | |
# create snapshot | |
print_msg "INF: Create snapshot Start" | |
VOL_ID=`${EC2_CMD}/ec2-describe-instances --region=${REGION} ${INSTANCE_ID} | awk 'NR==3 {print $3}'` | |
if [ -z ${VOL_ID} ] ; then | |
print_msg "ERR: ec2-describe-instances" | |
logger -f ${LOG_FILE} | |
exit 1 | |
fi | |
print_msg "INF: ec2-describe-instances Success : ${VOL_ID}" | |
${EC2_CMD}/ec2-create-snapshot --region=${REGION} -d "Created by ${CREATE_MSG}(${INSTANCE_ID}) from ${VOL_ID}" ${VOL_ID} >> ${LOG_FILE} 2>&1 | |
if [ $? != 0 ] ; then | |
print_msg "ERR: ec2-create-snapshot" | |
logger -f ${LOG_FILE} | |
exit 1 | |
fi | |
print_msg "INF: Create snapshot End" | |
# delete old snapshot | |
print_msg "INF: Delete old snapshot Start" | |
SNAPSHOTS=`${EC2_CMD}/ec2-describe-snapshots --region=${REGION} | grep ${VOL_ID} | grep "Created by ${CREATE_MSG}" | wc -l` | |
while [ ${SNAPSHOTS} -gt ${SNAPSHOTS_PERIOD} ] | |
do | |
SNAPSHOT=`${EC2_CMD}/ec2-describe-snapshots --region=${REGION} | grep ${VOL_ID} | grep "Created by ${CREATE_MSG}" | sort -k 5,5 -r | awk 'NR==3 {print $2}'` | |
${EC2_CMD}/ec2-delete-snapshot --region=${REGION} ${SNAPSHOT} >> ${LOG_FILE} 2>&1 | |
if [ $? != 0 ] ; then | |
print_msg "ERR: ec2-delete-snapshot" | |
logger -f ${LOG_FILE} | |
exit 1 | |
fi | |
SNAPSHOTS=`${EC2_CMD}/ec2-describe-snapshots --region=${REGION} | grep ${VOL_ID} | grep "Created by ${CREATE_MSG}" | wc -l` | |
done | |
print_msg "INF: Delete old snapshot End" | |
print_msg "INF: END" | |
exit 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment