IK.AM

@making's tech note


AWS CLIとjqを使ってRDSの特定のインスタンスをshellスクリプトで起動・停止させる

🗃 {Dev/AWS/RDS}
🗓 Updated at 2014-03-13T02:43:39Z  🗓 Created at 2014-03-13T02:43:39Z   🌎 English Page

Jenkinsで定期的に停止させたり、ボタンポチで復帰させたりしたい

既にインスタンスは作成されている前提

db-instance-identifier=postgresql01というインスタンスを停止・起動させる例

停止

deleteしてsnapshotに保存。

#### ==== ここから変更可能 ====

# 対象のDB InstanceId
target=postgresql01

#### ==== ここまで変更可能 ====

status=`aws rds describe-db-instances | jq '.DBInstances | map(select(.DBInstanceIdentifier == "'"${target}"'"))[] | .DBInstanceStatus' | tr -d '"'`
snapshot=`aws rds describe-db-snapshots | jq '.DBSnapshots | map(select(.DBSnapshotIdentifier == "'"${target}"'"))[0] | .DBSnapshotIdentifier' | tr -d '"'`

## 既にsnapshotが存在しないかチェックする
if [ "${snapshot}" != "null" ]; then
  echo snapshot already exists!
  exit 0
fi

## RDSインスタンスの状態がavailableの場合に削除して、snapshotを作成する
if [ "${status}" == "available" ];then
  aws rds delete-db-instance --db-instance-identifier ${target} --final-db-snapshot-identifier ${target};
else 
  echo already stopped;
fi

定期的に落とすジョブを作ると、無駄な課金されずに済む。ちょっとしたテストに使いたい用途。

起動

snapshotからrestoreして、そのあとsnapshotを削除する。

#### ==== ここから変更可能 ====

# 対象のDB InstanceId
target=postgresql01

## ↓基本変えなくてよい↓

# DBサブネットグループ
sggroup=xxx (自分で設定した値)
# 状態変化待機間隔(秒)
waitsec=30

#### ==== ここまで変更可能 ====


## 対象のインスタンスが既に存在しているかチェック
status=`aws rds describe-db-instances | jq '.DBInstances | map(select(.DBInstanceIdentifier == "'"${target}"'"))[] | .DBInstanceStatus' | tr -d '"'`

if [ "${status}" == "deleting" ]; then
  echo wait deleting
  while [ "${status}" == "deleting" ];
  do
    echo ${status}
    sleep ${waitsec}
    status=`aws rds describe-db-instances | jq '.DBInstances | map(select(.DBInstanceIdentifier == "'"${target}"'"))[] | .DBInstanceStatus' | tr -d '"'`
  done
fi

if [ "${status}" != "" ];then
  echo instance exists!
  exit -1
fi

## snapshotからインスタンスの復帰
aws rds restore-db-instance-from-db-snapshot --db-instance-identifier ${target} --db-snapshot-identifier ${target} --db-subnet-group-name ${sggroup} --no-publicly-accessible

## statusがavailableになるまで待つ
status=`aws rds describe-db-instances | jq '.DBInstances | map(select(.DBInstanceIdentifier == "'"${target}"'"))[] | .DBInstanceStatus' | tr -d '"'`

echo until status is changed to available

while [ "${status}" != "available" ];
do
  echo ${status}
  sleep ${waitsec}
  status=`aws rds describe-db-instances | jq '.DBInstances | map(select(.DBInstanceIdentifier == "'"${target}"'"))[] | .DBInstanceStatus' | tr -d '"'`
done
    
## snapshotの削除

aws rds delete-db-snapshot --db-snapshot-identifier ${target}

✒️️ Edit  ⏰ History  🗑 Delete