AWS CLIでAmazon Aurora PostgreSQLをスナップショットから正しくリストアする方法

Amazon Aurora PostgreSQLのスナップショットからリストアした際に、

 

クラスターしか作られず、DBインスタンスがない

 

、という問題に直面しました。

 

AWS公式ドキュメントを確認すると、クラスターをリストア後にプライマリ(ライター)DBインスタンスを"作成"しなければいけないようです。

 

今回の記事では、AWS CLIを利用してAmazon Auroraの正しいリストア手順を実施し、元のデータを復元する方法を紹介します。

 

 

クラスターしか作られていない!

まず restore-db-cluster-from-snapshot を実行してクラスターをリストアしてみたところ、DB インスタンスが作成されず、PostgreSQLに接続できませんでした。

 

saitou-aurora-restore-awscliデータベース確認2

 

実際に psql で接続しようとすると、以下のエラーが発生。

 

[ec2-user@ip-10-0-1-223 ~]$ psql -h $HOST -p $PORT -U $DB_USER
psql: error: could not translate host name "saitou-database-1.cluster-<ランダム文字列>.ap-southeast-1.rds.amazonaws.com" to address: Name or service not known

 

元の状態に戻すために、ドキュメントを確認しながら復元してみます。

 

 

■1.前提条件

正しく復元を行うための環境・事前準備は以下の通りです。

 

●必要な環境

 

  • EC2インスタンス作成済み
    AWS CLIを実行するための環境です。

  • Aurora for PostgreSQL 作成済み
    スナップショットを取得するためのオリジナルのクラスターです。

  • AWS CLIインストール済み
    インストール方法はこちら

  • PostgreSQLクライアントのインストール済み
    インストール方法はこちら

 

●必要な IAM 権限

EC2インスタンスにアタッチするIAMロールには、以下のアクションを許可したポリシーを付与してください。
 

  • rds:CreateDBClusterSnapshot
  • rds:CreateDBInstance
  • rds:Describe*

 

 

■2.リストア前のサンプルデータ作成

スナップショットを作成する前に、サンプルデータを登録してリストア後に比較できるようにしておきます。

 

↓Auroraが作成されていることを確認します。

 

saitou-aurora-restore-awscliデータベース確認1

 

↓サーバからデータベースに接続します。

 

【コマンド】

DB_USER=postgres
PASSWORD=<パスワード>
HOST=saitou-database-1.cluster-<ランダム文字列>.ap-southeast-1.rds.amazonaws.com
PORT=5432
export PGPASSWORD=$PASSWORD

psql -h $HOST -p $PORT -U $DB_USER

 

【実行結果】

[ec2-user@ip-10-0-1-223 ~]$ psql -h $HOST -p $PORT -U $DB_USER
psql (16.6, server 16.4)
SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, compression: off)
Type "help" for help.

postgres=> 

 

↓つぎに、サンプルテーブルを作成します。

 

【コマンド】

CREATE TABLE sample_data (
    id SERIAL PRIMARY KEY,
    name TEXT NOT NULL,
    created_at TIMESTAMP DEFAULT now()
);

 

【実行結果】

postgres=> CREATE TABLE sample_data (
    id SERIAL PRIMARY KEY,
    name TEXT NOT NULL,
    created_at TIMESTAMP DEFAULT now()
);
CREATE TABLE
postgres=>

 

↓つづいて、データの挿入を実施します。

 

【コマンド】

INSERT INTO sample_data (name) VALUES
('Alice'),
('Bob'),
('Charlie');

 

【実行結果】

postgres=> INSERT INTO sample_data (name) VALUES
('Alice'),
('Bob'),
('Charlie');
INSERT 0 3
postgres=>

 

さいごに、データを確認しましょう。

 

↓【コマンド】

SELECT * FROM sample_data;

 

【実行結果】

postgres=> SELECT * FROM sample_data;
 id |  name   |         created_at
----+---------+----------------------------
  1 | Alice   | 2025-02-07 23:53:53.265513
  2 | Bob     | 2025-02-07 23:53:53.265513
  3 | Charlie | 2025-02-07 23:53:53.265513
(3 rows)

postgres=>

 

こちらで準備OKです。

 

 

■3.スナップショットの作成

リストアで利用するスナップショットを作成します。

 

↓サーバから以下のコマンドを実行します。

 

【コマンド】

aws rds create-db-cluster-snapshot \
    --db-cluster-snapshot-identifier <作成するスナップショット名> \
    --db-cluster-identifier <スナップショットを取得するクラスター名> \
    --region <リージョン>

 

