zoukankan      html  css  js  c++  java
  • [原创]Python 命令 恢复 删除 RDS

    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()
  • 相关阅读:
    每日总结
    体温登记app(大年初一要收的作业)慢慢更,这个写完了
    2021/01/31周学习总结
    2021/01/24周学习总结
    从小工到专家
    构建之法阅读笔记
    2021/01/17周学习总结
    人月神话阅读笔记
    利用Word制作Kindle用的6寸PDF电纸书
    面试题-谈谈封装和抽象的区别(转)
  • 原文地址:https://www.cnblogs.com/dl-ekong/p/8205432.html
Copyright © 2011-2022 走看看