LoginSignup
2
1

More than 5 years have passed since last update.

AWS EC2でオートスケール時にファイルをS3へ退避させる

Posted at

OSのシャットダウン処理を追加します。

ここではログディレクトリの圧縮ファイルをS3へ転送します

1.インスタンス起動時に以下のシェルを実行する

転送先のS3パスと退避させたいローカルディレクトリを指定して下さい
sample.sh
cat << 'EOW' >/etc/init.d/instance-lifecycle
#!/bin/bash
# chkconfig: 2345 99 1
# description: インスタンス縮退時にログをS3に退避させる

S3_PATH='' #転送先のS3パス
DIR_NAME='' #退避させたいローカルディレクトリ
TIMESTAMP=`date +"%Y%m%d%H%M%S"`
INSTANCE_ID=`curl http://169.254.169.254/latest/meta-data/instance-id/`
COMPRESS_FILE_NAME="terminate_${INSTANCE_ID}_${TIMESTAMP}.tar.gz"

case "$1" in
  start)
    touch /var/lock/subsys/instance-lifecycle
    ;;
  stop)
    cd /home/ec2-user
    tar -zcvf ${COMPRESS_FILE_NAME} ${DIR_NAME}
    aws s3 cp ${COMPRESS_FILE_NAME} ${S3_PATH}
    rm -f /var/lock/subsys/instance-lifecycle
    ;;
  *) break ;;
esac
EOW

2.以下のコマンドでserviceに登録します

chmod 700 /etc/init.d/instance-lifecycle
chkconfig --add instance-lifecycle
chkconfig instance-lifecycle on
service instance-lifecycle start
参考

2
1
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
2
1