【実行結果】

[ec2-user@ip-10-0-1-223 ~]$ aws rds create-db-cluster-snapshot \
    --db-cluster-snapshot-identifier saitou-database-1-cluster-snapshot \
    --db-cluster-identifier saitou-database-1 \
    --region ap-southeast-1
{
    "DBClusterSnapshot": {
        "AvailabilityZones": [
            "ap-southeast-1a",
            "ap-southeast-1b",
            "ap-southeast-1c"
        ],
        "DBClusterSnapshotIdentifier": "saitou-database-1-cluster-snapshot",
        "DBClusterIdentifier": "saitou-database-1",
        "SnapshotCreateTime": "2025-02-07T23:57:57.170000+00:00",
        "Engine": "aurora-postgresql",
        "EngineMode": "provisioned",
        "AllocatedStorage": 1,
        "Status": "creating",
        "Port": 0,
        "VpcId": "vpc-0c5cbf18254a8cb57",
        "ClusterCreateTime": "2025-02-07T23:42:47.158000+00:00",
        "MasterUsername": "postgres",
        "EngineVersion": "16.4",
        "LicenseModel": "postgresql-license",
        "SnapshotType": "manual",
        "PercentProgress": 0,
        "StorageEncrypted": false,
        "DBClusterSnapshotArn": "arn:aws:rds:ap-southeast-1:<ACCOUNT_ID>:cluster-snapshot:saitou-database-1-cluster-snapshot",
        "IAMDatabaseAuthenticationEnabled": false,
        "TagList": [],
        "DbClusterResourceId": "cluster-FLRMABTGXSE6xxxxxxxxxxxxxxx"
    }
}

 

↓作成したスナップショットが利用可能か、状態を確認します。

 
【コマンド】

aws rds describe-db-cluster-snapshots \
    --db-cluster-snapshot-identifier <作成したスナップショット名> \
    --region <リージョン> \
    --query "DBClusterSnapshots[0].Status"

 

【実行結果】

[ec2-user@ip-10-0-1-223 ~]$ aws rds describe-db-cluster-snapshots \
    --db-cluster-snapshot-identifier saitou-database-1-cluster-snapshot \
    --region ap-southeast-1 \
    --query "DBClusterSnapshots[0].Status"
"available"

 

"available" になったらリストア可能です。

 

 

■4.クラスターをスナップショットからリストア

それでは、クラスターをスナップショットからリストアしてみましょう。

 

↓以下のコマンド実行します。

 
【コマンド】

aws rds restore-db-cluster-from-snapshot \
    --db-cluster-identifier <リストア後のクラスター名> \
    --snapshot-identifier <作成したスナップショット名> \
    --engine aurora-postgresql \
    --db-subnet-group-name <クラスターが利用するサブネットグループ名> \
    --vpc-security-group-ids <クラスターが利用するセキュリティグループID> \
    --region <リージョン>

 

【実行結果】

