【问题标题】:write StackId to S3 using Lambda使用 Lambda 将 StackId 写入 S3
【发布时间】:2016-11-10 04:18:00
【问题描述】:

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

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

MYnestedStack-Ec2Stack-1WQDHSJFIFNFN

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

我已经按照下面@ataylor 的建议进行了尝试,但出现错误

“响应 JSON 序列化时出错: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

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

“响应的 JSON 序列化过程中出错: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

请推荐!!

【问题讨论】:

    标签: python amazon-web-services amazon-s3 aws-lambda amazon-cloudformation


    【解决方案1】:

    您可以从 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。

    【讨论】:

    • import boto3 import time client = boto3.client('cloudformation') response = client.describe_stack_resources( StackName='Mystack', LogicalResourceId='AppStack' ) def lambda_handler(event, context): 返回响应我得到以下错误响应的 JSON 序列化过程中发生错误:datetime.datetime(2016, 7, 12, 15, 23, 16, 451000, tzinfo=tzlocal()) is not JSON serializable
    猜你喜欢
    • 2019-07-06
    • 2021-01-27
    • 1970-01-01
    • 2018-08-03
    • 1970-01-01
    • 2017-03-04
    • 1970-01-01
    • 2021-05-19
    • 1970-01-01
    相关资源
    最近更新 更多