列出今天创建的自动RDS快照,并使用boto3

时间:2018-05-07 07:50:23

标签: amazon-web-services aws-lambda amazon-rds boto3

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

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

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函数仍然无法列出快照。

2 个答案:

答案 0 :(得分:0)

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

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

或者,您可以为每个快照发行副本,而不考虑日期。客户会提出异常,您可以这样捕获它

# 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 :(得分: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