[ec2-user@ip-10-0-1-223 ~]$ aws rds restore-db-cluster-from-snapshot \
    --db-cluster-identifier saitou-database-1-restored \
    --snapshot-identifier saitou-database-1-cluster-snapshot \
    --engine aurora-postgresql \
    --db-subnet-group-name default-vpc-0c5cbf18254a8cb57 \
    --vpc-security-group-ids sg-0d5694405acf09262 \
    --region ap-southeast-1
{
    "DBCluster": {
        "AllocatedStorage": 1,
        "AvailabilityZones": [
            "ap-southeast-1a",
            "ap-southeast-1b",
            "ap-southeast-1c"
        ],
        "BackupRetentionPeriod": 7,
        "DatabaseName": "testdb",
        "DBClusterIdentifier": "saitou-database-1-restored",
        "DBClusterParameterGroup": "default.aurora-postgresql16",
        "DBSubnetGroup": "default-vpc-0c5cbf18254a8cb57",
        "Status": "creating",
        "Endpoint": "saitou-database-1-restored.cluster-<ランダム文字列>.ap-southeast-1.rds.amazonaws.com",
        "ReaderEndpoint": "saitou-database-1-restored.cluster-ro-<ランダム文字列>.ap-southeast-1.rds.amazonaws.com",
        "MultiAZ": false,
        "Engine": "aurora-postgresql",
        "EngineVersion": "16.4",
        "Port": 5432,
        "MasterUsername": "postgres",
        "PreferredBackupWindow": "15:47-16:17",
        "PreferredMaintenanceWindow": "fri:19:37-fri:20:07",
        "ReadReplicaIdentifiers": [],
        "DBClusterMembers": [],
        "VpcSecurityGroups": [
            {
                "VpcSecurityGroupId": "sg-0d5694405acf09262",
                "Status": "active"
            }
        ],
        "HostedZoneId": "Z2G0U3KFCY8NZ5",
        "StorageEncrypted": false,
        "DbClusterResourceId": "cluster-PEIUOW33YN6TKLxxxxxxxxxxxxxxx",
        "DBClusterArn": "arn:aws:rds:ap-southeast-1:<ACCOUNT_ID>:cluster:saitou-database-1-restored",
        "AssociatedRoles": [],
        "IAMDatabaseAuthenticationEnabled": false,
        "ClusterCreateTime": "2025-02-08T01:01:30.705000+00:00",
        "EngineMode": "provisioned",
        "DeletionProtection": false,
        "HttpEndpointEnabled": false,
        "CopyTagsToSnapshot": false,
        "CrossAccountClone": false,
        "DomainMemberships": [],
        "TagList": [
            {
                "Key": "User",
                "Value": "saitou"
            }
        ],
        "AutoMinorVersionUpgrade": true,
        "DatabaseInsightsMode": "standard",
        "NetworkType": "IPV4",
        "LocalWriteForwardingStatus": "disabled",
        "EngineLifecycleSupport": "open-source-rds-extended-support"
    }
}

 

しかし、この時点ではクラスターしか作成されず、DBインスタンスは存在しないですね。

saitou-aurora-restore-awscliデータベース確認2

 

この時点で、データベースに接続を試みても、失敗します。

 

【実行結果】

[ec2-user@ip-10-0-1-223 ~]$ psql -h $HOST -p $PORT -U $DB_USER
psql: error: could not translate host name "saitou-database-1-restored.cluster-<ランダム文字列>.ap-southeast-1.rds.amazonaws.com" to address: Name or service not known

 

 

■5.DBインスタンスを手動で作成

Auroraクラスターには最低1つのプライマリ(ライター)DBインスタンスが必要です。リストア時には、クラスターリストア後にプライマリ(ライター)DBインスタンスを作成しなければいけません。

 

↓以下のコマンドで作成と、どのクラスターに紐づけるかを設定します。

 

【コマンド】

aws rds create-db-instance \
    --db-instance-identifier <作成するDBインスタンス名> \
    --db-cluster-identifier <リストアしたクラスター名> \
    --engine aurora-postgresql \
    --db-instance-class <インスタンスクラス> \
    --availability-zone <DBインスタンスを配置するAZ> \
    --db-subnet-group-name <DBインスタンスが利用するサブネットグループ名> \
    --region <リージョン>

 

【実行結果】

