AWS: CloudFormation example creating DynamoDB table and IAM
Let me share an example of the CloudFormation configuration to create DynamoDB tables and an IAM user with particular policy to use it from some applications.
I’ll create two tables for stage and production with TTL and also I set PAY_PER_REQUEST. So first, create the following YAML file as template.yml.
1AWSTemplateFormatVersion: "2010-09-09"
2Description: "DynamoDB and IAM"
3
4Resources:
5 Policy:
6 Type: 'AWS::IAM::ManagedPolicy'
7 Properties:
8 Path: /
9 PolicyDocument:
10 Version: 2012-10-17
11 Statement:
12 - Effect: Allow
13 Action:
14 - dynamodb:List*
15 - dynamodb:DescribeReservedCapacity*
16 - dynamodb:DescribeLimits
17 - dynamodb:DescribeTimeToLive
18 Resource:
19 - "*"
20
21 - Effect: Allow
22 Action:
23 - dynamodb:DescribeTable
24 - dynamodb:GetItem
25 - dynamodb:Query
26 - dynamodb:Scan
27 - dynamodb:CreateTable
28 - dynamodb:DeleteItem
29 - dynamodb:UpdateItem
30 - dynamodb:UpdateTable
31 - dynamodb:PutItem
32 Resource:
33 - !GetAtt DynamoDBTableUserListProd.Arn
34 - !GetAtt DynamoDBTableUserListStage.Arn
35 User:
36 Type: AWS::IAM::User
37 Properties:
38 ManagedPolicyArns:
39 - !Ref Policy
40 UserName: dynamodb-user-list
41
42 DynamoDBTableUserListProd:
43 Type: AWS::DynamoDB::Table
44 Properties:
45 TableName: "user_list_prod"
46 BillingMode: "PAY_PER_REQUEST"
47 KeySchema:
48 -
49 AttributeName: "user_id"
50 KeyType: "HASH"
51 AttributeDefinitions:
52 -
53 AttributeName: "user_id"
54 AttributeType: "N"
55 ProvisionedThroughput:
56 ReadCapacityUnits: "0"
57 WriteCapacityUnits: "0"
58
59 DynamoDBTableUserListStage:
60 Type: AWS::DynamoDB::Table
61 Properties:
62 TableName: "user_list_stage"
63 BillingMode: "PAY_PER_REQUEST"
64 KeySchema:
65 -
66 AttributeName: "user_id"
67 KeyType: "HASH"
68 AttributeDefinitions:
69 -
70 AttributeName: "user_id"
71 AttributeType: "N"
72 ProvisionedThroughput:
73 ReadCapacityUnits: "0"
74 WriteCapacityUnits: "0"
75 TimeToLiveSpecification:
76 AttributeName: expired_at
77 Enabled: true
And then, create the script as deploy.sh to deploy it.
1#!/bin/bash
2STACK_NAME="DynamoDBTableUserList"
3S3_BUCKET="your_bucket"
4TEMPLATE_FILE='template.yml'
5OUTPUT_YAML='output.yml'
6
7echo -n "Packaging stack..."
8aws cloudformation package \
9--template-file $TEMPLATE_FILE \
10--s3-bucket $S3_BUCKET \
11--output-template-file $OUTPUT_YAML
12echo " Done"
13
14echo -n "Deploying stack... "
15aws cloudformation deploy \
16--template-file $OUTPUT_YAML \
17--stack-name $STACK_NAME \
18--capabilities CAPABILITY_NAMED_IAM CAPABILITY_AUTO_EXPAND
19echo "Done"
And then, execute the above script.
1chmod u+x ./deploy.sh
2./deploy.sh
After that, go to the IAM page in the AWS web site and generate a new key to access the above DynamoDB tables from some applications.
If you want to delete it, execute the following command.
1aws cloudformation delete-stack --stack-name "DynamoDBTableUserList"