Created
June 6, 2015 07:46
-
-
Save Twinuma/3655e20186145c5d52d8 to your computer and use it in GitHub Desktop.
AMIのバックアップの取得
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 | |
DATE_CURRENT=`date +%Y-%m-%d` | |
TIME_CURRENT=`date +%Y%m%d%H%M%S` | |
PURGE_AFTER_DAYS=10 | |
PURGE_AFTER=`date -d +${PURGE_AFTER_DAYS}days -u +%Y-%m-%d` | |
# 1-1.バックアップを作成したいリソース一覧を取得する | |
INSTANCES=`aws ec2 describe-tags --filters "Name=resource-type,Values=instance" "Name=key,Values=Backup" | awk '{print $3}'` | |
for INSTANCE in ${INSTANCES}; do | |
BACKUP=`aws ec2 describe-tags --filters "Name=resource-type,Values=instance" "Name=resource-id,Values=${INSTANCE}" "Name=key,Values=Backup" | awk '{print $5}'` | |
# 1-2.タグを見てバックアップ対象かどうかチェックする | |
if [ "${BACKUP}" == "true" ]; then | |
# 1-3.バックアップを作成する | |
AMI_ID=`aws ec2 create-image --instance-id ${INSTANCE} --name "${INSTANCE}_${TIME_CURRENT}" --no-reboot` | |
# 1-4.検索に使うタグを作成する | |
aws ec2 create-tags --resources ${AMI_ID} --tags Key=PurgeAllow,Value=true Key=PurgeAfter,Value=$PURGE_AFTER | |
fi | |
done | |
# 2-1.タグを条件にして削除可能なバックアップを検索する | |
AMI_PURGE_ALLOWED=`aws ec2 describe-tags --filters "Name=resource-type,Values=image" "Name=key,Values=PurgeAllow" | awk '{print $3}'` | |
for AMI_ID in ${AMI_PURGE_ALLOWED}; do | |
PURGE_AFTER_DATE=`aws ec2 describe-tags --filters "Name=resource-type,Values=image" "Name=resource-id,Values=${AMI_ID}" "Name=key,Values=PurgeAfter" | awk '{print $5}'` | |
if [ -n ${PURGE_AFTER_DATE} ]; then | |
DATE_CURRENT_EPOCH=`date -d ${DATE_CURRENT} +%s` | |
PURGE_AFTER_DATE_EPOCH=`date -d ${PURGE_AFTER_DATE} +%s` | |
if [[ ${PURGE_AFTER_DATE_EPOCH} < ${DATE_CURRENT_EPOCH} ]]; then | |
# 2-2.タグを見て削除対象か判定を行い、対象であればバックアップを削除する | |
aws ec2 deregister-image --image-id ${AMI_ID} | |
SNAPSHOT_ID=`aws ec2 describe-images --image-ids ${AMI_ID} | grep EBS | awk '{print $4}'` | |
aws ec2 delete-snapshot --snapshot-id ${SNAPSHOT_ID} | |
fi | |
fi | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment