本页内容
- 先决条件
- 我们要做什么
- 检查先决条件
- 创建脚本
- 执行脚本。
- 结论
你可以使用 Python 将数据项从一个 DynamoDB 表复制到另一个表。同样的脚本也可用于在不同账户的 DynamoDB 表之间复制数据项。在继续阅读本文之前,假设你对 Python 有基本的了解。你无需自己编写任何内容,只需执行脚本即可完成复制操作。如果你想理解脚本及其中的代码,那么你需要具备 Python 的基础知识。
你可以在任何能够联网且安装了 Python 的机器上运行此脚本。你的系统上需要安装 Python 和 Boto3。此脚本已在 Python 2.7.16 上测试通过,你也可以尝试使用 Python 2.7 中的其他可用版本。
AWS Data Pipeline 服务也可用于将数据项从一个 DynamoDB 表复制到另一个表,但这一过程略显繁琐。因此,我自行编写了这个脚本来简化该任务。
现在,让我们开始吧。
先决条件
- 具备 Python 基础知识。
- Linux 服务器上安装 Python 2.7.16 和 Boto3。
- AWS 账户(如果没有,请创建一个)。
- 拥有对 DynamoDB 具备足够/完整权限的 AWS IAM 用户的 'access_key' 和 'secret_key'。(点击此处了解如何在 AWS 上创建带有 'access_key' 和 'secret_key' 的 IAM 用户。)
我们要做什么
- 检查先决条件。
- 创建脚本。
- 执行脚本。
检查先决条件
检查 Python
python --version

检查 Pip
pip --version

检查 Boto3
pip show boto3

