使用 Lambda 将 StackId 写入 S3

write StackId to S3 using Lambda

我使用 create_stack api 使用 AWS Lambda(带嵌套堆栈)..但我想将每个堆栈 ID 存储在作为嵌套堆栈的一部分创建的 S3 中。 我对 Lambda 函数使用 python。

每当将单个堆栈创建为嵌套堆栈 (cloudformation) 的一部分时,它都会为每个堆栈附加唯一 ID,如下所示

MYnestedStack-Ec2Stack-1WQDHSJFINFNFN

我想将此值存储在 S3 存储桶中,以便我可以使用该 ID 删除堆栈,而无需手动转到 AWS cloudformation 控制台删除相同的..

我按照下面@ataylor 的建议进行了尝试,但我收到错误

"An error occurred during JSON serialization of response: datetime.datetime(2016, 7, 12, 15, 23, 16, 451000, tzinfo=tzlocal()) is not JSON serializable"

import boto3
import time
import json

client = boto3.client('cloudformation')


response = client.describe_stack_resources(
    StackName='Mystack',
    LogicalResourceId='Ec2Stack'
)

def lambda_handler(event, context):
        return response

我也试过下面的代码并得到错误

"An error occurred during JSON serialization of response: cloudformation.StackResource(stack_name='Mystack', logical_id='Ec2Stack') is not JSON serializable"

import boto3
import time
import json

cloudformation = boto3.resource('cloudformation')
stack_resource = cloudformation.StackResource('prodUpgradeForchestartorFullStack','ApplicationStack')

def lambda_handler(event, context):
        return stack_resource

请多多指教!!

您可以从 CloudFormation API 中获取堆栈名称。特别是,如果您的父堆栈称为 Ec2Stack,您可以从命令行获取嵌套堆栈的名称:

aws cloudformation describe-stack-resources \
    --query StackResources[].[PhysicalResourceId][] \
    --stack-name Ec2Stack

如果您有逻辑 ID 并想要资源的物理 ID,请使用:

aws cloudformation describe-stack-resources \
    --query 'StackResources[?LogicalResourceId==`MYnestedStack`].[PhysicalResourceId][]' \
    --stack-name Ec2Stack

您可以从 python 调用相同的 API:http://boto3.readthedocs.io/en/latest/reference/services/cloudformation.html#stackresource

当你想删除堆栈时,你可以直接从API使用它,或者将它保存到S3。