使用boto3修改基于标签的Cloud-formation堆栈的终止保护

Modifying Termination protection of Cloud-formation stack based on tags using boto3

我对使用 Boto3 还很陌生。我的要求是创建一个 boto3 脚本,它将根据标签修改 Cloud Formation Stack 的终止保护:例如,如果标签值为“Production”,那么它将启用终止保护,当标签值为“Development”时,它将禁用终止保护。我尝试处理它,但卡在某个地方,无法获取 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)