參考網路上的修改過
https://simplyopensource.blogspot.tw/2014/04/script-to-create-daily-ami-of-aws.html
https://github.com/colinbjohnson/aws-missing-tools/blob/master/ec2-automate-backup/ec2-automate-backup.sh
https://simplyopensource.blogspot.tw/2014/04/script-to-create-daily-ami-of-aws.html
https://github.com/colinbjohnson/aws-missing-tools/blob/master/ec2-automate-backup/ec2-automate-backup.sh
使用指令
amibackup.sh -i i-0102e3b13418794d4 -r ap-northeast-2 -d 1 >> /root/ami_backup/AmiBackupLog.log 2>&1
# ReadMe - How to use this script
# cyfbackup.sh -r [region] -i [instance name]
# -d [How may days ago to delete] -t [emulate today is how many days ago]
#Define TextColor Varible to use
#TextRedBgYellow="\e[0;31;43m"
TextGreen="\e[0;32m"
TextRed="\e[0;31m"
TextYellow="\e[0;33m"
TextBlue="\e[0;36m"
EndText="\e[0m"
#Define test_day for Emulate Today is some days ago.
declare -i test_day=0
#get Paramenter -d beforeDay2Del, -i InstanceID, -r Region
while getopts :d:i:r:t:end opt; do
case $opt in
d) remainDay=$OPTARG;;
i) instance_id=$OPTARG;;
r) region=$OPTARG;;
t) test_day=$OPTARG;;
*) echo "Option is invalid, Please check."; exit 1;;
esac
done
StartBackup()
{
echo -e "----------------------------------\n `date` \n----------------------------------"
#To create a unique AMI name for this script (Get From NameTag)
InstanceName=$(aws ec2 describe-instances --region $region --instance-id $instance_id \
--query 'Reservations[*].Instances[].[Tags[?Key==`Name`].Value]' \
| grep \" | cut -d "\"" -f 2)
if [[ ! $InstanceName ]];then
echo -e "\n[ ${TextRed}Warning${EndText} ] Instance's Name Tag has no value, Please Check!!\n"
echo -e "[ ${TextRed}Warning${EndText} ] AMI Backup Job Aborted.\n"
exit 1;
fi
# if Got paramenter -t 2 , then Emulate today is 2 days ago (what the AmiName to Create).
if [ $test_day -eq 0 ];then
DateToday=$(date +%Y%m%d)
else
DateToday=$(date -d "$test_day days ago" +%Y%m%d)
fi
AmiName2Create=${InstanceName}_$DateToday
# AmiTagName: Date 20170518 modify to 170518
AmiNameTagValue=${InstanceName}_$(echo $DateToday | cut -c 3-)
echo -e "Starting the Daily AMI creation: `echo $AmiName2Create`\n"
#To create AMI of defined instance
amiID=$(aws ec2 create-image --region $region --instance-id $instance_id --name $AmiName2Create \
--description "AutoBackup_$AmiName2Create" --no-reboot \
| grep -i ami | awk '{print $2}' | cut -d "\"" -f 2)
# Create AMI Name Tag
if [ $amiID ];then
aws ec2 create-tags --region $region --resources $amiID --tags Key=Name,Value=$AmiNameTagValue
AmiNameTagQuery=$(aws ec2 describe-tags --region $region --filters "Name=resource-id,Values=$amiID" \
| grep Value | awk {'print $2'} | cut -d "\"" -f 2)
#Showing the AMI ID , Name And NameTag created by AWS
echo -e "AMI ID is: `echo $amiID`\n"
echo -e "AMI Name is: `echo $AmiName2Create`\n"
echo -e "AMI Name Tag is: `echo $AmiNameTagQuery`\n"
# If create AMI not success (not get the AMI id) then abort.
else
echo -e "\n${TextRed}[ Error ]${EndText} Create AMI Error, Please Check Messages Above."
exit 1;
fi
}
# If Specify the day to remain, then delete ami and snapshots before the remain day, count 3 days.
ami_snap_del()
{
sleep 2
echo -e "Looking for AMI older than $remainDay days:\n "
# Range(set to 3 days) to delete AMI & snapshot which the day before you specify to remain.
declare -i delRange=$remainDay+2
echo "Remain Day = $remainDay"
echo "del Range = $delRange"
for (( i=$remainDay; i<=$delRange; i++ ))
do
#Define the value of AMI_Name older than 3 days which needed to be removed
amiName2del=${InstanceName}_$(date -d "$i days ago" +%Y%m%d)
echo "amiName2del = $amiName2del"
#Finding Image ID of instance by AMI_Name which needed to be Deregistered
amiID2del=$(aws ec2 describe-images --region $region --filters "Name=name,Values=$amiName2del" \
| grep -i imageid | cut -d "\"" -f 4)
#If Find the target AMI_Name to delete , then process delete.
if [ $amiID2del ];
then
echo -e "Following AMI is found : $amiID2del\n"
echo "This Snapshot will be deleted:$snap2del"
#Find the snapshots attached to the Image need to be Deregister
snap2del=$(aws ec2 describe-images --region $region --image-ids $amiID2del | grep snap | cut -d "\"" -f 4)
echo -e "Following are the snapshots associated with it : $snap2del:\n "
echo -e "Starting the Deregister of AMI... \n"
#Deregistering the AMI
echo "amiID2del: $amiID2del"
aws ec2 deregister-image --region $region --image-id $amiID2del
echo -e "\nDeleting the associated snapshots.... \n"
#Deleting snapshots attached to AMI
for n in $snap2del;
do aws ec2 delete-snapshot --snapshot-id $n ; done
else
echo -e "No AMI found older than minimum required no of days \n"
fi
done
echo -e "${TextBlue}Deleting Job Completed!!!${EndText}"
}
# Create Snapshot NameTag
CreateSnapTag()
{
sleep 5
#_ remove region paramanter
snapID=$(aws ec2 describe-images --image-ids $amiID | grep snap | cut -d "\"" -f 4)
if [ -n "$snapID" ];then
# For multiple snapshots
for snaps in $snapID;
do
# Create Snapshot NameTag
createSnapNametage=$(aws ec2 create-tags --region $region --resources $snaps \
--tags Key=Name,Value=$AmiNameTagValue)
# Get Snapshot NameTag
SnapNameTag=$(aws ec2 describe-tags --region $region --filters \
"Name=resource-id,Values=$snaps" \
| grep Value | awk {'print $2'} | cut -d "\"" -f 2)
echo -e "Snapshot ID is $snaps\n"
echo -e "Snapshot NameTag is $SnapNameTag \n"
done
# ReQuery SnapNameTag: May Cause Loop, Not Use Now
else
echo -e "Snapshot ID not Found, Please Set Snapshot's NameTag Manually."
fi
}
# Detect if Parameters: instance id, region has got or not, if yes, Starting Backup
if [ ! $instance_id ]; then
echo -e "\nPlease Specify Option with -i [instance id] -r [region]\n";
exit 1;
else
if [ ! $region ];then
echo -e "\nPlease Specify the region name with -r [region]\n"
exit 1;
else
# Set the AWS Default Region as User Specify
export AWS_DEFAULT_REGION=$region
StartBackup;
fi
fi
# [Create Snapshot NameTag] if amiID exist , Find Snapshot ID and then create Tag.
if [ $amiID ];then
echo -e "${TextYellow}Please wait 10 second to Create Snapshot NameTag...${EndText}\n"
CreateSnapTag;
echo -e "${TextBlue}$DateToday Backup Job Completed!!${EndText}\n"
fi
# [Delete Snapshot which ami is Deregisterd] if not specify the day to Remain, Ami and Snapshots will not to delete
if [ $remainDay ]; then
ami_snap_del;
fi