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

使用boto3 CloudFormation list_stacks()无法获取全部栈的问题排查

CloudFormation list-stacks CLI与boto3结果不一致的问题解决

问题根源

AWS CLI执行aws cloudformation list-stacks时会自动处理API的分页逻辑,把所有分页结果合并后返回;但boto3的list_stacks接口默认只返回第一页数据(默认单页最多100条),如果你的栈数量超过这个阈值,就会出现部分栈信息缺失的情况。

两种解决办法

1. 用boto3分页器自动处理(推荐)

分页器会帮你自动遍历所有分页,无需手动处理令牌:

import boto3

cf_client = boto3.client('cloudformation')
# 创建分页器实例
paginator = cf_client.get_paginator('list_stacks')
# 执行分页查询
page_iterator = paginator.paginate(StackStatusFilter=["CREATE_COMPLETE"])

# 收集所有栈信息
all_stacks = []
for page in page_iterator:
    all_stacks.extend(page['StackSummaries'])

# 此时all_stacks包含所有CREATE_COMPLETE状态的栈

2. 手动循环处理NextToken

如果需要自定义分页逻辑,可以手动检查并传递NextToken:

import boto3

cf_client = boto3.client('cloudformation')
all_stacks = []
next_token = None

while True:
    # 根据是否有next_token决定调用参数
    kwargs = {"StackStatusFilter": ["CREATE_COMPLETE"]}
    if next_token:
        kwargs["NextToken"] = next_token
    
    response = cf_client.list_stacks(**kwargs)
    all_stacks.extend(response['StackSummaries'])
    
    # 获取下一页令牌,没有则退出循环
    next_token = response.get('NextToken')
    if not next_token:
        break

# 输出全部栈信息
print(f"共获取到 {len(all_stacks)} 个CREATE_COMPLETE状态的栈")

验证方法

执行完代码后,打印栈的数量,和CLI命令返回的结果对比,确认数量一致即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 11:05:21