skip to Main Content

I want to create a dynamo db table using cloud formation template and then i want to create entries in that table using the same cloud formation template in a single stack. Can someone tell how this can be achieved , it is possible or not ?

I tried using the custom resources lambda function but it does not work

2

Answers


  1. I have not tested it but the CloudFormation entity has an attribute ImportSourceSpecification (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-table-importsourcespecification.html)

    And DynamoDB supports import from S3 (https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/S3DataImport.Requesting.html)

    To be tested.

    Login or Signup to reply.
  2. Here is a small example that creates a table and adds 5 items:

    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' };
                  response.send(event, context, response.SUCCESS, responseData);
                } catch (error) {
                  console.log(error)
                  const responseData = { Error: 'Something went wrong' };
                  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
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search