LinuxディレクトリをS3にバックアップ

指定したディレクトリ配下に存在するディレクトリを*.tar.gz形式でS3にバックアップするスクリプトを作成したので、備忘録として残します。

#!/bin/bash
BKPath="/hoge/hoge/"      #バックアップ対象ディレクトリを記載
Credential_profile="hoge" #認証プロファイルを記載(空欄も可)
s3_bucket_Name="fugaguga" #保存先S3バケット名記載
BK_retention_days=7       #バックアップ保持日数を記載
AWS_CLI_Path="/usr/local/bin/"

#変数設定値確認(空の場合は処理終了)
if [ -z "$BKPath" ]; then
    logger -p user.err "BKPath is not set"
     exit
fi

if [ -z "$s3_bucket_Name" ]; then
    logger -p user.err "s3_bucket_Name is not set"
    exit
fi

#プロファイル設定
if [ -n "$Credential_profile" ]; then
    export AWS_PROFILE=${Credential_profile}
fi

#S3内のバケット一覧取得
str=`${AWS_CLI_Path}aws s3 ls 2>&1`
#取得時のエラー処理
if [ $? != 0 ]; then
    logger -p user.err ${str}
    exit
fi

#S3バケット作成確認
if [[ $str != *${s3_bucket_Name}* ]]; then
    result=`${AWS_CLI_Path}aws s3 mb s3://${s3_bucket_Name} 2>&1`
    if [ $? != 0 ]; then
        logger -p user.err ${result}
        exit
    fi
fi

#BK対象となるディレクトリを検索
BKDirs=`ls -l ${BKPath} 2>&1`
if [ $? != 0 ]; then
    logger -p user.err "${BKDirs}"
    exit
fi

#BK対象のディレクトリ抽出・対象確認
BKDirs=`ls -l ${BKPath} | grep ^d| awk '{print $9}'`
if [ -z "$BKDirs" ]; then
    logger -p user.notice "The directory to be compressed did not exist in ${BKDirs}"
    exit
fi

#圧縮ファイルをS3に転送
str_date=`date +'%Y-%m-%d'`
for BKDir in ${BKDirs}
do
  tar czf "/tmp/${BKDir}-${str_date}.tar.gz" "${BKPath}${BKDir}"
  ${AWS_CLI_Path}aws s3 cp "/tmp/${BKDir}-${str_date}.tar.gz" "s3://${s3_bucket_Name}/${BKDir}-${str_date}.tar.gz" --expires `date -d "${BK_retention_days} day" +'%Y-%m-%dT%H:%M:%SZ'` --acl private --storage-class ONEZONE_IA
  rm "/tmp/${BKDir}-${str_date}.tar.gz"
done

※実行前にAWSCLIの認証情報を設定する必要があります。

aws configure --profile hoge
AWS Access Key ID [None]:
AWS Secret Access Key [None]:
Default region name [None]:
Default output format [None]:

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

日本語が含まれない投稿は無視されますのでご注意ください。(スパム対策)