gpt4 book ai didi

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

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

我想使用云形成模板创建一个发电机数据库表,然后我想在单个堆栈中使用相同的云形成模板在该表中创建条目。有人能告诉我如何实现这一点吗?可能吗?

我尝试使用自定义资源 lambda 函数,但它不起作用

最佳答案

这是一个创建表格并添加 5 个项目的小示例:

AWSTemplateFormatVersion: '2010-09-09'
Resources:
MyDynamoDBTable:
Type: 'AWS::DynamoDB::Table'
Properties:
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: pk
AttributeType: S
- AttributeName: sk
AttributeType: S
KeySchema:
- AttributeName: pk
KeyType: HASH
- AttributeName: sk
KeyType: RANGE
MyCustomResourceLambdaFunction:
Type: 'AWS::Lambda::Function'
Properties:
Runtime: nodejs14.x
Handler: index.handler
Role: !GetAtt MyLambdaExecutionRole.Arn
Environment:
Variables:
tableName: !Ref MyDynamoDBTable
Code:
ZipFile: |
const AWS = require('aws-sdk');
const client = new AWS.DynamoDB();
const dynamodb = new AWS.DynamoDB.DocumentClient();
const response = require('cfn-response');

exports.handler = async (event, context) => {
try {
const tableName = process.env.tableName
console.log(tableName)
var params = {
'TableName': tableName
};

client.waitFor('tableExists', params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});

const itemsToAdd = [
{ pk: 'item1', sk: 'sortKey1', otherAttribute: 'value1' },
{ pk: 'item2', sk: 'sortKey2', otherAttribute: 'value2' },
{ pk: 'item3', sk: 'sortKey3', otherAttribute: 'value3' },
{ pk: 'item4', sk: 'sortKey4', otherAttribute: 'value4' },
{ pk: 'item5', sk: 'sortKey5', otherAttribute: 'value5' },
];

const putItemPromises = itemsToAdd.map((item) => {
const params = {
TableName: tableName,
Item: item,
};
return dynamodb.put(params).promise();
});

await Promise.all(putItemPromises).then(res=>console.log(res)).catch(err=>console.log(err))

const responseData = { Result: 'Items added successfully' };
await response.send(event, context, response.SUCCESS, responseData);
} catch (error) {
console.log(error)
const responseData = { Error: 'Something went wrong' };
await response.send(event, context, response.FAILED, responseData);
}
};
Timeout: 30
MyLambdaExecutionRole:
Type: 'AWS::IAM::Role'
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: 'sts:AssumeRole'
ManagedPolicyArns:
- 'arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole'
- 'arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess'
MyCustomResource:
Type: 'Custom::MyCustomResource'
Properties:
ServiceToken: !GetAtt MyCustomResourceLambdaFunction.Arn

全文here

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

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