利用boto3改进基于标签的云形成堆栈终止保护



我对Boto3还是个新手。我的要求是创建一个boto3脚本,它将根据标签修改云形成堆栈的终止保护:例如,如果标签值为"Production"则会使能终止保护,当标签值为"developing"时;它将禁用终止保护。我试着在它上工作,但被困在某个地方,无法得到StackName。它不断给我的错误,StackName CloudFormation对象没有属性'StackName'。非常感谢您的指导。谢谢!

现在我正在过滤具有CREATE_COMPLETE状态的堆栈,我能够过滤并打印当前正在运行的堆栈的数量,但无法打印堆栈的名称。下面是我的代码:

import boto3
def lambda_handler(event, context):
cftresource = boto3.resource('cloudformation',region_name='eu-west-3')
cftclient = boto3.client('cloudformation',region_name='eu-west-3')
stackfilter = cftclient.list_stacks(StackStatusFilter=['CREATE_COMPLETE'])
print ('The Number of Stacks having Status CREATE_COMPLETE are:') , print(len(stackfilter['StackSummaries']))
print(stackfilter.StackName)

我能够自己找到这个问题的解决方案,所以我在这里发布,这样如果其他人面临这个问题,他们就很容易找到:

import boto3
def lambda_handler(event, context):
cftresource = boto3.resource('cloudformation',region_name='eu-west-3')
cftclient = boto3.client('cloudformation',region_name='eu-west-3')
stackfilter = cftclient.list_stacks(StackStatusFilter=['CREATE_COMPLETE', 'UPDATE_COMPLETE' , 'ROLLBACK_COMPLETE'])
print ('The Number of Stacks having Status CREATE_COMPLETE, UPDATE_COMPLETE and ROLLBACK_COMPLETE are:') , print(len(stackfilter['StackSummaries']))
statuses = ['CREATE_COMPLETE' , 'UPDATE_COMPLETE' , 'ROLLBACK_COMPLETE']
stacks = [stack for stack in cftresource.stacks.all() if stack.stack_status in statuses]
for stack in stacks:
print(f'Stack Name having Status of CREATE_COMPLETE, UPDATE_COMPLETE and ROLLBACK_COMPLETE are: {stack.name}')
if len(stack.tags) > 0:
for tag in stack.tags:
# print(f' - Tag: {tag["Key"]}={tag["Value"]}')
if tag["Value"] == 'Production':
print(f' - Tag: {tag["Key"]}={tag["Value"]}')
cftclient.update_termination_protection(EnableTerminationProtection=True, StackName=stack.name)
elif tag["Value"] == 'Development':
print(f' - Tag: {tag["Key"]}={tag["Value"]}')
cftclient.update_termination_protection(EnableTerminationProtection=False, StackName=stack.name)
else:
print(f' - No Tags')
print('-'*60)

最新更新