如何使用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

相关推荐
AI原吾2 小时前
掌握Python-uinput:打造你的输入设备控制大师
开发语言·python·apython-uinput
毕设木哥2 小时前
25届计算机专业毕设选题推荐-基于python的二手电子设备交易平台【源码+文档+讲解】
开发语言·python·计算机·django·毕业设计·课程设计·毕设
weixin_455446172 小时前
Python学习的主要知识框架
开发语言·python·学习
D11_3 小时前
Pandas缺失值处理
python·机器学习·数据分析·numpy·pandas
花生了什么树~.3 小时前
python基础知识(四)--if语句,for\while循环
python
IT毕设梦工厂4 小时前
计算机毕业设计选题推荐-在线拍卖系统-Java/Python项目实战
java·spring boot·python·django·毕业设计·源码·课程设计
luthane5 小时前
python 实现average mean平均数算法
开发语言·python·算法
码农研究僧5 小时前
Flask 实现用户登录功能的完整示例:前端与后端整合(附Demo)
python·flask·用户登录
Ylucius5 小时前
动态语言? 静态语言? ------区别何在?java,js,c,c++,python分给是静态or动态语言?
java·c语言·javascript·c++·python·学习
凡人的AI工具箱5 小时前
AI教你学Python 第11天 : 局部变量与全局变量
开发语言·人工智能·后端·python