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

发布时间:2024年01月03日

小结

本文记录了使用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')
    #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 = cf_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':
                        continue
                    else:
                        logger.info("Delete stack complete")
            except Exception as e:
                logger.error(e) 

以上代码执行效果如下:

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

其中最后一个错误是因为CloudFormation的栈(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

文章来源:https://blog.csdn.net/scruffybear/article/details/135359958
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。