4
2

More than 5 years have passed since last update.

RDSスナップショットを別のリージョンにコピーするラムダ(Python3.7)

Posted at

RDSのスナップショットを別リージョンにコピーするラムダ関数の備忘録です。
Python 3.7で、環境変数に以下をセットしています。Javascriptでやろうとしましたが、PythonがシンプルだったのでPython素人ですが採用しました。

Key 説明
DESTINATION_REGION コピー先のリージョン名(ex:us-east-1)
AWS のリージョンとエンドポイント

AWSの公式でも公開してました。2017/8/28の記事ですが、現在(2019/6/22)でも有効です。
Cross-Region Automatic Disaster Recovery on Amazon RDS for Oracle Database Using DB Snapshots and AWS Lambda

import botocore
import json
import boto3
import os

destinationRegion = os.environ['DESTINATION_REGION']

def lambda_handler(event, context):

     sourceRegion = event['region']

     rds = boto3.client('rds', region_name = destinationRegion)

     #Build the Snapshot ARN - Always use the ARN when copying snapshots across region.
     sourceSnapshotARN = event['detail']['SourceArn']
     sourceSnapshotARN = sourceSnapshotARN.replace(":db:", ":snapshot:")

     #build a new snapshot name
     sourceSnapshotIdentifer = event['detail']['SourceIdentifier']
     targetSnapshotIdentifer = "{0}-ManualCopy".format(sourceSnapshotIdentifer)
     targetSnapshotIdentifer = targetSnapshotIdentifer.replace(":","-")

     #Execute copy
     try:
         copy = rds.copy_db_snapshot(
             SourceDBSnapshotIdentifier = sourceSnapshotARN,
             TargetDBSnapshotIdentifier = targetSnapshotIdentifer,
             SourceRegion = sourceRegion)
         print("Started Copy of Snapshot {0} in {2} to {1} in {3} ".format(
             sourceSnapshotIdentifer,
             targetSnapshotIdentifer,
             sourceRegion,destinationRegion)
         )
     except botocore.exceptions.ClientError as ex:
         if ex.response['Error']['Code'] == 'DBSnapshotAlreadyExists':
             print("Snapshot {0} already exist".format(targetSnapshotIdentifer))
         else:
             print("ERROR: {0}".format(ex.response['Error']['Code']))

     return {
         'statusCode': 200,
         'body': json.dumps('Opearation Complete')
     }

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