Recent Posts
Recent Comments
Link
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
Tags
more
Archives
Today
Total
관리 메뉴

Sawadeekab

AMI 자동 백업 및 삭제 스크립트 본문

AWS

AMI 자동 백업 및 삭제 스크립트

Sawadeekab 2016. 11. 18. 17:39

#/bin/bash

### region setting (리전 선택)

region="us-west-1"


### Instance ID (백업할 AMI 인스턴스)

instanceID="AMI ID"


# AMI Description

amiDescription="Daily AMI backup"


# please set routine true otherwise set it false

routine=true


### Account_ID (계정 Account Number)

account="Account Number"


###Service (AMI 붙일 이름)

Service=zabbix_


# Time (AMI에 시간이 붙여짐)

today=$(date +%Y%m%d)

twoday_ago=`date +%Y%m%d -d $twoday_ago' -2days'`

nowtime=$(date +%Y/%m/%d_%H:%M)


echo $nowtime >> ami-backup.log

echo "start-ami-backup" >> ami-backup.log


# AMI Get AMI Name & AMI ID & Snapshot ID

if [ $routine = true ]; then

    # Get AMI Name (2틀 이전의 AMI 리스트를 가져옴)

    amiNAME=$(aws ec2 describe-images --image-ids --owners $account --query 'Images[*].{ID:Name}' | awk '{print $2}' | sed 's/"//g' | sed '/^$/d' | grep $Service | grep $twoday_ago)


    # Get AMI ID (2틀 이전의 AMI ID를 가져옴)

    amiID=$(aws ec2 describe-images --image-ids --owners $account --filters "Name=name,Values=$amiNAME" --query 'Images[*].{ID:ImageId}' | awk '{print $2}' | sed 's/"//g' | sed '/^$/d')


    # Get Snapshot ID (2틀 이전의 Snapshot 리스트를 가져옴)

    if [[ ! -z $amiNAME ]]; then

        snapshotID=$(aws ec2 describe-images --owners $account --filters "Name=name,Values=$amiNAME" --query 'Images[*].BlockDeviceMappings[*].{Ebs:*}'| grep SnapshotId  |awk '{print $2}' | sed 's/"//g' | sed 's/,//g')

    fi

fi


# Delete old image and snapshot (2틀 이전의 AMI와 Snapshot을 삭제 )

if [[ ! -z $amiID ]]; then

    # Delete AMI (2틀 이전의 AMI ID삭제)

    aws ec2 deregister-image --image-id $amiID


    # Delete snapshot (2틀 이전의 Snapshot 삭제)

    aws ec2 delete-snapshot --snapshot-id $snapshotID

fi

# Create AMI (오늘 날짜의 AMI를 생성)

aws ec2 create-image --instance-id $instanceID --name "$Service$amiName$today" --description "$amiDescription" --no-reboot


echo $nowtime >> ami-backup.log

echo "end-ami-backup" >> ami-backup.log