创建脚本
在你的本地系统上用以下代码创建一个新文件。代码也可在我的 Github 仓库中获取。以下是 Github 上代码的链接。
Github 链接:https://github.com/shivalkarrahul/DevOps/blob/master/aws/python/aws-copy-dynamo-db-table/copy-dynamodb-table.py
文件:copy-dynamodb-table.py
import boto3
import os
import sys
import argparse
import datetime
global args
parser = argparse.ArgumentParser()
parser.add_argument('-sa', '--source_aws_access_key_id', required=True, action="store", dest="source_aws_access_key_id",
help="Source AWS Account aws_access_key_id", default=None)
parser.add_argument('-ss', '--source_aws_secret_access_key', required=True, action="store", dest="source_aws_secret_access_key",
help="Source AWS Account aws_secret_access_key", default=None)
parser.add_argument('-da', '--destination_aws_access_key_id', required=True, action="store", dest="destination_aws_access_key_id",
help="Destination AWS Account aws_access_key_id", default=None)
parser.add_argument('-ds', '--destination_aws_secret_access_key', required=True, action="store", dest="destination_aws_secret_access_key",
help="Destination AWS Account aws_secret_access_key", default=None)
parser.add_argument('-st', '--sourceTableName', required=True, action="store", dest="sourceTableName",
help="Source AWS Account DyanamoDB Table", default=None)
parser.add_argument('-dt', '--destinationTableName', required=True, action="store", dest="destinationTableName",
help="Destination AWS Account DyanamoDB Table", default=None)
args = parser.parse_args()
source_aws_access_key_id = args.source_aws_access_key_id
source_aws_secret_access_key = args.source_aws_secret_access_key
destination_aws_access_key_id = args.destination_aws_access_key_id
destination_aws_secret_access_key = args.destination_aws_secret_access_key
sourceTableName=args.sourceTableName
destinationTableName=args.destinationTableName
sourceTableExists = "false"
destinationTableExists = "false"
print("Printing values")
print("source_aws_access_key_id", source_aws_access_key_id)
print("source_aws_secret_access_key", source_aws_secret_access_key)
print("destination_aws_access_key_id", destination_aws_access_key_id)
print("destination_aws_secret_access_key", destination_aws_secret_access_key)
print("sourceTableName", sourceTableName)
print("destinationTableName", destinationTableName)
timeStamp = datetime.datetime.now()
backupName = destinationTableName + str(timeStamp.strftime("-%Y_%m_%d_%H_%M_%S"))
item_count = 1000 #Specify total number of items to be copied here, this helps when a specified number of items need to be copied
counter = 1 # Don't not change this
source_session = boto3.Session(region_name='eu-west-3', aws_access_key_id=source_aws_access_key_id, aws_secret_access_key=source_aws_secret_access_key)
source_dynamo_client = source_session.client('dynamodb')
target_session = boto3.Session(region_name='eu-west-3', aws_access_key_id=destination_aws_access_key_id, aws_secret_access_key=destination_aws_secret_access_key)
target_dynamodb = target_session.resource('dynamodb')
dynamoclient = boto3.client('dynamodb', region_name='eu-west-3', #Specify the region here
aws_access_key_id=source_aws_access_key_id, #Add you source account's access key here
aws_secret_access_key=source_aws_secret_access_key) #Add you source account's secret key here
dynamotargetclient = boto3.client('dynamodb', region_name='eu-west-3', #Specify the region here
aws_access_key_id=destination_aws_access_key_id, #Add you destination account's access key here
aws_secret_access_key=destination_aws_secret_access_key) #Add you destination account's secret key here
# response = dynamotargetclient.list_tables()
# print("List of tables", response)
dynamopaginator = dynamoclient.get_paginator('scan')
def validateTables(sourceTable, destinationTable):
print("Inside validateTables")
try:
dynamoclient.describe_table(TableName=sourceTable)
sourceTableExists = "true"
except dynamotargetclient.exceptions.ResourceNotFoundException:
sourceTableExists = "false"
try:
dynamotargetclient.describe_table(TableName=destinationTable)
destinationTableExists = "true"
except dynamotargetclient.exceptions.ResourceNotFoundException:
destinationTableExists = "false"
return {'sourceTableExists': sourceTableExists, 'destinationTableExists':destinationTableExists}
def copyTable(sourceTable, destinationTable,item_count,counter):
print("Inside copyTable")
print("Coping", sourceTable, "to", destinationTable)
print('Start Reading the Source Table')
try:
dynamoresponse = dynamopaginator.paginate(
TableName=sourceTable,
Select='ALL_ATTRIBUTES',
ReturnConsumedCapacity='NONE',
ConsistentRead=True
)
except dynamotargetclient.exceptions.ResourceNotFoundException:
print("Table does not exist")
print("Exiting")
sys.exit()
print('Finished Reading the Table')
print('Proceed with writing to the Destination Table')
print("Writing first", item_count , "items" )
print(dynamoresponse)
for page in dynamoresponse:
for item in page['Items']:
if (counter == item_count):
print("exiting")
sys.exit()
else:
print('writing item no', counter)
dynamotargetclient.put_item(
TableName=destinationTable,
Item=item
)
counter = counter + 1
def backupTable(destTableName, backupTimeStamp):
print("Inside backupTable")
print("Taking backup of = ", destTableName)
print("Backup Name = ", backupTimeStamp)
response = dynamotargetclient.create_backup(
TableName=destTableName,
BackupName=backupTimeStamp
)
print("Backup ARN =", response["BackupDetails"]["BackupArn"])
def deleteDestinationTable(destTableName):
print("Inside deleteDestinationTable")
try:
dynamotargetclient.delete_table(TableName=destTableName)
waiter = dynamotargetclient.get_waiter('table_not_exists')
waiter.wait(TableName=destTableName)
print("Table deleted")
except dynamotargetclient.exceptions.ResourceNotFoundException:
print("Table does not exist")
def doesNotExist():
print("Inside doesNotExist")
print("Destination table does not exist ")
print("Exiting the execution")
# sys.exit()
def createDestinationTable(sourceTable):
print("Inside createDestinationTable")
source_table = source_session.resource('dynamodb').Table(sourceTable)
target_table = target_dynamodb.create_table(
TableName=destinationTableName,
KeySchema=source_table.key_schema,
AttributeDefinitions=source_table.attribute_definitions,
ProvisionedThroughput={
'ReadCapacityUnits': 5,
'WriteCapacityUnits': 5
})
target_table.wait_until_exists()
target_table.reload()
result = validateTables(sourceTableName, destinationTableName)
print("value of sourceTableExists = ", result['sourceTableExists'])
print("value of destinationTableExists = ", result['destinationTableExists'])
if (result['sourceTableExists'] == "false" ) and (result['destinationTableExists'] == "false" ):
print("Both the tables do not exist")
elif (result['sourceTableExists'] == "false" ) and (result['destinationTableExists'] == "true" ):
print("Source Table does not exist")
elif (result['sourceTableExists'] == "true" ) and (result['destinationTableExists'] == "false" ):
createDestinationTable(sourceTableName)
copyTable(sourceTableName, destinationTableName, item_count, counter)
elif (result['sourceTableExists'] == "true" ) and (result['destinationTableExists'] == "true" ):
backupTable(destinationTableName, backupName)
deleteDestinationTable(destinationTableName)
createDestinationTable(sourceTableName)
copyTable(sourceTableName, destinationTableName, item_count, counter)
else:
print("Something is wrong")
语法:
python copy-dynamodb-table.py -sa
执行脚本。
你可以参考上述语法,并将参数传递给脚本。
命令:
python copy-dynamodb-table.py -sa AKI12345IA5XJXFLMTQR -ss ihiHd8+NzLJ567890z4i6EwcN6hbV2A5cMfurscg -da AKI12345IA5XJXFLMTQR -ds ihiHd8+NzLJ567890z4i6EwcN6hbV2A5cMfurscg -st my-source-table -dt my-destination-table
这里,
- -sa = 源 AWS 账户 Access key = AKIAQ6GAIA5XJXFLMTQR
- -ss = 源 AWS 账户 Secret key = ihiHd8+NzLJK5DFfTz4i6EwcN6hbV2A5cMfurscg
- -da = 目标 AWS 账户 Access key = AKIAQ6GAIA5XJXFLMTQR
- -ds = 目标 AWS 账户 Secret key = ihiHd8+NzLJK5DFfTz4i6EwcN6hbV2A5cMfurscg
- -st = 源表 = my-source-table
- -dt = 目标表 = my-destination-table
你必须使用自己的密钥,这里的密钥属于我。
该脚本涵盖 4 种不同的使用场景
- 场景 1:源表和目标表都不存在。
- 场景 2:源表不存在,但目标表存在。
- 场景 3:源表存在,但目标表不存在。
- 场景 4:源表和目标表都存在。
让我们逐一查看这些使用场景。
场景 1:源表和目标表都不存在。
如果你的账户中没有 DynamoDB 表,但仍尝试执行脚本,脚本将退出并显示 "Both the tables do not exist" 消息。

场景 2:源表不存在,但目标表存在。
如果你尝试将不存在的表作为源表传入,脚本将退出并显示 "Source Table does not exist" 消息。

场景 3:源表存在,但目标表不存在。
在上述两种场景中,都不会执行任何操作。现在,如果你传入的源表存在而目标表不存在,脚本将使用你指定的名称创建目标表,并将数据项从源表复制到新创建的目标表。

场景 4:源表和目标表都存在。
在这种情况下,在从源表复制数据项之前,会先对目标表进行备份,然后删除目标表。表被删除后,会使用你在目标参数中指定的名称创建一个新表,然后将源表中的数据项复制到新创建的目标表中。



结论
在本文中,我们介绍了用于将数据项从一个 DynamoDB 表复制到另一个 DynamoDB 表的 Python 脚本。该脚本涵盖了从一个表向另一个表复制数据时可能出现的四种不同场景。现在,你可以使用此脚本在同一个 AWS 账户或不同 AWS 账户中,将数据项从一个 DynamoDB 表复制到另一个表。