Memphis Meng
Memphis Meng

Reputation: 1681

Avoid re-creating DynamoDB tables in CloudFormation stack when they already exist

I need to create some dynamodb tables for a project as the resources in CloudFormation. However, if I put the creation part(shown in part 1) in my yaml file, the building always fail if the tables already exist. That makes a huge trouble because we need to keep maintaining the service so we expect to build the stack over and over again. What can we do on the template file so we don't need to always delete the tables as well as the data in the tables?

Part 1: example table building:

  Table: 
    Type: AWS::DynamoDB::Table
    DeletionPolicy: Delete
    Properties:
      BillingMode: PAY_PER_REQUEST 
      AttributeDefinitions: 
        - 
          AttributeName: "event_id"
          AttributeType: "S"
      KeySchema: 
        - 
          AttributeName: "event_id"
          KeyType: "HASH"
      StreamSpecification:
        StreamViewType: NEW_AND_OLD_IMAGES
      TableName: !Sub my-table-${Environment}

Part 2: stack build command: sam build --template cfn-template.yml

Upvotes: 2

Views: 1491

Answers (1)

Asdfg
Asdfg

Reputation: 12248

Change DeletionPolicy: Delete to DeletionPolicy: Retain. After that, when you delete the CFT, it will not delete the DynamoDB table. However, when you re-deploy your CFT, it will fail as the table already exists. To avoid that, add a new parameter called something like DoCreateTable and specify Yes or No. Create a condition based on the value of DoCreateTable parameter and conditionally create DynamoDB table.

Upvotes: 4

Related Questions