-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdeploy.py
291 lines (260 loc) · 10 KB
/
deploy.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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
#!/usr/bin/env python3
import json
import uuid
import argparse
import io
import zipfile
import boto3
def jsondict(s):
d = json.loads(s)
assert isinstance(d, dict)
return d
def zip_files(filenames):
"""
Map a collection of files into a zip file with the same name and paths.
"""
sso = io.BytesIO()
with zipfile.ZipFile(sso, "w") as zfile:
for fname in filenames:
zfile.write(fname)
sso.seek(0)
return sso.read()
def main():
parser = argparse.ArgumentParser(
description="Deploy a scorecard stack with the given parameters")
parser.add_argument(
"--code-bucket",
required=True,
help="""The bucket that is used to store code zipfiles for reference
in the CloudFormation template.""")
parser.add_argument(
"--stack-name",
required=True,
help="""The name of the stack to bring up. If the stack exists, it is
updated instead.""")
parser.add_argument(
"--registration-email-source",
required=True,
help=
"""The email address to use as the source of an email to new registrants."""
)
parser.add_argument(
"--hmac-secret",
required=False,
default=None,
help=
"""HMAC secret used during registration flow. Required if registration-email-source is set."""
)
parser.add_argument(
"--backend-type",
required=False,
default="DynamoDB",
help="""Indicates backend implementation for scorekeeping.""")
# help="""Indicates either a DynamoDB or S3 backend for score-keeping.
# If omitted, the previous the default for new stacks is DynamoDB, and
# for stack updates, the existing value is preserved. Allowable values are
# "DynamoDB" and "S3". If set to "S3" then both --backend-s3-bucket and
# --backend-s3-prefix must be specified.""")
# parser.add_argument(
# "--backend-s3-bucket",
# required=False,
# default=None,
# help="Bucket to use for S3 backend for scorekeeping")
# parser.add_argument(
# "--backend-s3-prefix",
# required=False,
# default=None,
# help="Prefix to use for S3 backend for scorekeeping")
parser.add_argument(
"--score-cache-lifetime",
required=False,
default=None,
help="Duration (in seconds) for lambda functions to cache team scores."
)
parser.add_argument(
"--flag-cache-lifetime",
required=False,
default=None,
help="Duration (in seconds) for lambda functions to cache game flags.")
parser.add_argument(
"--cfn-tags",
required=False,
type=jsondict,
default=dict(),
help=
"""A list of tags as a dict to use as tag keys and values for the CloudFormation stack."""
)
parser.add_argument(
"--registration-mode",
required=False,
default="Open",
type=lambda v: {k:k for k in ["Open", "Closed"]}[v],
help="""
Determines whether to permit registration from emails that aren't already in the DB.
This does not exempt registrants from confirming their email address, as we still need to
know that we can contact them at that address."""
)
pargs = parser.parse_args()
if pargs.registration_email_source is not None and pargs.hmac_secret is None:
print("If using email registration, the HMAC secret must be provided.")
exit(1)
if pargs.backend_type is not None:
if pargs.backend_type not in ["DynamoDB"]: #["S3", "DynamoDB"]:
print("Backend type must be one of: S3, DynamoDB")
exit(1)
elif pargs.backend_type == "S3":
if pargs.backend_s3_bucket is None or pargs.backend_s3_prefix is None:
print(
"If backend type is S3, both bucket and prefix must be specified."
)
exit(2)
print("Building code zip files for deployment...")
tally_code = (str(uuid.uuid4()),
zip_files([
"ScoreCardTally.py", "S3KeyValueStore.py",
"XrayChain.py", "util.py"
]))
submit_code = (str(uuid.uuid4()),
zip_files([
"ScoreCardSubmit.py", "S3KeyValueStore.py",
"XrayChain.py", "util.py"
]))
register_code = (str(uuid.uuid4()),
zip_files(["Register.py", "XrayChain.py", "util.py"]))
print("Uploading code zip files to S3 bucket (%s)..." % pargs.code_bucket)
s3_client = boto3.client("s3")
for code in [tally_code, submit_code, register_code]:
print(" Uploading %s.zip" % code[0])
s3_client.put_object(Bucket=pargs.code_bucket,
Key="%s.zip" % code[0],
Body=code[1])
cfn_client = boto3.client("cloudformation")
print("Determining stack operation...")
try:
stack_description = cfn_client.describe_stacks(
StackName=pargs.stack_name)
print(" Stack Update selected")
except:
print(" Stack create selected")
stack_description = None
print("Building stack parameters...")
stack_params = []
if pargs.registration_email_source is not None:
stack_params.append({
"ParameterKey": "SESEmailSource",
"ParameterValue": pargs.registration_email_source
})
if pargs.registration_mode is not None:
stack_params.append({
"ParameterKey": "RegistrationMode",
"ParameterValue": pargs.registration_mode
})
if pargs.hmac_secret is not None:
stack_params.append({
"ParameterKey": "HMACSecret",
"ParameterValue": pargs.hmac_secret
})
if stack_description is not None:
stack_params.append({
"ParameterKey": "XraySampleRate",
"UsePreviousValue": True
})
stack_params.append({
"ParameterKey": "CodeSourceBucket",
"ParameterValue": pargs.code_bucket
})
stack_params.append({
"ParameterKey": "CodeSourceTallyObject",
"ParameterValue": tally_code[0] + ".zip"
})
stack_params.append({
"ParameterKey": "CodeSourceSubmitObject",
"ParameterValue": submit_code[0] + ".zip"
})
stack_params.append({
"ParameterKey": "CodeSourceRegisterObject",
"ParameterValue": register_code[0] + ".zip"
})
if pargs.backend_type is None:
if stack_description is None:
print(" Using default backend configuration")
else:
print(" Using previous backend configuration")
stack_params.append({
"ParameterKey": "KeyValueBackend",
"UsePreviousValue": True
})
elif pargs.backend_type == "S3":
print(" Configuring S3 backend (%s, %s)" %
(pargs.backend_s3_bucket, pargs.backend_s3_prefix))
stack_params.append({
"ParameterKey": "KeyValueBackend",
"ParameterValue": "S3"
})
elif pargs.backend_type == "DynamoDB":
print(" Configuring DynamoDB backend")
stack_params.append({
"ParameterKey": "KeyValueBackend",
"ParameterValue": "DynamoDB"
})
if pargs.score_cache_lifetime is not None:
print(" Setting new score cache timeout")
stack_params.append({
"ParameterKey": "ScoreCacheLifetime",
"ParameterValue": str(pargs.score_cache_lifetime)
})
elif stack_description is not None:
stack_params.append({
"ParameterKey": "ScoreCacheLifetime",
"UsePreviousValue": True
})
if pargs.flag_cache_lifetime is not None:
print(" Setting new flag cache timeout")
stack_params.append({
"ParameterKey": "FlagCacheLifetime",
"ParameterValue": str(pargs.flag_cache_lifetime)
})
elif stack_description is not None:
stack_params.append({
"ParameterKey": "FlagCacheLifetime",
"UsePreviousValue": True
})
print("Reading cloudformation template...")
with open("cloudformation.yaml") as fp:
template_body = fp.read()
if stack_description is None:
print("Creating stack...")
cfn_client.create_stack(StackName=pargs.stack_name,
TemplateBody=template_body,
Parameters=stack_params,
Tags=[{
"Key": key,
"Value": value
} for key, value in pargs.cfn_tags.items()],
Capabilities=['CAPABILITY_IAM'])
waiter = cfn_client.get_waiter('stack_create_complete')
else:
print("Updating stack...")
cfn_client.update_stack(StackName=pargs.stack_name,
TemplateBody=template_body,
Parameters=stack_params,
Tags=[{
"Key": key,
"Value": value
} for key, value in pargs.cfn_tags.items()],
Capabilities=['CAPABILITY_IAM'])
waiter = cfn_client.get_waiter('stack_update_complete')
print("Waiting for stack operation to complete...")
waiter.wait(StackName=pargs.stack_name)
api_resource = cfn_client.describe_stack_resources(
StackName=pargs.stack_name,
LogicalResourceId='API')['StackResources'][0]['PhysicalResourceId']
if stack_description is not None:
print("Creating new API Gateway deployment...")
apig_client = boto3.client('apigateway')
apig_client.create_deployment(restApiId=api_resource, stageName='Main')
print("Stack operation complete.")
print("API URL: https://%s.execute-api.%s.amazonaws.com/Main" %
(api_resource, boto3.Session().region_name))
if __name__ == "__main__":
main()