[ec2-user@ip-10-0-1-223 ~]$ aws rds create-db-instance \
    --db-instance-identifier saitou-database-1-instance-1-restored \
    --db-cluster-identifier saitou-database-1-restored \
    --engine aurora-postgresql \
    --db-instance-class db.t3.medium \
    --availability-zone ap-southeast-1a \
    --db-subnet-group-name default-vpc-0c5cbf18254a8cb57 \
    --region ap-southeast-1
{
    "DBInstance": {
        "DBInstanceIdentifier": "saitou-database-1-instance-1-restored",
        "DBInstanceClass": "db.t3.medium",
        "Engine": "aurora-postgresql",
        "DBInstanceStatus": "creating",
        "MasterUsername": "postgres",
        "DBName": "testdb",
        "AllocatedStorage": 1,
        "PreferredBackupWindow": "15:47-16:17",
        "BackupRetentionPeriod": 7,
        "DBSecurityGroups": [],
        "VpcSecurityGroups": [
            {
                "VpcSecurityGroupId": "sg-0d5694405acf09262",
                "Status": "active"
            }
        ],
        "DBParameterGroups": [
            {
                "DBParameterGroupName": "default.aurora-postgresql16",
                "ParameterApplyStatus": "in-sync"
            }
        ],
        "AvailabilityZone": "ap-southeast-1a",
        "DBSubnetGroup": {
            "DBSubnetGroupName": "default-vpc-0c5cbf18254a8cb57",
            "DBSubnetGroupDescription": "Created from the RDS Management Console",
            "VpcId": "vpc-0c5cbf18254a8cb57",
            "SubnetGroupStatus": "Complete",
            "Subnets": [
                {
                    "SubnetIdentifier": "subnet-0558f94ac765e38ed",
                    "SubnetAvailabilityZone": {
                        "Name": "ap-southeast-1a"
                    },
                    "SubnetOutpost": {},
                    "SubnetStatus": "Active"
                },
                {
                    "SubnetIdentifier": "subnet-077c98826e8ea5c5b",
                    "SubnetAvailabilityZone": {
                        "Name": "ap-southeast-1c"
                    },
                    "SubnetOutpost": {},
                    "SubnetStatus": "Active"
                },
                {
                    "SubnetIdentifier": "subnet-01a44699e0d4d6d37",
                    "SubnetAvailabilityZone": {
                        "Name": "ap-southeast-1c"
                    },
                    "SubnetOutpost": {},
                    "SubnetStatus": "Active"
                },
                {
                    "SubnetIdentifier": "subnet-0be2cf8d6cd984a51",
                    "SubnetAvailabilityZone": {
                        "Name": "ap-southeast-1a"
                    },
                    "SubnetOutpost": {},
                    "SubnetStatus": "Active"
                }
            ]
        },
        "PreferredMaintenanceWindow": "fri:14:28-fri:14:58",
        "PendingModifiedValues": {},
        "MultiAZ": false,
        "EngineVersion": "16.4",
        "AutoMinorVersionUpgrade": true,
        "ReadReplicaDBInstanceIdentifiers": [],
        "LicenseModel": "postgresql-license",
        "OptionGroupMemberships": [
            {
                "OptionGroupName": "default:aurora-postgresql-16",
                "Status": "in-sync"
            }
        ],
        "PubliclyAccessible": false,
        "StorageType": "aurora",
        "DbInstancePort": 0,
        "DBClusterIdentifier": "saitou-database-1-restored",
        "StorageEncrypted": false,
        "DbiResourceId": "db-QPEMKTE7NOJRxxxxxxxxxxxxxx",
        "CACertificateIdentifier": "rds-ca-rsa2048-g1",
        "DomainMemberships": [],
        "CopyTagsToSnapshot": false,
        "MonitoringInterval": 0,
        "PromotionTier": 1,
        "DBInstanceArn": "arn:aws:rds:ap-southeast-1:<ACCOUNT_ID>:db:saitou-database-1-instance-1-restored",
        "IAMDatabaseAuthenticationEnabled": false,
        "DatabaseInsightsMode": "standard",
        "PerformanceInsightsEnabled": false,
        "DeletionProtection": false,
        "AssociatedRoles": [],
        "TagList": [],
        "CustomerOwnedIpEnabled": false,
        "BackupTarget": "region",
        "NetworkType": "IPV4",
        "StorageThroughput": 0,
        "CertificateDetails": {
            "CAIdentifier": "rds-ca-rsa2048-g1"
        },
        "DedicatedLogVolume": false,
        "EngineLifecycleSupport": "open-source-rds-extended-support"
    }
}

 

作成されたか、マネジメントコンソールから見てみます。

 

saitou-aurora-restore-awscliデータベース確認3

saitou-aurora-restore-awscliデータベース確認4

 

無事に作成され、かつリストアしたクラスターに紐づいていますね。

 

 

■6.データが正しくリストアされたか確認

リストアは完了しましたが、データはどうなっているのでしょうか。

 

冒頭で作成したサンプルデータがあるか確認してみましょう。

 

↓データベースに接続します。

 

【コマンド】

DB_USER=postgres
PASSWORD=<パスワード>
HOST=saitou-database-1-restored.cluster-<ランダム文字列>.ap-southeast-1.rds.amazonaws.com
PORT=5432
export PGPASSWORD=$PASSWORD

psql -h $HOST -p $PORT -U $DB_USER

 

↓データを確認確認しましょう。

SELECT * FROM sample_data;

 

【実行結果】

[ec2-user@ip-10-0-1-223 ~]$ psql -h $HOST -p $PORT -U $DB_USER
psql (16.6, server 16.4)
SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, compression: off)
Type "help" for help.

postgres=> SELECT * FROM sample_data;
 id |  name   |         created_at
----+---------+----------------------------
  1 | Alice   | 2025-02-07 23:53:53.265513
  2 | Bob     | 2025-02-07 23:53:53.265513
  3 | Charlie | 2025-02-07 23:53:53.265513
(3 rows)

 

データが復元されていればOKです!

 

