Blog Content

    티스토리 뷰

    AWS 인스턴스에 대한 스냅샷 백업 스크립트

     AWS 인스턴스에 대한 스냅샷 백업이 필요할 때 사용하는 스크립트 입니다.
    기본적으로 스냅샷생성 및 오래된 스냅샷 삭제처리 기능이 있습니다.

    참고로 메모리 내용까지는 스냅샷 백업이 되지 않기 때문에 DBMS 인스턴스에 사용하게 될 경우 check point 주기에 따라 일부 데이터 손실이 발생 할 수도 있습니다. NOSQL 의 MongoDB 에서는 저널설정을 on 한 경우에만 사용하시는게 좋습니다. (단 저널파일과 데이터 파일에 대한 EBS 볼륨이 나눠진 경우는 fsynclock 설정 후 스냅 샷 백업을 진행해야만 백업 정합성을 보장 합니다.)

    스크립트를 이용하기 위한 사전 작업으로는 스냅샷 백업을 위한 VOLUMES_LIST 항목을 아래와 같이 등록하여야 합니다.

    참고URL :  https://n2ws.com/how-to-guides/automate-amazon-ec2-instance-backup.html

    #!/bin/bash

    VOLUMES_LIST=/test/volumes-list
    SNAPSHOT_INFO=/test/snapshot_info
    DATE=`date +%Y-%m-%d`
    HDATE=`date +%Y%m%d_%H%M`
    REGION="ap-northeast-2"

    RETENTION=7

    SNAP_CREATION="/test/snap_creation"
    SNAP_DELETION="/test/snap_deletion"


    echo "===================================================================================" >> $SNAP_CREATION
    echo "===================================================================================" >> $SNAP_DELETION
    echo "List of Snapshots Creation Status" >> $SNAP_CREATION
    echo "List of Snapshots Deletion Status" >> $SNAP_DELETION

    if [ -f $VOLUMES_LIST ]; then

        for VOL_INFO in `cat $VOLUMES_LIST`
        do
            # Getting the Volume ID and Volume Name into the Separate Variables.
            VOL_ID=`echo $VOL_INFO | awk -F ":" '{print $1}'`
            VOL_NAME=`echo $VOL_INFO | awk -F ":" '{print $2}'`

            # Creating the Snapshot of the Volumes with Proper Description.
            DESCRIPTION="${VOL_ID}_${VOL_NAME}_${HDATE}"

            /usr/local/bin/aws ec2 create-snapshot --volume-id $VOL_ID --description "$DESCRIPTION" --region $REGION &>> $SNAP_CREATION
        done
    else
        #echo "Volumes list file is not available : $VOLUMES_LIST Exiting." | mail -s "Snapshots Creation Status" $EMAIL_LIST
        echo "Volumes list file is not available : $VOLUMES_LIST Exiting."
        exit 1
    fi

    #echo >> $SNAP_CREATION
    #echo >> $SNAP_CREATION

    echo "==============================================================================================================================" >> $SNAPSHOT_INFO
    # Deleting the Snapshots which are 10 days old.
    for VOL_INFO in `cat $VOLUMES_LIST`
    do
        # Getting the Volume ID and Volume Name into the Separate Variables.
        VOL_ID=`echo $VOL_INFO | awk -F ":" '{print $1}'`
        VOL_NAME=`echo $VOL_INFO | awk -F ":" '{print $2}'`

        # Getting the Snapshot details of each volume.
        /usr/local/bin/aws ec2 describe-snapshots --query Snapshots[*].[SnapshotId,VolumeId,Description,StartTime] --output text --filters "Name=status,Values=completed" "Name=volume-id,Values=$VOL_ID" | grep -v "CreateImage" >> $SNAPSHOT_INFO
        echo "------------------------------------------------------------------------------------------------------------------------------" >> $SNAPSHOT_INFO
        # Snapshots Retention Period Checking and if it crosses delete them.
        while read SNAP_INFO
        do
            SNAP_ID=`echo $SNAP_INFO | awk '{print $1}'`
            SNAP_DATE=`echo $SNAP_INFO | awk '{print $4}' | awk -F "T" '{print $1}'`
            #echo $SNAP_ID":"$SNAP_DATE

            # Getting the no.of days difference between a snapshot and present day.
            RETENTION_DIFF=`echo $(($(($(date -d "$DATE" "+%s") - $(date -d "$SNAP_DATE" "+%s"))) / 86400))`
            #echo $RETENTION_DIFF

            # Deleting the Snapshots which are older than the Retention Period
            if [ $RETENTION -lt $RETENTION_DIFF ];
            then
                /usr/local/bin/aws ec2 delete-snapshot --snapshot-id $SNAP_ID --region $REGION --output text > /nexon/snap_del
                echo DELETING $SNAP_INFO >> $SNAP_DELETION
            fi
        done < $SNAPSHOT_INFO
    done

    echo >> $SNAP_DELETION

    # Merging the Snap Creation and Deletion Data
    #cat $SNAP_CREATION $SNAP_DELETION > /var/log/mail_report

    # Sending the mail Update
    #cat /var/log/mail_report | mail -s "Volume Snapshots Status" $EMAIL_LIST

    하단의 URL 스크립트를 이용하면 자동으로 해당 인스턴스의 “리전정보”, “인스턴스ID”, “볼륨정보”를 찾아서 스냅샷 백업이 됩니다.
    참고하여 위 소스를 개선 하면 좋을 거 같습니다.
    https://github.com/CaseyLabs/aws-ec2-ebs-automatic-snapshot-bash

    # Get Instance Details
    instance_id=$(wget -q -O- http://169.254.169.254/latest/meta-data/instance-id)
    region=$(wget -q -O- http://169.254.169.254/latest/meta-data/placement/availability-zone | sed -e 's/\([1-9]\).$/\1/g')

     

    Comments