aws-lambda - Lambda 支持的自定义资源 cf 模板返回“CREATE_FAILED”
问题描述
下面的 lambda 函数是将 SNS 主题关联到现有目录,然后是自定义资源以调用 lambda 函数本身。我看到 lambda 创建成功,“Register_event_topic”也完成了。但是,堆栈在一段时间后失败主要是因为“自定义资源未能在预期时间内稳定”;如何确保堆栈不会出错?
AWSTemplateFormatVersion: '2010-09-09'
#creating lambda function to register_event_topic
Description: Lambda function to register event topic with existing directory ID
Parameters:
RoleName:
Type: String
Description: "IAM Role used for Lambda execution"
Default: "arn:aws:iam::<<Accountnumber>>:role/LambdaExecutionRole"
EnvVariable:
Type: String
Description: "The Environment variable set for the lambda func"
Default: "ESdirsvcSNS"
Resources:
REGISTEREVENTTOPIC:
Type: 'AWS::Lambda::Function'
Properties:
FunctionName: dirsvc_snstopic_lambda
Handler: index.lambda_handler
Runtime: python3.6
Description: Lambda func code to assoc dirID with created SNS topic
Code:
ZipFile: |
import boto3
import os
import logging
dsclient = boto3.client('ds')
def lambda_handler(event, context):
response = dsclient.describe_directories()
directoryList = []
print(response)
for directoryList in response['DirectoryDescriptions']:
listTopics = dsclient.describe_event_topics(
DirectoryId=directoryList['DirectoryId']
)
eventTopics = listTopics['EventTopics']
topiclength = len(eventTopics)
if topiclength == 0:
response = dsclient.register_event_topic(
DirectoryId=directoryList['DirectoryId'],
TopicName= (os.environ['MONITORING_TOPIC_NAME'])
)
print(listTopics)
Timeout: 60
Environment:
Variables:
MONITORING_TOPIC_NAME: !Ref EnvVariable
Role: !Ref RoleName
InvokeLambda:
Type: Custom::InvokeLambda
Properties:
ServiceToken: !GetAtt REGISTEREVENTTOPIC.Arn
ReservedConcurrentExecutions: 1
解决方案
唉,编写自定义资源并不像您最初想象的那么简单。相反,必须添加特殊代码才能将响应发布回 URL。
您可以在以下提供的示例 Zip 文件中看到这一点:演练:查找 Amazon 系统映像 ID - AWS CloudFormation
来自自定义资源 - AWS CloudFormation文档:
自定义资源提供程序处理 AWS CloudFormation 请求并返回对预签名 URL 的响应
SUCCESS
或FAILED
对预签名 URL 的响应。自定义资源提供程序以 JSON 格式的文件提供响应并将其上传到预签名的 S3 URL。
这是由于 CloudFormation 的异步行为。它不是简单地调用 Lambda 函数然后等待响应。相反,它会触发 Lambda 函数,并且该函数必须回调并触发 CloudFormation 中的下一步。
推荐阅读
- python - 使用 imshow 创建一个完全重复的辅助 X/Y 轴
- dart - Dart 流 .asBroadcastStream 内存泄漏
- c - 链接列表上的快速排序,如何使此代码使用第一个元素作为枢轴而不是最后一个
- javascript - javascript:使用函数方法通过数组的多个值过滤对象
- java - 使用原始字节而不是文件的 AWS S3 分段上传
- asp.net - ASP.NET 可以针对 .net 核心吗?
- javascript - 比较 NgFor 中不同数组的特定属性
- python - 顶点数组上的 Voronoi 图
- android - Flutter 灵活的警报对话框列表
- c - 防止编译器在不使用 volatile 的情况下优化代码