You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AWS CloudFormation资源troux标签检测代码误报重复结果问题

排查CloudFormation堆栈Troux标签重复/错误提示问题

问题现状

遍历CloudFormation堆栈筛选含department_name_的资源,检查是否存在troux_id/troux_uid标签时,出现以下问题:

  • 同一个堆栈多次输出"缺失troux标签"的提示
  • 同一个堆栈同时显示存在troux标签和缺失标签的矛盾结果

原代码如下:

import boto3
import ssl

ssl._create_default_https_context = ssl._create_unverified_context

#if using WSL2
boto3.setup_default_session(profile_name='profile')

client = boto3.client('cloudformation')
paginator = client.get_paginator('describe_stacks')
page_iterator = paginator.paginate()

result = []

for page in page_iterator:
    for stack in page['Stacks']:
        if "department_name_" in stack["StackName"]:
            for dict in stack["Tags"]:
                for key, value in dict.items():
                    if value in ("troux_id", "troux_uid"):
                        stack_with_troux = stack["StackName"] + " " + dict.get('Key') + ": " + dict.get('Value')
                        result.append(stack_with_troux)
                    else:
                        stack_without_troux = stack["StackName"] + " is missing troux tag!"
                        result.append(stack_without_troux)


print(result)

标签数据示例(stack["Tags"]返回内容):

{'Key': 'tag', 'Value': 'abc'}
{'Key': 'tag', 'Value': 'abc'}
{'Key': 'tag', 'Value': 'abc'}
{'Key': 'troux_id', 'Value': 'xyz'}
{'Key': 'tag', 'Value': 'xyz'}
{'Key': 'tag', 'Value': 'abc'}

当前错误输出:

department_name_resource_one  is missing troux tag!
department_name_resource_one  is missing troux tag!
department_name_resource_one  is missing troux tag!
department_name_resource_one  is missing troux tag!
department_name_resource_one  troux_id: xyz
department_name_resource_one  is missing troux tag!

期望输出:每个堆栈仅输出一条结果,找到标签则记录标签信息,未找到则仅显示一次缺失提示:

department_name_resource_one  is missing troux tag!
department_name_resource_two  troux_id: xyz
department_name_resource_three is missing troux tag!

问题原因

原代码逻辑错误:

  1. 遍历每个标签时,只要当前标签不是troux_id/troux_uid就添加缺失提示,导致每个非目标标签都生成一条重复记录
  2. 找到目标标签后未标记该堆栈已匹配,后续非目标标签仍会继续添加缺失提示,造成矛盾结果
  3. 核心逻辑误判:原代码检查标签的Value是否等于troux_id/troux_uid,实际应该检查标签的Key是否为这两个值

修正后的代码

import boto3
import ssl

ssl._create_default_https_context = ssl._create_unverified_context

# if using WSL2
boto3.setup_default_session(profile_name='profile')

client = boto3.client('cloudformation')
paginator = client.get_paginator('describe_stacks')
page_iterator = paginator.paginate()

result = []

for page in page_iterator:
    for stack in page['Stacks']:
        stack_name = stack["StackName"]
        if "department_name_" not in stack_name:
            continue
        
        found_troux = False
        # 遍历当前堆栈的所有标签,检查是否有目标标签
        for tag in stack["Tags"]:
            if tag['Key'] in ("troux_id", "troux_uid"):
                entry = f"{stack_name} {tag['Key']}: {tag['Value']}"
                result.append(entry)
                found_troux = True
                # 找到一个即可,无需继续遍历当前堆栈的标签
                break
        
        # 遍历完所有标签后,若未找到目标标签,添加一次缺失提示
        if not found_troux:
            result.append(f"{stack_name} is missing troux tag!")

print(result)

关键修正点

  • 为每个堆栈添加found_troux标记,初始设为False
  • 修正核心判断逻辑:检查标签的Key而非Value是否匹配troux_id/troux_uid
  • 找到目标标签后标记found_troux为True,并跳出当前标签循环(避免重复记录同一堆栈的多个troux标签)
  • 遍历完当前堆栈所有标签后,若found_troux仍为False,才添加一次缺失提示

内容的提问来源于stack exchange,提问作者marcin2x4

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 12:27:59