-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDeployment.py
More file actions
99 lines (73 loc) · 2.74 KB
/
Deployment.py
File metadata and controls
99 lines (73 loc) · 2.74 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
import boto3
import time
# methods to launch cloudformation stacks
def check_health(loadbalancer, Arn, target_id, port):
response = loadbalancer.describe_target_health(
TargetGroupArn = Arn,
Targets = [
{
'Id': target_id,
'Port': port
},
]
)
targethealth = response['TargetHealthDescriptions'][0]['TargetHealth']['State']
return targethealth
def get_target_ids(asgroup, groupname):
# this method needs to be modified if asg has more than 100 instances (pagination)
response = asgroup.describe_auto_scaling_groups(
AutoScalingGroupNames = [
groupname
],
)
instancecount = response['AutoScalingGroups'][0]['DesiredCapacity']
target_ids = []
for i in range(instancecount):
target_ids.append(response['AutoScalingGroups'][0]['Instances'][i]['InstanceId'])
return target_ids
def switch_asg(loadbalancer, Arn, target_id, port):
response = loadbalancer.register_targets(
TargetGroupArn = Arn,
Targets=[
{
'Id': target_id,
'Port': port
},
]
)
if not (response['ResponseMetadata']['HTTPStatusCode'] == '200'):
return "Error: Unexpected Response{}".format(response)
def roll_back(loadbalancer, target_id, Arn, port):
response = loadbalancer.deregister_targets(
TargetGroupArn = Arn,
Targets = [
{
'Id': target_id,
'Port': port
},
]
)
if not (response['ResponseMetadata']['HTTPStatusCode'] == '200'):
return "Error: Unexpected Response{}".format(response)
if __name__ == '__main__':
asg = boto3.client('autoscaling', region_name='us-east-1')
alb = boto3.client('elbv2', region_name='us-east-1')
arn = '' # <!-- insert ARN string HERE -->
port = 80
green_asgname = '' # <!-- insert launch config names here -->
blue_asgname = ''
# get target ids and do the loop logic here
green_targets = get_target_ids(asg, green_asgname)
for i in green_targets:
print "switching to green stack"
switch_asg(alb, arn, i, port)
#time.sleep(120) # delay for two minutes to make sure health checks are passed
targethealth = check_health(alb, arn, i, port)
if (targethealth == 'unhealthy'):
print "error in green stack. Rolling back!!!"
roll_back(alb, i, arn, port)
if (targethealth == 'healthy'):
print "retiring blue stack!"
blue_targets = get_target_ids(asg, blue_asgname)
for j in blue_targets:
roll_back(alb, j, arn, port)