如何利用CloudFormation模板在已部署的DynamoDB表中创建条目?
问题分析与修正方案
你的模板存在几个关键问题,导致无法成功向DynamoDB添加条目:
- 自定义资源与WaitCondition重复使用:自定义资源(
Custom::InitFunction)本身就会等待Lambda函数返回的成功/失败信号,额外添加WaitCondition属于冗余逻辑,还会因为信号发送失败导致部署超时。 - Lambda信号发送参数错误:你在Lambda里调用
signalResource时缺少StackName、LogicalResourceId等必填参数,而且这个调用完全没必要——自定义资源只需要通过cfn-response.send通知CloudFormation结果即可。 - 参数名不匹配:自定义资源传递的是
WaitConditionHandle,但Lambda里尝试读取WaitConditionId,导致无法获取正确值。
修正后的完整模板
AWSTemplateFormatVersion: '2010-09-09' Resources: LambdaRole: Type: AWS::IAM::Role Properties: AssumeRolePolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Principal: Service: - lambda.amazonaws.com Action: - sts:AssumeRole Path: "/" Policies: - PolicyName: dynamodbAccessRole PolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Action: - dynamodb:PutItem Resource: !GetAtt DynamoDB.Arn # 缩小权限范围到目标表 - Effect: Allow Action: - logs:CreateLogGroup - logs:CreateLogStream - logs:PutLogEvents Resource: "arn:aws:logs:*:*:*" # 日志权限缩小到必要操作 InitFunction: Type: AWS::Lambda::Function Properties: Code: ZipFile: > const AWS = require("aws-sdk"); const response = require("cfn-response"); const docClient = new AWS.DynamoDB.DocumentClient(); exports.handler = function(event, context) { console.log(JSON.stringify(event, null, 2)); var params = { TableName: event.ResourceProperties.DynamoTableName, Item:{ "id": "abc123" } }; docClient.put(params, function(err, data) { if (err) { console.error("Failed to put item:", err); response.send(event, context, response.FAILED, {Error: err.message}); } else { console.log("Item added successfully:", data); response.send(event, context, response.SUCCESS, {}); } }); Handler: index.handler Role: !GetAtt LambdaRole.Arn Runtime: nodejs18.x Timeout: 60 DynamoDB: Type: AWS::DynamoDB::Table Properties: AttributeDefinitions: - AttributeName: id AttributeType: S KeySchema: - AttributeName: id KeyType: HASH ProvisionedThroughput: ReadCapacityUnits: 1 WriteCapacityUnits: 1 InitializeDynamoDB: Type: Custom::InitFunction DependsOn: DynamoDB # 确保DynamoDB表创建完成后再执行Lambda Properties: ServiceToken: !GetAtt InitFunction.Arn DynamoTableName: !Ref DynamoDB
关键修正点说明
- 移除冗余的WaitCondition资源:删掉
InitWaitCondition和InitWaitConditionHandle,让自定义资源自动处理等待逻辑。 - 简化Lambda逻辑:移除无用的
signalResource调用,只保留cfn-response.send来通知CloudFormation执行结果,同时添加错误日志便于排查问题。 - 优化IAM权限:将DynamoDB权限缩小到仅
PutItem操作,日志权限也限制为必要的创建和写入操作,遵循最小权限原则。 - 添加依赖关系:给自定义资源
InitializeDynamoDB加上DependsOn: DynamoDB,确保Lambda执行时表已经创建完成。
内容的提问来源于stack exchange,提问作者Shubhanshu Bhadouria
相关产品推荐
相关产品推荐

