You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何利用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

关键修正点说明

  1. 移除冗余的WaitCondition资源:删掉InitWaitCondition和InitWaitConditionHandle,让自定义资源自动处理等待逻辑。
  2. 简化Lambda逻辑:移除无用的signalResource调用,只保留cfn-response.send来通知CloudFormation执行结果,同时添加错误日志便于排查问题。
  3. 优化IAM权限:将DynamoDB权限缩小到仅PutItem操作,日志权限也限制为必要的创建和写入操作,遵循最小权限原则。
  4. 添加依赖关系:给自定义资源InitializeDynamoDB加上DependsOn: DynamoDB,确保Lambda执行时表已经创建完成。

内容的提问来源于stack exchange,提问作者Shubhanshu Bhadouria

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 17:53:15