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!
问题原因
原代码逻辑错误:
- 遍历每个标签时,只要当前标签不是
troux_id/troux_uid就添加缺失提示,导致每个非目标标签都生成一条重复记录 - 找到目标标签后未标记该堆栈已匹配,后续非目标标签仍会继续添加缺失提示,造成矛盾结果
- 核心逻辑误判:原代码检查标签的
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
相关产品推荐
相关产品推荐

