LoginSignup
4
4

More than 5 years have passed since last update.

DataPipelineでEC2インスタンスのバックアップと停止してみた

Posted at

開発サーバーとして利用している、EC2インスタンスのバックアップと日々の停止処理をDataPipelineを利用して行ってみました。

DataPipelineの使い方としては、こちらの記事のようにシェルスクリプトのスケジューラとして利用しただけです。

DataPipelineの設定としては、ActivityにShellCommandActivityを選択し、ResourceにはEC2インスタンスを自VPCで起動するようにします。

ActivityのCommand欄に下記のシェルスクリプトを設定します。

#!/bin/sh

backup(){
    type=$1
    ami_name=$2

    # 指定タグの起動中のインスタンスIDを取得
    InstanceId=`aws ec2 describe-instances --region ap-northeast-1 --filters "Name=tag:type,Values=${type}" "Name=instance-state-name,Values=running" | grep InstanceId | awk -F : '{print $2}' | sed -e 's/[ ",]//g' | sed -n '1p'`

    if [ ${InstanceId} ];then
        # 前日分のami_id取得
        OldImageId=`aws ec2 describe-images --region ap-northeast-1 --filters Name=tag:type,Values=${type} | grep ImageId | awk -F : '{print $2}' | sed -e 's/[ ",]//g' | sed -n '1p'`
        # 前日分のsnapshot_id取得
        OldSnapshotId=`aws ec2 describe-images --region ap-northeast-1 --filters Name=tag:type,Values=${type} | grep SnapshotId | awk -F : '{print $2}' | sed -e 's/[ ",]//g' | sed -n '1p'`
        # 前日分のami削除
        if [ ${OldImageId} ];then
            aws ec2 deregister-image --region ap-northeast-1 --image-id ${OldImageId}
        fi
        # 前日分のsnapshot削除
        if [ ${OldSnapshotId} ];then
            aws ec2 delete-snapshot --region ap-northeast-1 --snapshot-id ${OldSnapshotId}
        fi

        # ami作成
        today=`date '+%Y%m%d%H%M%S'`
        CurrentImageId=`aws ec2 create-image --region ap-northeast-1 --instance-id ${InstanceId} --name "${ami_name}-${today}" --no-reboot | grep ImageId | awk -F : '{print $2}' | sed -e 's/[ "]//g'`
        if [ ${CurrentImageId} ];then
            # amiにタグつけ
            aws ec2 create-tags --region ap-northeast-1 --resources ${CurrentImageId} --tags Key=type,Value=${type}
        fi
    fi
}

stop_instance(){
    type=$1

    # 指定タグの起動中のインスタンスIDを取得
    InstanceId=`aws ec2 describe-instances --region ap-northeast-1 --filters "Name=tag:type,Values=${type}" "Name=instance-state-name,Values=running" | grep InstanceId | awk -F : '{print $2}' | sed -e 's/[ ",]//g' | sed -n '1p'`

    if [ ${InstanceId} ];then
        # インスタンス停止
        stop=`aws ec2 stop-instances --region ap-northeast-1 --instance-ids ${InstanceId}`
    fi
}

# ec2 backup
backup [ec2_tag] [ami_name]
stop_instance [ec2_tag]

シェル末尾のec2_tagとami_nameを置き換えると、起動中のインスタンスのamiを取り、そのインスタンスを停止します。

操作したいインスタンスには、あらかじめtypeというタグにec2_tagと同じ名前のタグ名をつけておきます。
ami_nameは作成するamiのprefixになり、末尾に日時文字列がくっつきます。

読みにくいコードでごめんなさい。
あと本当はインスタンス止めてからamiとったほうがいいと思うので、そのうちなおすかも。

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4