开发者

使用Python3 Boto3包删除AWS CloudFormation的栈(Stacks)

目录
  • 小结
  • 问题及解决
    • 有关json文件的输入和输出
    • 使用python3及正则表达式查找字符串包含某个子字符串
    • 使用Python3 Boto3删除AWS CloudFormation的栈(Stacks)
  • 参考

    小结

    本文记录了使用Python3的Boto3包删除AWS CloudFormation的栈(Stacks)

    问题及解决

    有关Json文件的输入和输出

    json.loads函数是将一个字符串(String)输入转换为字典类型(dictionary)输出

    json.dumps函数是将一个字典类型(dictionary)输入转换为字符串(String)输出

    当出现JSON object must be str, bytes or bytearray, not dict或者'dict' object has no attribute 'read'的错误时,需要检查以上输入类型是否正确。

    对于datetime.datetime not JSON serializable的问题,也就是日期类型无法进行Json序列化,可以使用以下指令解决问题,应该是default=str这个参数起了作用,将日期类型处理为了字符串:

    json_formatted_str = json.dumps(task_definition, indent=2, sort_keys=True, default=str)

    使用Python3及正则表达式查找字符串包含某个子字符串

    使用以下办法:

    exp = re.compile(stack_name_to_Search)
    stack_name = cfn_stack['StackName']
    if re.search(exp, stack_name):
      ....

    以上是查找 stack_name 这个字符串是否包含stack_name_to_Search这个子字符串。

    使用Python3 Boto3删除AWS CloudFormation的栈(Stacks)

    def delete_skms_stack(stack_name):
        cf_client = boto3.client('cloudformation')android
        #list all the stacks excepts 'DELETED_STACKS'
        response = cf_client.list_stacks(
            StackStatusFilter=[
            'CREATE_IN_PROGRESS','CREATE_FAILED','CREATE_COMPLETE',
            'ROLLBACK_IN_PROGRESS','ROLLBACK_FAILED','ROLLBACK_COMPLETE',
            'DELETE_IN_PROGRESS','DELETE_FAILED',
            'UPDATE_IN_PROGRESS','UPDATE_COMPLETE_CLEANUP_IN_PROGRESS','UPDATE_COMPLETE','UPDATE_FAILED','UPDATE_ROLLBACK_IN_PROGRESS','UPDATE_ROLLBACK_FAILED','UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS','UPDATE_ROLLBACK_COMPLETE','REVIEW_IN_PROGRESS',
            'IMPORT_IN_PROGRESS','IMPORT_COMPLETE','IMPORT_ROLLBACK_IN_PROGRESS','IMPORT_ROLLBACK_FAILED','IMPORT_ROLLBACK_COMPLETE'
            ]
        )
        #Stack name pattern
        exp = re.compile(stack_name)
        print('--------------------')
        print(response['StackSummaries'])
        for cfn_stack in response['StackSummaries']:
            stack_name = cfn_stack['StackName']
            #match = re.search(regex_pattern,stack_name)
            if re.search(exp, stack_name):
            #Custome conditions can be implemented here
                try:
                    response = cfjavascript_client.delete_stack(StackName=stack_name)
                    stack_delete_status = cf_client.describe_stacks(StackName=stack_name)
                    logger.info("Delete stack: " + json.dumps(response))
                    while stack_delete_status['Stacks'][0]['StackStatus'] == 'DELETE_IN_PROGRESS':
                        time.sleep(10)
                        stack_delete_status = cf_client.describe_stacks(StackName=stack_name)
                        logger.info("Delete stack status: " + stack_delete_status['Stacks'][0]['StackStatus'])
                        if stack_delete_status['Stacks'][0]['StackStatus'] == 'DELETE_FAILED':
                            logger.warning('Delete failed. Retry delete')
                            resources = cf_client.delete_stack(StackName=stack_name)
                            return resources
                        elif stack_delete_status['Stacks'][0]['StackStatus'] == 'DELETE_IN_PROGRESS':javascript
                            continue
                        else:
                            logger.info("Delete stack complete")
                except Exception as e:
                    logger.error(e) 
    http://www.devze.com

    以上代码执行效果如下:

    INFO:__main__:Delete stack status: DELETE_IN_PROGRESS

    INFO:__main__:Delete stack status: DELETE_IN_PROGRESS

    INFO:__main__:Delete stack status: DELETE_IN_PROGRESS

    INFO:__main__:Delete stack status: DELETE_IN_PROGRESS

    ERROR:__main__:An error occurred (ValidationError) when calling the DescribeStacks operation: Stack with id ECS-Console-V2-Service-sammperso-johnvpc-svc-John-VPC-Cluster-8c3e39c8 does not exist

    其中最后一个错误是因为CloudFo编程客栈rmation的栈(Stacks)已经被删除,找不到了,所以是正常返回。

    参考

    Digital Ocean: Python Pretty Print JSON

    Stackoverflow: JSON object must be str, bytes or bytearray, not dict

    Stackoverflow: ‘dict’ object has no attribute ‘read’

    Stackoverflow: How can I overcome “datetime.datetime not JSON serializable”?

    Stackoverflow: How to delete multiple Cloudformation stacks at once?

    Stackoverflow: Python regex check if string contains any of words

    到此这篇关于如何使用Python3 Boto3删除AWS CloudFormation的栈(Stacks)的文章就介绍到这了,更多相关Python3 Boto3删除AWS CloudFormation的栈内容请搜索编程客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!

    0

    上一篇:

    下一篇:

    精彩评论

    暂无评论...
    验证码 换一张
    取 消

    最新开发

    开发排行榜