{Aurora}データを Aurora PostgreSQL DB クラスターから Amazon S3 にエクスポートする

現在、エクスポートは PostgreSQL 10.14、11.9、12.4 以降でサポートされています。

より大きなエクスポートは複数のファイルに格納され、それぞれの最大サイズは約 6 GB です。


-- 1. S3バケット作成

aws s3 mb s3://bucket123
aws s3 ls


-- 2. IAMポリシー作成
vim policy01.json


{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "s3export",
"Effect": "Allow",
"Action": [
"s3:PutObject"
],
"Resource": [
"arn:aws:s3:::bucket123/*"
]
}
]
}

aws iam create-policy \
--policy-name policy01 \
--policy-document file://policy01.json

-- 3. IAMロール作成
vim role01.json

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "rds.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}

aws iam create-role \
--role-name role01 \
--assume-role-policy-document file://role01.json


-- 4. ポリシーをロールにアタッチ
aws iam attach-role-policy \
--policy-arn arn:aws:iam::999999999999:policy/policy01 \
--role-name role01

-- 5. クラスタの作成

aws rds create-db-cluster \
--db-cluster-identifier cluster11 \
--engine aurora-postgresql \
--engine-version 12.6 \
--master-username postgres \
--master-user-password 'password'


aws rds create-db-instance \
--db-instance-identifier cluster11-instance01 \
--db-cluster-identifier cluster11 \
--db-instance-class db.t3.medium \
--engine aurora-postgresql \
--no-auto-minor-version-upgrade


-- 6. IAMロールをクラスタに関連付ける

aws rds add-role-to-db-cluster \
--db-cluster-identifier cluster11 \
--feature-name s3Export \
--role-arn arn:aws:iam::999999999999:role/role01

-- 7. PostgreSQL 拡張機能をインストール
CREATE EXTENSION aws_s3 CASCADE;

\dx

-- 8. テスト用テーブル、データ作成
create table tab1(col1 int,col2 varchar(100) );

insert into tab1 values(1,'AAA');
insert into tab1 values(2,'BBB');
insert into tab1 values(3,'CCC');

select * from tab1;

-- 9. エクスポート実行

SELECT * from aws_s3.query_export_to_s3('select * from tab1', aws_commons.create_s3_uri( 'bucket123', 'tab1.txt', 'ap-northeast-1' ), options :='format csv, delimiter $$,$$');


aws s3 ls s3://bucket123

aws s3 cp s3://bucket123/tab1.txt .

 

-- 10. クリーンアップ

-- ロールの一覧
aws iam list-roles | grep role01

-- ロールの削除

aws iam detach-role-policy \
--role-name role01 \
--policy-arn arn:aws:iam::999999999999:policy/policy01


aws iam delete-role --role-name role01

-- ポリシーの一覧
aws iam list-policies | grep policy01

-- ポリシーの削除
aws iam delete-policy \
--policy-arn arn:aws:iam::999999999999:policy/policy01


-- バケット一覧
aws s3 ls

-- バケット削除
aws s3 rb s3://bucket123 --force


-- クラスタ削除
aws rds delete-db-instance \
--db-instance-identifier cluster11-instance01 \
--skip-final-snapshot

aws rds delete-db-cluster \
--db-cluster-identifier cluster11 \
--skip-final-snapshot