Python3 通过引用aws官方包 可以 实现对 RDS的一些 恢复和删除操作

下面的恢复脚本是通过AWS Lambda改变过来的

import boto3
import os
import re

client = boto3.client('rds')


def lambda_handler():
    #INSTANCE_LIST = os.environ.get('TARGET_INSTANCE').split(";")
    INSTANCE_LIST = ['instacneid']

    for instanceid in INSTANCE_LIST:
        # 获取RDS快照
        snapshot_list = client.describe_db_snapshots(
            DBInstanceIdentifier=instanceid
        )

        # 匹配instanceid
        pattern = re.compile(r"%s" % instanceid)

        # Python3
        snapshot_list_f = list(filter \
                                   (lambda x: pattern.match(x["DBSnapshotIdentifier"]) and x["Status"] == "available",
                                    snapshot_list["DBSnapshots"]))

        # 是否找到
        if len(snapshot_list_f) == 0:
            print("No snapshot: InstanceID = {0}".format(instanceid))
            return

        #按照时间降序
        snapshot_list_s = sorted(snapshot_list_f, key=lambda x: x["SnapshotCreateTime"], reverse=True)

        # 取出最新的快照用于启动实例
        try:
            instance = instanceid
            snapshot = snapshot_list_s[0]["DBSnapshotIdentifier"]
            client.restore_db_instance_from_db_snapshot(
                DBInstanceIdentifier=instance,
                DBSnapshotIdentifier=snapshot,
                DBName="DBName",
                DBInstanceClass="db.t2.small",
                MultiAZ=False,
                DBSubnetGroupName="SubnetGroup",
                PubliclyAccessible=True,
                AvailabilityZone="ap-northeast-1a"
            )
            print("Restore Instance {0} from snapshot = {1}".format(instance, snapshot))
        except Exception as e:
            print("Error: {0}".format(e))
            print("Error InstanceId = {0} Snapshot = {1}".format(instance, snapshot))
    return

if __name__ == "__main__":
    lambda_handler()

删除脚本,获取当前时间来命名存储快照名字

import boto3
import time
import os
import re
from botocore.client import ClientError
from datetime import datetime, timedelta, tzinfo

rds = boto3.client('rds')
#sns = boto3.client('sns')

#TOPIC_ARN = 'arn:aws:sns:ap-northeast-1:390960260847:AutoShutdown_EC2'
INSTANCE_ID='inst-etl-new'

class JST(tzinfo):
    def utcoffset(self, dt):
        return timedelta(hours=9)

    def dst(self, dt):
        return timedelta(0)

    def tzname(self, dt):
        return 'JST'


as_list = ['On', 'ON']


def delete_instance(prefix, instanceid):
    if instanceid == INSTANCE_ID:
        snapshotid = "-".join([prefix, datetime.now(tz=JST()).strftime("%Y%m%d%H%M")])
        print("createsnapshot:" + snapshotid)
        print("Deleting:" + instanceid)
        rds.delete_db_instance(
            DBInstanceIdentifier=instanceid,
            SkipFinalSnapshot=False,
            FinalDBSnapshotIdentifier=snapshotid
        )


def lambda_handler():
    instances = get_rdsinstanceid()

    delnum = 0

    for instance in instances:
        try:
            #print("try deleting insrance:" + instance)
            delete_instance(instance, instance)
            delnum += 1

        except Exception as e:
            print("Error: {0}".format(e))
            print("ErrorInstanceId: {0}".format(instance))
            # response = sns.publish(
            #     TopicArn=TOPIC_ARN,
            #     Message='an error occured when stopping rds instance id=' + instance,
            #     Subject='AutoShutdown_RDS_Error'
            # )

    print("number of instances deleted successfully: " + str(delnum))
    return


def get_rdsinstanceid():
    response = rds.describe_db_instances()

    rds_count = len(response['DBInstances'])

    print("対象数:" + str(rds_count))
    rds_list = []
    if not rds_count == 0:
        for i in range(0, rds_count):
            if response['DBInstances'][i]['DBInstanceStatus'] == 'available':
                arn = response['DBInstances'][i]['DBInstanceArn']

                print("Running:" + arn)
                response_tags = rds.list_tags_for_resource(ResourceName=arn, )
                print(response_tags['TagList'])

                for tag in response_tags['TagList']:
                    if tag['Key'] == 'Auto-Shutdown' and tag['Value'] in as_list:
                        rds_list.append(response['DBInstances'][i]['DBInstanceIdentifier'])
    else:
        print("SUCCESS: specified hosts is None")
    return rds_list

if __name__ == "__main__":
    lambda_handler()

 

posted on 2018-01-05 16:37  窗外蔡大岭  阅读(675)  评论(0编辑  收藏  举报