首页 > 解决方案 > 如何使用 Boto 创建一个 Python 方法来查找 CloudFormation 堆栈的 UUID?

问题描述

我们目前使用:

cloudformation = environment+"-"+role
qa = QAWS()
qa.initialize(environ)
events = qa.cfn.describe_stack_events(StackName=sn)
"Some interesting stuff:
event["Timestamp"]
event["ResourceStatus"]
event["ResourceType"]
event["LogicalResourceId"]
if exists = event["ResourceStatusReason"]
"""
return events["StackEvents"]

这适用于我们的大多数 Cloudformation 堆栈,它们是:

但不适用于我们的一些具有 UUID 的堆栈:

我该如何解决这个问题?

标签: pythonamazon-web-servicesboto3boto

解决方案


我目前使用 cloudformation 堆栈名称中的“唯一 ID”做了类似的事情,理论上你可以做的只是删除角色等并搜索“测试”,这样你只会得到堆栈像'test-vpn''test-activedirectory'等。

import boto3
import re
from sys import argv

"""
profile = AWS CLI profile you want to use, a.k.a what account you want to run this in.
region = Self explanatory, generally eu-west-1/2 etc.
unique_id = Your unique id for the CF stacks, i.e test, ppe or prod

Example usage: python delete_stacks.py test eu-west-1 test

"""
_, profile, region, unique_id  = argv

session = boto3.Session(profile_name=profile)
client = session.client('cloudformation', region_name=region)

response = client.describe_stacks().get('Stacks',[])
stacks = []
for r in response:
    ((stacks.append(r['StackName']) if unique_id in r['StackName'] else None))

print("These are the stacks that were found")
print(stacks)


for s in stacks:
    events = client.describe_stack_events(StackName=s)
    print(events)

这是用python3编写的,我不确定您使用什么python版本进行开发,因此如果使用python2,您可能需要进行调整。


推荐阅读