This repository was archived by the owner on Feb 2, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbootstrap_dynamodb.py
More file actions
145 lines (124 loc) · 4.23 KB
/
bootstrap_dynamodb.py
File metadata and controls
145 lines (124 loc) · 4.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
#!/usr/bin/env python
# Local development with:
#
# Download URL: http://dynamodb-local.s3-website-us-west-2.amazonaws.com/dynamodb_local_latest.zip
# Start command: java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar -sharedDb -inMemory
#
# Docker option:
#
# docker run -d -v "$PWD":/dynamodb_local_db -p 8000:8000 --network sam-demo cnadiminti/dynamodb-local
# More info: http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBLocal.html
import boto3
import argparse
import uuid
import faker
from boto3.dynamodb.conditions import Key
from botocore.exceptions import ClientError
# Uncomment this for local bootstrapping
dynamodb = boto3.resource(
'dynamodb', region_name='eu-west-1', endpoint_url='http://localhost:8000')
# Uncomment this for non-local bootstrapping
# dynamodb = boto3.resource(
# 'dynamodb', region_name='eu-west-1')
fake = faker.Faker("en.GB")
def create_table(table_name, hash):
"""Creates DynamoDB table with given Hash and Range key as strings"""
print("[+] Creating Table {}...".format(table_name))
params = {
"TableName": table_name,
"KeySchema": [
{
'AttributeName': str(hash),
'KeyType': 'HASH'
}
],
"AttributeDefinitions": [
{
'AttributeName': str(hash),
'AttributeType': 'S'
},
{
'AttributeName': "email",
'AttributeType': 'S'
}
],
"ProvisionedThroughput": {
'ReadCapacityUnits': 5,
'WriteCapacityUnits': 5
},
"GlobalSecondaryIndexes": [
{
'IndexName': 'email-gsi',
'KeySchema': [
{
'AttributeName': 'email',
'KeyType': 'HASH'
},
],
'Projection': {
'ProjectionType': 'ALL'
},
'ProvisionedThroughput': {
'ReadCapacityUnits': 5,
'WriteCapacityUnits': 5
}
},
]
}
table = dynamodb.create_table(**params)
table.meta.client.get_waiter('table_exists').wait(TableName=table_name)
return table
def does_table_exist(table_name):
"""Quick check on table"""
try:
table = dynamodb.Table(table_name)
if "ACTIVE" in table.table_status:
return True
except ClientError as error_message:
return False
def bootstrap_table(table_name):
"""Adds basic data
Ideally this would be a group command to accept params or a file
"""
userId = str(uuid.uuid4())
userEmail = fake.email()
try:
table = dynamodb.Table(table_name)
params = {
"Item": {
"id": userId,
"email": userEmail
}
}
table.put_item(**params) # This format will accept duplicates of same email
response = table.query(
KeyConditionExpression=Key('id').eq(userId)
)
item = response['Items'][0]
print(item)
print("[+] Bootstrapping ran successfully...")
except ClientError as error_message:
print("[!] Failed to bootstrap table with demo data...")
print(error_message)
def main():
# Quick and dirty arg parsing
parser = argparse.ArgumentParser(
description='Quick and dirty create dynamoDB local for demo.')
parser.add_argument(
'-t', '--table', help='Table name to be created', required=True)
parser.add_argument(
'-p', '--hash-key', help='Primary key (Hash key)', required=True)
# parser.add_argument(
# '-r', '--range-key', help='Range key (Range key)', required=True)
args = parser.parse_args()
if does_table_exist(args.table):
print("[*] Table {} already exists! Skipping creation...".format(args.table))
else:
create_table(args.table, args.hash_key)
# create_table(args.table, args.hash_key, args.range_key)
try:
bootstrap_table(args.table)
except Exception as e:
raise Exception("Operation failed due to {0}: ".format(e))
if __name__ == '__main__':
main()