今回のAuroraのリストア方法の紹介は以上です。

 

 

■補足: 構成の差分チェック

クラスターのリストアやDBインスタンスを作成する際に、名前やインスタンスクラスを設定しますが、他の設定値が一緒なのか心配になりました。

 

その確認のため、簡単な構成チェックスクリプトを用意し、確認してみます。

 

↓まずは、元クラスター・元DBインスタンス、リストアクラスター・DBインスタンスの設定値を取得し、jsonファイルに出力します。

 
【コマンド】

aws rds describe-db-clusters \
    --db-cluster-identifier <元クラスター名> \
    --region <リージョン> \
    --output json > cluster_before.json

aws rds describe-db-clusters \
    --db-cluster-identifier <リストアクラスター名> \
    --region <リージョン> \
    --output json > cluster_after.json

aws rds describe-db-instances \
    --db-instance-identifier <元DBインスタンス名> \
    --region <リージョン> \
    --output json > instance_before.json

aws rds describe-db-instances \
    --db-instance-identifier <リストアで作成したDBインスタンス名>\
    --region <リージョン> \
    --output json > instance_after.json

 

つづいて、スクリプトを用意します。

 

aurora-diff.py

import json
import difflib

def load_json(filename):
    with open(filename, "r") as f:
        return json.load(f)

def compare_dicts(dict1, dict2, keys_to_check):
    differences = {}
    for key in keys_to_check:
        value1 = dict1.get(key)
        value2 = dict2.get(key)
        if value1 != value2:
            differences[key] = {"Before": value1, "After": value2}
    return differences

# 主要なクラスターの設定項目
cluster_keys = [
    "Engine", "EngineVersion", "DBClusterParameterGroup", "DBSubnetGroup", 
    "VpcSecurityGroups", "StorageEncrypted", "BackupRetentionPeriod",
    "DBClusterIdentifier"
]

# 主要なインスタンスの設定項目
instance_keys = [
    "DBInstanceClass", "AllocatedStorage", "StorageType", "MultiAZ",
    "Engine", "EngineVersion", "DBParameterGroups", "AvailabilityZone",
    "VpcSecurityGroups", "DBSubnetGroup", "DBInstanceIdentifier"
]

# クラスターの比較
cluster_before = load_json("cluster_before.json")["DBClusters"][0]
cluster_after = load_json("cluster_after.json")["DBClusters"][0]
cluster_diff = compare_dicts(cluster_before, cluster_after, cluster_keys)

# インスタンスの比較
instance_before = load_json("instance_before.json")["DBInstances"][0]
instance_after = load_json("instance_after.json")["DBInstances"][0]
instance_diff = compare_dicts(instance_before, instance_after, instance_keys)

print("Cluster Configuration Differences:")
print(json.dumps(cluster_diff, indent=4))

print("\nInstance Configuration Differences:")
print(json.dumps(instance_diff, indent=4))

 

スクリプトが作成できましたら、実行してみましょう。

 

[ec2-user@ip-10-0-1-223 ~]$ python aurora-diff.py
Cluster Configuration Differences:
{
    "DBClusterIdentifier": {
        "Before": "saitou-database-1",
        "After": "saitou-database-1-restored"
    }
}

Instance Configuration Differences:
{
    "DBInstanceIdentifier": {
        "Before": "saitou-database-1-instance-1",
        "After": "saitou-database-1-instance-1-restored"
    }
}

 

差分比較した結果を見ると、名前しか差分はなさそうですね。

 

 

まとめ

Auroraをリストアした際に、いつまでたってもDBインスタンスが起動せず、しばらく困りました。

 

しかし、以下の点をを理解していれば、スナップショットからのリストア時に混乱しないかと思います。

  • スナップショットからのリストアでは「Aurora クラスターのみ」復元される
  • DB インスタンス(ライター)は自動では復元されない
  • 手動で create-db-instance を実行し、クラスターにインスタンスを追加する必要がある

 

ぜひ試してみてください。

 

 

参考リンク:AWS公式ドキュメント

 

 

↓ほかの協栄情報メンバーもAmazon Auroraについての記事を公開しています。ぜひ参考にしてみてください。
 

IAMデータベース認証を利用し、Aurora PostgreSQLに接続する手順(齊藤弘樹)

 
EC2インスタンス(RHEL)からSecrets Managerを利用してAurora for PostgreSQL 16に接続する手順(齊藤弘樹)

 

 

 

Last modified: 2025-02-08

Author