7 月
28
2014
28
2014
使用Shell Script自動建立AWS AMI Image備份

我已經將這個shell script放上github,方便維護與更新 https://github.com/henrychen95/AWS-AMI-Auto-Backup
使用AWS的時候,建立AMI Image算是一個不錯的備份方式,下面我分享使用AWS內建的指令來進行備份
必備條件
- 必須安裝AWS tools,可以使用 yum install aws* 來進行安裝所有需要的套件。
- 請確認你的AWS tools路徑,預設會是在/opt/aws/bin,如果你的路徑不相同,請修改Shell Script的第二行。
- 請確認你的EC2_HOME路徑,可以使用 env | grep EC2_HOME 來確認。
- 請確認你的JAVA_HOME路徑,可以使用 env | grep JAVA_HOME 來確認。
- 請建立適當權限的IAM Role,並且在啟動instance的時候加入IAM Role。如果你對於IAM Role不熟悉,可以建立admin IAM Role來快速使用。
這個Shell Script可以設定以下變數
- region: 填入要備份的region
- instanceID: 填入要備份的instance
- amiNamePrefix: 填入你希望使用的AMI名稱
- amiDescription: 填入你希望使用的AMI描述
- routine: 如果設定為true,那麼會在amiNamePrefix後面加上Mon, Tue…這樣的文字來當作AMI名稱,並且會保留7天的備份
這個shell script會刪除舊的AMI和snapshot來節省空間
#!/bin/bash PATH=/sbin:/bin:/usr/sbin:/usr/bin:/opt/aws/bin # Please use env | grep EC2_HOME to find out your system's setting EC2_HOME=/opt/aws/apitools/ec2 # Please use env | grep JAVA_HOME to find out your system's setting JAVA_HOME=/usr/lib/jvm/jre export EC2_HOME JAVA_HOME # Regions reference: http://docs.aws.amazon.com/general/latest/gr/rande.html region="ap-northeast-1" # You can find your instance ID at AWS Manage Console instanceID="YOUR-INSTANCE-ID" # Your prefer AMI Name prefix amiNamePrefix="AMI_" # Your prefer AMI Description amiDescription="Daily AMI backup" # If you want to keep 7 days AMI backups, please set routine true otherwise set it false routine=true # Variable for routine is true weekday=$(date +%a) if [ $routine = true ]; then # Setup AMI Name amiName=$amiNamePrefix$weekday # Get AMI ID amiIDs=$(ec2-describe-images --region $region | grep 'ami-[a-z0-9]' | grep "$amiName" |cut -f 2) # Get Snapshot ID if [[ ! -z $amiIDs ]]; then snapshotIDs=$(ec2-describe-snapshots --region $region | grep $amiIDs | cut -f 2) fi else # Setup AMI Name amiName=$amiNamePrefix # Get AMI ID amiIDs=$(ec2-describe-images --region $region | grep 'ami-[a-z0-9]' | cut -f 2) # Get Snapshot ID if [[ ! -z $amiIDs ]]; then snapshotIDs=$(ec2-describe-snapshots --region $region | cut -f 2) fi fi if [[ ! -z $amiIDs ]]; then # Deregister AMI for amiID in $amiIDs do ec2-deregister --region $region $amiID done # Delete snapshot for snapshotID in $snapshotIDs do ec2-delete-snapshot --region $region $snapshotID done fi # Create AMI ec2-create-image $instanceID --region $region --name "$amiName" -d "$amiDescription" --no-reboot
- 我們可以把這個shell script存成/root/createAMI.sh
- 然後執行 chmod 755 /root/createAMI.sh
- 接著新增一筆排程,就可以自動進行AMI的備份
標籤: AMI, AWS, ec2-delete-snapshot, ec2-deregister, ec2-describe-images, ec2-describe-snapshots, shell script