发布
社区首页 >问答首页 >列出今天创建的自动RDS快照,并使用boto3复制到其他区域

列出今天创建的自动RDS快照,并使用boto3复制到其他区域
EN

Stack Overflow用户
提问于 2018-05-07 15:50:23
回答 2查看 1.4K关注 0票数 0

我们正在其他地区构建一个自动DR cold站点,目前正在检索今天创建的RDS自动快照的列表,并将它们传递给另一个功能,以将它们复制到另一个AWS区域。

问题出在RDS boto3客户端,它返回了唯一格式的日期,使得过滤创建日期变得更加困难。

代码语言:javascript
代码运行次数:0
复制
today = (datetime.today()).date()
rds_client = boto3.client('rds')
snapshots = rds_client.describe_db_snapshots(SnapshotType='automated')

harini = "datetime("+ today.strftime('%Y,%m,%d') + ")"
print harini

print snapshots

for i in snapshots['DBSnapshots']:

  if i['SnapshotCreateTime'].date() == harini:
      print(i['DBSnapshotIdentifier'])
      print (today)

尽管已经将日期"harini“转换为'SnapshotCreateTime':datetime(2015,1,1)格式,但Lambda函数仍然无法列出快照。

EN

回答 2

Stack Overflow用户

发布于 2019-04-21 17:52:38

更好的方法是通过使用云监视事件调用lambda函数来复制创建的文件。

请参阅分步说明:https://geektopia.tech/post.php?blogpost=Automating_The_Cross_Region_Copy_Of_RDS_Snapshots

或者,您可以为每个快照发布一份拷贝,而不考虑日期。客户端将引发一个异常,您可以像这样捕获它

代码语言:javascript
代码运行次数:0
复制
# Written By GeekTopia
#
# Copy All Snapshots for an RDS Instance To a new region
# --Free to use under all conditions
# --Script is provied as is. No Warranty, Express or Implied

import json
import boto3
from botocore.exceptions import ClientError
import time
destinationRegion = "us-east-1"
sourceRegion = 'us-west-2'
rdsInstanceName = 'needbackups'

def lambda_handler(event, context):
    #We need two clients
    # rdsDestinationClient -- Used to start the copy processes. All cross region 
copies must be started from the destination and reference the source
    # rdsSourceClient      -- Used to list the snapshots that need to be copied. 

    rdsDestinationClient = boto3.client('rds',region_name=destinationRegion)
    rdsSourceClient=boto3.client('rds',region_name=sourceRegion)

    #List All Automated for A Single Instance 

    snapshots = rdsSourceClient.describe_db_snapshots(DBInstanceIdentifier=rdsInstanceName,SnapshotType='automated')

    for snapshot in snapshots['DBSnapshots']:
        #Check the the snapshot is NOT in the process of being created
        if snapshot['Status'] == 'available':

            #Get the Source Snapshot ARN. - Always use the ARN when copying snapshots across region
            sourceSnapshotARN = snapshot['DBSnapshotArn']

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

            #Adding a delay to stop from reaching the api rate limit when there are large amount of snapshots -
            #This should never occur in this use-case, but may if the script is modified to copy more than one instance. 
            time.sleep(.2)            

            #Execute copy
            try:
                copy = rdsDestinationClient.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 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')
    }
票数 1
EN

Stack Overflow用户

发布于 2019-09-06 20:34:05

下面的代码将拍摄今天创建的自动快照。

代码语言:javascript
代码运行次数:0
复制
import boto3
from datetime import date, datetime

region_src = 'us-east-1'

client_src = boto3.client('rds', region_name=region_src)
date_today = datetime.today().strftime('%Y-%m-%d')

def get_db_snapshots_src():
    response = client_src.describe_db_snapshots(
        SnapshotType = 'automated',
        IncludeShared=False,
        IncludePublic=False
    )
    snapshotsInDay = []
    for i in response["DBSnapshots"]:
        if i["SnapshotCreateTime"].strftime('%Y-%m-%d') == date.isoformat(date.today()):
            snapshotsInDay.append(i)
    return snapshotsInDay
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50209440

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档