経緯
今まではAuroraではないAWS RDSをCDで作成していました。
今回Auroraに変更することになり、CLIで作るのに戸惑ったのでメモとして残しておきます。
前提
- 毎日Auroraが自動スナップショットを作成している
- 復元元のDBクラスター名(RDSの場合はインスタンス名)はtest-rdsとする
リポジトリ
- こちらにサンプルを作成してます。
スナップショット名の取得
- 1行目で自動スナップショットから最新日付のスナップショット名は取得できます
- 
describe-db-cluster-snapshotsではダブルクウォテーションを含んでしまうのでsedで削除しています
Aurora
SNAPSHOT_NAME=`aws rds describe-db-cluster-snapshots --query "reverse(sort_by(DBClusterSnapshots[?DBClusterIdentifier=='test-rds'],&SnapshotCreateTime))[0].DBClusterSnapshotIdentifier"`
SNAPSHOT_NAME=`echo $SNAPSHOT_NAME | sed "s/\"//g"`
RDS
SNAPSHOT_NAME=`aws rds describe-db-snapshots --query "reverse(sort_by(DBSnapshots[?DBInstanceIdentifier=='test-rds'],&SnapshotCreateTime))[0].DBSnapshotIdentifier"`
SNAPSHOT_NAME=`echo $SNAPSHOT_NAME | sed "s/\"//g"`
スナップショットから復元
- 
$SNAPSHOT_NAMEはスナップショット名の取得から持ってきています。単純にスナップショットから復元したい場合はここをベタ書きすればOKです。
- インスタンスの存在チェックも行っています
- AuroraはClusterとインスタンス両方する必要があります
Aurora
rds_cluster_exists=`aws rds restore-db-cluster-from-snapshot --snapshot-identifier $SNAPSHOT_NAME --db-cluster-identifier "作りたいcluster名" --engine "aurora-postgresql" --engine-version "11.6" --db-subnet-group-name "xxxx" --vpc-security-group-ids "xxxx" --db-cluster-parameter-group-name "xxxx"` || true
echo "rds_cluster_exists='$rds_cluster_exists'"
if [[ $rds_cluster_exists =~ 'DBClusterAlreadyExistsFault' ]] ;
then
  echo 'DBClusterAlreadyExistsFault !!'
fi
rds_instance_exists=`aws rds create-db-instance --db-cluster-identifier "上記で指定したcluster名" --db-instance-identifier "作りたいインスタンス名" --db-instance-class db.t2.small --engine aurora-postgresql --publicly-accessible 2>&1` || true
echo "rds_instance_exists='$rds_instance_exists'"
if [[ $rds_instance_exists =~ 'DBInstanceAlreadyExists' ]] ;
then
  echo 'DBInstanceAlreadyExists !!'
fi
RDS
rds_instance_exists=`aws rds restore-db-instance-from-db-snapshot --db-snapshot-identifier $SNAPSHOT_NAME --db-instance-identifier "作りたいインスタンス名" --db-subnet-group-name "xxxx" --db-instance-class db.t2.small --vpc-security-group-ids "xxxx" --db-parameter-group-name "xxxx" --publicly-accessible 2>&1` || true
echo "rds_instance_exists='$rds_instance_exists'"
if [[ $rds_instance_exists =~ 'DBInstanceAlreadyExists' ]] ;
then
  echo 'DBInstanceAlreadyExists !!'
fi
おまけ:復元完了を待つ
- 例えば復元した後でマイグレーションをかけたいなどCDでやりたいこともあると思います
- その場合には復元完了を待つ必要がありますのでそのやり方です
Aurora
- 
aws rds waitコマンドを実行しますが、これは何分か(正確な数値は忘れましたw)待ってまだできていない場合は処理が終了してしまいます。
- そこでループで終わるまで待つようにしています
- Auroraの作成って1時間弱かかるイメージなので、aws rds waitだけだと不十分なんですよね
rds_wait="1"
while [ $rds_wait != "0" ]
do
  rds_wait=`aws rds wait db-instance-available --db-instance-identifier "上記で作成したインスタンス名"; echo $?`
  rds_wait=`echo $rds_wait | tail -n1`
  echo "waiting..."
  sleep 1
done
RDS
- RDSはすぐに作成されるので、以下のみでOKです
aws rds wait db-instance-available --db-instance-identifier "上記で作成したインスタンス名"