【问题标题】:ValidationError on calling ListStacks on AWS Cloudformation在 AWS Cloudformation 上调用 ListStacks 时出现 ValidationError
【发布时间】:2021-09-07 02:39:34
【问题描述】:

我有一段 python 代码在 AWS 的 Cloudformation API 上调用 ListStacks 操作:

client = boto3.client('cloudformation', region_name='[MYREGION]')

status_filter = ['CREATE_COMPLETE', 'UPDATE_COMPLETE', 'ROLLBACK_COMPLETE']  

response = client.list_stacks(StackStatusFilter=status_filter)

next_token = response.get('NextToken', None)

while next_token:
    response = client.list_stacks(NextToken=next_token)

在最后一行,它抛出一个 ValidationError:

调用 ListStacks 操作时发生错误(ValidationError):[TOKEN] 不是有效的 NextToken

这一个月一直运行良好,但现在突然抛出此错误。代码没有变化。

奇怪的是,响应小于 1MB,因此根据文档,令牌应该为空:

下一个令牌
如果输出大小超过 1 MB,则为标识下一页堆栈的字符串。
如果不存在其他页面,则此值为 null。
类型:字符串
长度约束:最小长度为 1。最大长度为 1024

有谁知道为什么响应包含(无效的)NextToken 而不是 null?

编辑

我认为响应没有超过限制的假设是错误的。它只返回适合过滤器的堆栈子集。

所以问题是:为什么 NextToken 无效?

【问题讨论】:

  • while 循环中你不需要这个next_token = response.get('NextToken', None) 吗?
  • 这看起来很有趣。您介意共享请求 ID 以及您针对哪个区域提出请求吗? (我使用 CloudFormation)

标签: python amazon-cloudformation boto3


【解决方案1】:

我不知道为什么 NextToken 无效,但一位同事指出,我们可以通过使用 Cloudformation.Paginator.ListStacks 类来规避这个问题。

client = boto3.client('cloudformation', region_name='eu-central-1')
paginator = client.get_paginator('list_stacks')
status_filter = ['CREATE_COMPLETE', 'UPDATE_COMPLETE', 'ROLLBACK_COMPLETE']

response_iterator = paginator.paginate(
  StackStatusFilter=status_filter
)
stacks = []
for response in response_iterator:
  stacks += [stack['StackName'] for stack in response['StackSummaries']]

return stacks

【讨论】:

    【解决方案2】:

    我在这段代码中看到了同样的错误:

                for region in get_regions(aws):
                    instances = cf_client.list_stack_instances(StackSetName=data[i]['StackSetId'],region_name=region['RegionName'])
                    stack_instances.append(instances)
                    while 'NextToken' in instances:
                        more_instances = cf_client.list_stack_instances(
                            StackSetName=data[i]['StackSetName'],
                            NextToken=instances['NextToken'],
                            MaxResults=99,
                            StackInstanceRegion=region['RegionName']
                        )
    

    在尝试了分页器和其他一些想法之后,我在单步执行代码时通过删除 StackInstanceRegion 和 MaxResults 来简化函数参数,例如

    while 'NextToken' in instances:
                        more_instances = cf_client.list_stack_instances(
                            StackSetName=data[i]['StackSetName'],
                            NextToken=instances['NextToken']
                        )
    

    现在它正在使用 client.list_stack_instances()

    【讨论】:

      猜你喜欢
      • 2019-04-22
      • 2020-11-10
      • 1970-01-01
      • 2019-01-25
      • 1970-01-01
      • 2016-10-20
      • 2016-12-23
      • 1970-01-01
      • 2020-01-15
      相关资源
      最近更新 更多