gpt4 book ai didi

amazon-web-services - 如何使用云形成模板在 dynamodb 表中创建项目条目?

转载 作者:行者123 更新时间:2023-12-03 07:47:23 25 4
gpt4 key购买 nike

我有一个云形成模板,我正在使用该模板将 lamdba 函数和一个 dynamo db 表部署到第三方 aws 帐户中,现在我想使用相同的云形成模板在创建的 dynamo db 表中创建条目。有人可以帮忙吗?

我尝试过以下云形成模板,但它不起作用 -

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:*
Resource: "*"
- Effect: Allow
Action:
- logs:*
Resource: "*"
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) {
response.send(event, context, "FAILED", {});
} else {
response.send(event, context, "SUCCESS", {});
}

// Send signal to WaitCondition
const cloudformation = new AWS.CloudFormation();
const signalParams = {
UniqueId: event.ResourceProperties.WaitConditionId,
};

cloudformation.signalResource(signalParams, function(signalErr, signalData) {
if (signalErr) {
console.log("Error sending signal to WaitCondition:", signalErr);
} else {
console.log("Signal sent to WaitCondition");
}
});
});
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

InitWaitCondition:
Type: AWS::CloudFormation::WaitCondition
DependsOn: InitFunction
Properties:
Handle: !Ref InitWaitConditionHandle
Timeout: '300'
Count: 1

InitWaitConditionHandle:
Type: AWS::CloudFormation::WaitConditionHandle

InitializeDynamoDB:
Type: Custom::InitFunction
Properties:
ServiceToken: !GetAtt InitFunction.Arn
DynamoTableName: !Ref DynamoDB
WaitConditionHandle: !Ref InitWaitConditionHandle

最佳答案

你必须开发一个custom resource在 CloudFormation 中。这将采用 Lambda 函数的形式,该函数将使用 AWS SDK 填充您的 DynamoDB 表。

关于amazon-web-services - 如何使用云形成模板在 dynamodb 表中创建项目条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76514001/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com