如何使用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这个参数起了作用,将日期类型处理为了字符串:

python 复制代码
json_formatted_str = json.dumps(task_definition, indent=2, sort_keys=True, default=str)

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

使用以下办法:

python 复制代码
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)

python 复制代码
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) 

以上代码执行效果如下:

shell 复制代码
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

相关推荐
Python大数据分析@11 分钟前
python操作CSV和excel,如何来做?
开发语言·python·excel
黑叶白树13 分钟前
简单的签到程序 python笔记
笔记·python
知孤云出岫15 分钟前
云上拼团GO指南——腾讯云博客部署案例,双11欢乐GO
云计算·腾讯云
Shy96041826 分钟前
Bert完形填空
python·深度学习·bert
上海_彭彭37 分钟前
【提效工具开发】Python功能模块执行和 SQL 执行 需求整理
开发语言·python·sql·测试工具·element
lihuhelihu43 分钟前
第3章 CentOS系统管理
linux·运维·服务器·计算机网络·ubuntu·centos·云计算
zhongcx011 小时前
使用Python查找大文件的实用脚本
python
dessler1 小时前
Linux系统-ubuntu系统安装
linux·运维·云计算
yyfhq2 小时前
sdnet
python
测试19982 小时前
2024软件测试面试热点问题
自动化测试·软件测试·python·测试工具·面试·职场和发展·压力测试