-
Notifications
You must be signed in to change notification settings - Fork 0
/
create_resources.py
184 lines (161 loc) · 5.59 KB
/
create_resources.py
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
import argparse
import base64
import json
import os
import uuid
import boto3
AUTH_KEY_PARAM_NAME = '/positive-app/auth-key'
TABLES = {
'team': {
'prefix': 'team-app',
'env_var': 'TEAM_TABLE_NAME',
'hash_key': 'team_id',
},
'subscriptions': {
'prefix': 'subscriptions-app',
'env_var': 'SUBSCRIPTIONS_TABLE_NAME',
'hash_key': 'ID',
'range_key': 'CreatedDate'
}
}
# TODO add nice sqs queue
QUEUES = {
'events': {
'prefix': 'positive-events',
'env_var': 'EVENTS_QUEUE_NAME',
'attributes': {
'channel_id': str,
'user_id': str,
'message': str
}
},
'subscriptions': {
'prefix': 'positive-subscriptions',
'env_var': 'SUBSCRIPTIONS_QUEUE_NAME',
'attributes': {
'text': str
}
}
}
def create_table(table_name_prefix, hash_key, range_key=None):
table_name = '%s-%s' % (table_name_prefix, str(uuid.uuid4()))
client = boto3.client('dynamodb')
key_schema = [
{
'AttributeName': hash_key,
'KeyType': 'HASH',
}
]
attribute_definitions = [
{
'AttributeName': hash_key,
'AttributeType': 'S',
}
]
if range_key is not None:
key_schema.append({'AttributeName': range_key, 'KeyType': 'RANGE'})
attribute_definitions.append(
{'AttributeName': range_key, 'AttributeType': 'S'})
client.create_table(
TableName=table_name,
KeySchema=key_schema,
AttributeDefinitions=attribute_definitions,
ProvisionedThroughput={
'ReadCapacityUnits': 10,
'WriteCapacityUnits': 10,
}
)
waiter = client.get_waiter('table_exists')
waiter.wait(TableName=table_name, WaiterConfig={'Delay': 1})
return table_name
def create_queue(queue_name_prefix):
queue_name = '%s-%s' % (queue_name_prefix, str(uuid.uuid4()))
client = boto3.client('sqs')
client.create_queue(
QueueName=queue_name,
Attributes={
'VisibilityTimeout': 60
}
)
return queue_name
def record_as_env_var(key, value, stage):
with open(os.path.join('.chalice', 'config.json')) as f:
data = json.load(f)
data['stages'].setdefault(stage, {}).setdefault(
'environment_variables', {}
)[key] = value
with open(os.path.join('.chalice', 'config.json'), 'w') as f:
serialized = json.dumps(data, indent=2, separators=(',', ': '))
f.write(serialized + '\n')
def _already_in_config(env_var, stage):
with open(os.path.join('.chalice', 'config.json')) as f:
return env_var in json.load(f)['stages'].get(
stage, {}).get('environment_variables', {})
def create_auth_key_if_needed(stage):
ssm = boto3.client('ssm')
try:
ssm.get_parameter(Name=AUTH_KEY_PARAM_NAME)
except ssm.exceptions.ParameterNotFound:
print(f"Generating auth key.")
kms = boto3.client('kms')
random_bytes = kms.generate_random(NumberOfBytes=32)['Plaintext']
encoded_random_bytes = base64.b64encode(random_bytes).decode()
ssm.put_parameter(Name=AUTH_KEY_PARAM_NAME, Value=encoded_random_bytes,
Type='SecureString')
def create_resources(args):
for table_config in TABLES.values():
# We assume if it a value is recorded in the Chalice config
# file, the table already exists.
if _already_in_config(table_config['env_var'], args.stage):
continue
print(f"Creating table: {table_config['prefix']}")
table_name = create_table(
table_config['prefix'], table_config['hash_key'],
table_config.get('range_key')
)
record_as_env_var(table_config['env_var'], table_name, args.stage)
for queue_config in QUEUES.values():
if _already_in_config(queue_config['env_var'], args.stage):
continue
print(f"Creating queue: {queue_config['prefix']}")
queue_name = create_queue(
queue_config['prefix']
)
record_as_env_var(queue_config['env_var'], queue_name, args.stage)
create_auth_key_if_needed(args.stage)
def cleanup_resources(args):
ddb = boto3.client('dynamodb')
ssm = boto3.client('ssm')
with open(os.path.join('.chalice', 'config.json')) as f:
config = json.load(f)
env_vars = config['stages'].get(args.stage, {}).get(
'environment_variables', {})
for key in list(env_vars):
value = env_vars.pop(key)
if key.endswith('_TABLE_NAME'):
print(f"Deleting table: {value}")
ddb.delete_table(TableName=value)
if not env_vars:
del config['stages'][args.stage]['environment_variables']
try:
print(f"Deleting SSM param: {AUTH_KEY_PARAM_NAME}")
ssm.delete_parameter(Name=AUTH_KEY_PARAM_NAME)
except Exception:
pass
with open(os.path.join('.chalice', 'config.json'), 'w') as f:
serialized = json.dumps(config, indent=2, separators=(',', ': '))
f.write(serialized + '\n')
print("Resources deleted. If you haven't already, be "
"sure to run 'chalice delete' to delete your Chalice application.")
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-s', '--stage', default='dev')
parser.add_argument('-c', '--cleanup', action='store_true')
# users - stores the user data.
args = parser.parse_args()
if args.cleanup:
cleanup_resources(args)
else:
create_resources(args)
if __name__ == '__main__':
main()