-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdeploy.py
executable file
·438 lines (374 loc) · 15.8 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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
#!/usr/bin/env python3
"""Command-line utility to deploy an AWS ECS Service as well as some helper functions"""
import os
import re
import datetime
import json
import yaml
import boto3
import botocore
def get_priority(rules):
"""Returns the next available priority when given the response from aws elbv2 describe-rules"""
priorities = [rule['Priority'] for rule in rules]
i = 1
rule_priority = None
while not rule_priority: # increment from 1 onwards until we find a priority that is unused
if not str(i) in priorities:
return i
else:
i = i + 1
def create_or_update_stack(stack_name, template, parameters, tags):
"""Update or create stack synchronously, returns the stack ID"""
cloudformation = boto3.client('cloudformation')
template_data = _parse_template(template)
params = {
'StackName': stack_name,
'TemplateBody': template_data,
'Parameters': parameters,
'Tags': tags
}
try:
if _stack_exists(stack_name):
print('Updating {}'.format(stack_name))
stack_result = cloudformation.update_stack(**params)
waiter = cloudformation.get_waiter('stack_update_complete')
else:
print('Creating {}'.format(stack_name))
stack_result = cloudformation.create_stack(**params)
waiter = cloudformation.get_waiter('stack_create_complete')
print("...waiting for stack to be ready...")
waiter.wait(StackName=stack_name)
except botocore.exceptions.ClientError as ex:
error_message = ex.response['Error']['Message']
if error_message == 'No updates are to be performed.':
print("No changes")
else:
raise
else:
return cloudformation.describe_stacks(StackName=stack_result['StackId'])
def _parse_template(template):
cloudformation = boto3.client('cloudformation')
cloudformation.validate_template(TemplateBody=template)
return template
def _stack_exists(stack_name):
cloudformation = boto3.client('cloudformation')
try:
response = cloudformation.describe_stacks(
StackName=stack_name
)
stacks = response['Stacks']
except (KeyError, botocore.exceptions.ClientError):
return False
for stack in stacks:
if stack['StackStatus'] == 'DELETE_COMPLETE':
continue
if stack_name == stack['StackName']:
return True
return False
def generate_environment_object():
"""Given a .env file, returns an environment object as per https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions.html#cloudformationn-ecs-taskdefinition-containerdefinition-environment
Values are pulled from the running environment."""
whitelisted_vars = [
"AWS_SECRET_ACCESS_KEY",
"AWS_SESSION_TOKEN",
"AWS_ACCESS_KEY_ID",
"AWS_SECURITY_TOKEN",
"AWS_PROFILE",
"AWS_DEFAULT_REGION"
]
environment = []
env_file = open(os.environ.get('DOTENV', '.env'), 'r').read()
for env in env_file.split('\n'):
env = env.split('=')[0]
if env not in whitelisted_vars and env != '' and not re.match(r'^\s?#', env) and os.environ.get(env, None) is not None:
environment.append(
{
"name": env,
"value": os.environ[env]
}
)
return environment
def get_list_of_rules(app_stack_name):
"""Given a CloudFormation stack name, returns a list of routing rules present on the stack's ALB"""
cloudformation = boto3.client('cloudformation')
response = cloudformation.describe_stack_resources(
StackName=app_stack_name,
LogicalResourceId='ALBListenerSSL'
)
alb_listener = response['StackResources'][0]['PhysicalResourceId']
client = boto3.client('elbv2')
response = client.describe_rules(ListenerArn=alb_listener)
return response['Rules']
def _update_container_defs_with_env(task_definition):
"""merge each container definition with environment variables"""
environment = generate_environment_object()
if not environment:
return task_definition
for container_definition in task_definition['containerDefinitions']:
if 'environment' not in container_definition:
container_definition['environment'] = environment
continue
for env_name_value in environment:
env_found_in_definition = False
for container_env_name_value in container_definition['environment']:
if container_env_name_value['name'] == env_name_value['name']:
container_env_name_value['value'] = env_name_value['value']
env_found_in_definition = True
if not env_found_in_definition:
container_definition['environment'].append(env_name_value)
return task_definition
def upload_task_definition(task_definition):
"""Interpolates some values and then uploads the task definition to ECS
Returns the task definition version ARN"""
print("Task definition to be uploaded:")
print(json.dumps(task_definition, indent=2, default=str))
print("Uploading Task Definition...")
ecs = boto3.client('ecs')
response = ecs.register_task_definition(**task_definition)
task_definition_arn = response['taskDefinition']['taskDefinitionArn']
print("Task Definition ARN: {}".format(task_definition_arn))
return task_definition_arn
def get_parameters(config, version_stack_name, app_stack_name, task_definition, app_name, cluster_name, env, version, aws_hosted_zone, base_path, task_definition_arn): # pylint: disable=too-many-arguments,too-many-locals
"""Generates and returns necessary parameters for CloudFormation stack"""
print("Generating Parmeters for CloudFormation template")
container_port = [x['portMappings'][0]['containerPort'] for x in task_definition['containerDefinitions'] if x['name'] == app_name][0]
cloudformation = boto3.client('cloudformation')
print("Determining ALB Rule priority...")
priority = None
listener_rule = None
try:
response = cloudformation.describe_stack_resources(
StackName=version_stack_name,
LogicalResourceId='ListenerRule'
)
listener_rule = response['StackResources'][0]['PhysicalResourceId']
print("Listener Rule already exists, not setting priority.")
except (KeyError, IndexError, botocore.exceptions.ClientError):
print("Listener Rule does not already exist, getting priority...")
if listener_rule is None:
rules = get_list_of_rules(app_stack_name)
priority = get_priority(rules)
print("Rule priority is {}.".format(priority))
print("Determining if ALB is internal or internet-facing...")
elbv2 = boto3.client('elbv2')
response = cloudformation.describe_stack_resources(
StackName=app_stack_name,
LogicalResourceId='ALB'
)
alb = response['StackResources'][0]['PhysicalResourceId']
response = elbv2.describe_load_balancers(
LoadBalancerArns=[alb],
)
alb_scheme = response['LoadBalancers'][0]['Scheme']
print("ALB is {}.".format(alb_scheme))
try:
autoscaling = str(config['autoscaling'])
autoscaling_target = str(config['autoscaling_target'])
autoscaling_max_size = str(config['autoscaling_max_size'])
autoscaling_min_size = str(config['autoscaling_min_size'])
except KeyError as exception:
print("Autoscaling parameter missing, disabling autoscaling ({})".format(exception))
autoscaling = None
autoscaling_target = None
autoscaling_max_size = None
autoscaling_min_size = None
parameters = [
{
"ParameterKey": "Name",
"ParameterValue": app_name
},
{
"ParameterKey": 'ClusterName',
"ParameterValue": cluster_name
},
{
"ParameterKey": 'Environment',
"ParameterValue": env
},
{
"ParameterKey": 'Version',
"ParameterValue": version
},
{
"ParameterKey": 'HealthCheckPath',
"ParameterValue": config['lb_health_check']
},
{
"ParameterKey": 'HealthCheckGracePeriod',
"ParameterValue": str(config['lb_health_check_grace_period'])
},
{
"ParameterKey": 'HealthCheckTimeout',
"ParameterValue": str(config['lb_health_check_timeout'])
},
{
"ParameterKey": 'HealthCheckInterval',
"ParameterValue": str(config['lb_health_check_interval'])
},
{
"ParameterKey": 'ContainerPort',
"ParameterValue": str(container_port)
},
{
"ParameterKey": 'Domain',
"ParameterValue": aws_hosted_zone
},
{
"ParameterKey": 'Path',
"ParameterValue": base_path
},
{
"ParameterKey": 'TaskDefinitionArn',
"ParameterValue": task_definition_arn
},
{
"ParameterKey": 'AlbScheme',
"ParameterValue": alb_scheme
},
{
"ParameterKey": 'Autoscaling',
"ParameterValue": autoscaling
},
{
"ParameterKey": 'AutoscalingTargetValue',
"ParameterValue": autoscaling_target
},
{
"ParameterKey": 'AutoscalingMaxSize',
"ParameterValue": autoscaling_max_size
},
{
"ParameterKey": 'AutoscalingMinSize',
"ParameterValue": autoscaling_min_size
},
{
"ParameterKey": 'ECSServiceName',
"ParameterValue": "{}-ECSService".format(version_stack_name)
},
{
"ParameterKey": 'ECSServiceSecurityClassification',
"ParameterValue": str(config['security_classification'])
},
{
"ParameterKey": 'ECSServiceSecurityDataType',
"ParameterValue": str(config['security_data_type'])
},
{
"ParameterKey": 'ECSServiceSecurityAccessibility',
"ParameterValue": str(config['security_accessibility'])
}
]
parameters = [x for x in parameters if x['ParameterValue'] is not None] # remove all keys that have a value of None
if priority is not None:
parameters.append({
"ParameterKey": 'RulePriority',
"ParameterValue": str(priority)
})
else:
parameters.append({
"ParameterKey": 'RulePriority',
"UsePreviousValue": True
})
print("Finished generating parameters:")
for param in parameters:
print("{:30}{}".format(param['ParameterKey'] + ':', param.get('ParameterValue', None)))
return parameters
def check_deployment(version_stack_name, app_name):
"""Poll deployment until it is succesful, raise exception if not"""
print("Polling Target Group ({}) until a successful state is reached...".format(version_stack_name))
elbv2 = boto3.client('elbv2')
waiter = elbv2.get_waiter('target_in_service')
cloudformation = boto3.client('cloudformation')
response = cloudformation.describe_stack_resources(
StackName=version_stack_name,
LogicalResourceId='ALBTargetGroup'
)
target_group = response['StackResources'][0]['PhysicalResourceId']
start_time = datetime.datetime.now()
try:
waiter.wait(TargetGroupArn=target_group)
except botocore.exceptions.WaiterError:
print('Health check did not pass!')
response = cloudformation.describe_stack_resources(
StackName=version_stack_name,
LogicalResourceId='ECSService'
)
service = response['StackResources'][0]['PhysicalResourceId']
print('Outputting events for service {}:'.format(service))
response = cloudformation.describe_stack_resources(
StackName="ECS-{}".format(app_name),
LogicalResourceId='ECSCluster'
)
cluster = response['StackResources'][0]['PhysicalResourceId']
ecs = boto3.client('ecs')
response = ecs.describe_services(
cluster=cluster,
services=[service]
)
for event in [x['message'] for x in response['services'][0]['events']]:
print(event)
# print('Deleting CloudFormation stack...')
# response = cloudformation.delete_stack(
# StackName="MV-{realm}-{app_name}-{version}-{env}".format(env=os.environ['ENV'], app_name=os.environ['ECS_APP_NAME'], version=os.environ['BUILD_VERSION'], realm=os.environ['REALM'])
# )
# waiter = cf.get_waiter('stack_delete_complete')
# waiter.wait(
# StackName="MV-{realm}-{app_name}-{version}-{env}".format(env=os.environ['ENV'], app_name=os.environ['ECS_APP_NAME'], version=os.environ['BUILD_VERSION'], realm=os.environ['REALM'])
# )
# print('CloudFormation stack deleted.')
elapsed_time = datetime.datetime.now() - start_time
print('Health check passed in {}'.format(elapsed_time))
print("Done.")
def deploy_ecs_service(app_name, env, cluster_name, version, aws_hosted_zone, base_path, config, task_definition, template): # pylint: disable=too-many-arguments,too-many-locals,too-many-branches,too-many-statements
"""Core function for deploying an ECS Service"""
print("Beginning deployment of {}...".format(app_name))
version_stack_name = "ECS-{cluster_name}-App-{app_name}-{version}".format(
cluster_name=cluster_name,
app_name=app_name,
version=version
)
app_stack_name = "ECS-{cluster}-App-{app}".format(cluster=cluster_name, app=app_name)
task_definition = _update_container_defs_with_env(task_definition)
task_definition_arn = upload_task_definition(task_definition)
parameters = get_parameters(
config=config,
version_stack_name=version_stack_name,
app_stack_name=app_stack_name,
task_definition=task_definition,
app_name=app_name,
cluster_name=cluster_name,
env=env,
version=version,
aws_hosted_zone=aws_hosted_zone,
base_path=base_path,
task_definition_arn=task_definition_arn
)
print("Deploying CloudFormation stack: {}".format(version_stack_name))
start_time = datetime.datetime.now()
response = create_or_update_stack(version_stack_name, template, parameters, config['stack_tags'])
elapsed_time = datetime.datetime.now() - start_time
print("CloudFormation stack deploy completed in {}.".format(elapsed_time))
cloudformation = boto3.client('cloudformation')
response = cloudformation.describe_stacks(
StackName=version_stack_name
)
outputs = response['Stacks'][0]['Outputs']
print("CloudFormation stack outputs:")
for output in outputs:
print("{:30}{}".format(output['OutputKey'] + ':', output.get('OutputValue', None)))
check_deployment(version_stack_name, app_name)
def main():
"""Entrypoint for CLI"""
template_path = os.environ.get('ECS_APP_VERSION_TEMPLATE_PATH', '/scripts/ecs-cluster-application-version.yml')
app_name = os.environ['ECS_APP_NAME']
env = os.environ['ENV']
cluster_name = os.environ['ECS_CLUSTER_NAME']
version = os.environ['BUILD_VERSION']
aws_hosted_zone = os.environ['AWS_HOSTED_ZONE']
base_path = os.environ['BASE_PATH']
config = yaml.safe_load(open('deployment/ecs-config-env.yml', 'r').read())
task_definition = json.loads(open('deployment/ecs-env.json', 'r').read())
template = open(template_path, 'r').read()
deploy_ecs_service(app_name=app_name, env=env, cluster_name=cluster_name, version=version, aws_hosted_zone=aws_hosted_zone, base_path=base_path, config=config, task_definition=task_definition, template=template)
if __name__ == "__main__":
main()