LoginSignup
1
2

More than 5 years have passed since last update.

RDS をスナップショットからリストアしたときに利用可能(available)になるのを待ってセキュリティグループを変更するシェルスクリプト

Posted at

下記の記事のように RDS をシェルスクリプトで削除→リストアしようとしたところ、

なぜか --vpc-security-group-ids が指定できませんでした。

しかも、セキュリティグループはリストアを開始した後、利用可能になるまで変更できないようです。

なので、最新のスナップショットからリストアをしつつ、利用可能になるまで待って、セキュリティグループを変更するシェルスクリプトを作成しました。

#!/bin/bash

set -eu

function rds_start()
{
    for id in "$@"; do
        aws rds describe-db-instances \
            --db-instance-identifier "$id" \
            --query "DBInstances[].DBInstanceStatus" \
            --output text >/dev/null 2>&1 &&:

        if [ $? -eq 0 ]; then
            echo "rds $id has been created"
        else
            snapshot=$(aws rds describe-db-snapshots \
                --query "reverse(sort_by(DBSnapshots,&SnapshotCreateTime))
                    [?DBInstanceIdentifier==\`${id}\`]|[0].[DBSnapshotIdentifier]" \
                --output text)

            echo "rds $id restore from $snapshot"

            aws rds restore-db-instance-from-db-snapshot \
                --db-instance-identifier "${id}" \
                --db-snapshot-identifier "${snapshot}" \
                --db-instance-class "db.t2.micro" \
                --db-subnet-group-name "ore-subnet" \
                --no-multi-az \
                --no-publicly-accessible \
                --no-auto-minor-version-upgrade \
                --storage-type gp2 > /dev/null
        fi
    done
}

function rds_wait()
{
    for id in "$@"; do
        echo -n "rds $id wait for available"
        while :; do
            status=$(aws rds describe-db-instances \
                --db-instance-identifier "$id" \
                --query "DBInstances[].DBInstanceStatus" \
                --output text)

            if [ "$status" == "available" ]; then
                echo " now $status"
                break
            fi

            echo -n .
            sleep 1
        done
    done
}

function rds_sg()
{
    for id in "$@"; do
        echo "rds $id modify security-group"

        sg=$(aws ec2 describe-security-groups \
            --filter 'Name=group-name,Values=ore-group' \
            --query 'SecurityGroups[].GroupId' \
            --output text)

        aws rds modify-db-instance \
            --db-instance-identifier "$id" \
            --vpc-security-group-ids "$sg" \
            --apply-immediately > /dev/null
    done
}

function rds_start_wait_sg()
{
    rds_start "$@"
    rds_wait "$@"
    rds_sg "$@"
}

rds_start_wait_sg ore-db are-db

インスタンスのサイズとか、サブネットグループの名前とか、セキュリティグループの名前とかはベタ書きしているので、変更する必要があります。

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