扫描cloudformation堆栈层次结构的资源

时间:2017-01-11 16:21:03

标签: amazon-cloudformation boto3

我在尝试递归扫描层次结构时感到很沮丧 AWS CloudFormation堆栈。我需要看看他们所有的 资源。

回想一下,一个CloudFormation堆栈可以包含另一个堆栈。

看来这些子堆栈的描述返回了 describe_stack_resources并不有用。

我的问题的一个例子如下:

使用Boto3,我们可以看到这个堆栈有八个子堆栈:

In [22]: resources = cfn.describe_stack_resources(StackName=my_stack_name)['StackResources']

In [23]: len(resources)
Out[23]: 8

In [24]: [r['ResourceType'] for r in resources]
Out[24]: 
['AWS::CloudFormation::Stack',
 'AWS::CloudFormation::Stack',
 'AWS::CloudFormation::Stack',
 'AWS::CloudFormation::Stack',
 'AWS::CloudFormation::Stack',
 'AWS::CloudFormation::Stack',
 'AWS::CloudFormation::Stack',
 'AWS::CloudFormation::Stack']

奇怪的是,所有这些亚组都被报道为具有该名称 创建它们的父级,尽管它们具有不同的PhysicalResourceId s。

In [25]: [r['StackName'] == my_stack_name for r in resources]
Out[25]: [True, True, True, True, True, True, True, True]

In [29]: resources[0]['PhysicalResourceId'] == resources[1]['PhysicalResourceId']
Out[29]: False

如果我使用他们的身份证要求亚组的资源它不起作用,我会获得父母的资源:

In [32]: p_id_0 = resources[0]['PhysicalResourceId']

In [33]: child_resources = cfn.describe_stack_resources(PhysicalResourceId=p_id_0)['StackResources']

In [34]: child_resources == resources
Out[34]: True

有解决方法吗?

1 个答案:

答案 0 :(得分:0)

此命令将列出所有嵌套堆栈的资源:

map(lambda x: cfn.describe_stack_resources(StackName=x['PhysicalResourceId'])['StackResources'], cfn.describe_stack_resources(StackName=my_stack_name)['StackResources'])

有关此API的请求参数/响应元素的详细信息,请参阅DescribeStackResources API文档。

在请求中,StackName参数接受 堆栈的名称​​或其唯一堆栈ID。在内部堆栈调用中,您可以提供AWS::CloudFormation::Stack资源的PhysicalResourceId,因为物理ID(Ref内部函数返回的字符串)是defined作为此资源类型的堆栈ID。

请注意,在响应中,StackResources.StackName属性表示与堆栈关联的名称,而不是所描述资源的堆栈名称。

另请注意,使用DescribeStackResources参数调用PhysicalResourceId会返回包含该物理资源ID的父堆栈的所有资源,而不是堆栈的资源表示的物理资源ID,如API文档中所述:

  

返回正在运行和已删除堆栈的AWS资源描述。如果指定了StackName,则返回属于堆栈的所有关联资源。如果指定了PhysicalResourceId,则返回资源所属堆栈的关联资源。