/
fimt-update-cf-stack.py
186 lines (171 loc) · 6.09 KB
/
fimt-update-cf-stack.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
"""
Script Name: fimt-update-cf-stack.py
Purpose: This script is used to take several inputs and execute
cloudformation after referencing chef.
"""
import os
import sys
import getopt
import commands
import time
import boto.cloudformation
import boto
def main():
# Define arguement variables
app = ""
nvtype = ""
env = ""
ver = ""
owner = ""
email = ""
stackname = ""
# Define globals
helpmessage = "fimt-update-cf-stack.py --app <Application> --type <EnvironmentType> --env <ChefEnvironment> --ver <Version> --owner <eid> --email <owneremail> --stackname <aws-cfn-stackname>"
knifefile = "/opt/chef/developer12/developer/knife.rb"
# Check if less than 9 parameters were passed
#if len(sys.argv) < 9:
# print helpmessage
# sys.exit(2)
# Grab parameters and populate variables
try:
opts, args = getopt.getopt(sys.argv[1:],"ha:t:v:o:e:s:",["app=","type=","ver=","owner=","email=","stackname="])
except getopt.GetoptError:
print helpmessage
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print helpmessage
sys.exit(2)
elif opt in ("-a", "--app"):
app = arg
elif opt in ("-t", "--type"):
nvtype = arg
elif opt in ("-v", "--ver"):
ver = arg
elif opt in ("-o", "--owner"):
owner = arg
elif opt in ("-e", "--email"):
email = arg
elif opt in ("-s", "--stackname"):
stackname = arg
else:
print helpmessage
sys.exit(2)
# If any of the variables were blank, echo help and quit
#if (app == '') or (nvtype == '') or (env == '') or (ver == '') or (owner == '') or (email == '') or (stackname == ''):
# print helpmessage
# sys.exit(2)
# Pull Chef Environment default_attributes
chefpull = "/usr/bin/knife environment show -a default_attributes " + app + "_" + nvtype
#+ "_" + env + "_" + ver + " -c " + knifefile + " | sed 1,2d"
print "\nPulling chef environment:\n" + chefpull
defattrib = commands.getoutput(chefpull)
print "\nOutput:\n" + defattrib
diction = dict(item.strip().split(":") for item in defattrib.splitlines())
region = diction["region"].strip()
# Build CFN parameters
cfecho = ""
cfnparams = diction["cfn_inputs"].strip().split(",")
for detail in diction["echo2cfdetails"].strip().split(","):
cfecho = cfecho + "echo " + detail + " >> /tmp/cf_details.txt;"
paramslist = []
for param in cfnparams:
if "TemplateURI" in param:
paramslist.append((param,'https://' + diction[param].strip()))
elif "echo2cfdetails" in param:
paramslist.append((param,cfecho))
else:
paramslist.append((param,diction[param].strip()))
paramslist.append(('OwnerEID',owner))
paramslist.append(('OwnerEmail',email))
paramslist.append(('ApplicationName',app))
paramslist.append(('Environment',nvtype))
print "\nParameters Contents:\n"
print paramslist
# Set S3 Template URL
s3template = "https://" + diction["ParentTemplateS3File"].strip()
# Run CFN command
cfnconn = boto.cloudformation.connect_to_region(region)
print "\nUpdating stack...\n"
cfnoutput = cfnconn.update_stack(stackname, template_url=s3template, parameters=paramslist)
if "arn:aws:cloudformation:" not in cfnoutput:
print "Stack udpate failed."
sys.exit(2)
else:
print "Output:\n" + cfnoutput
# Wait for Stack to finish
stacks = cfnconn.describe_stacks(stackname)
stack = stacks[0]
lcv = 0
print "\nWaiting for stack to update..."
while "UPDATE_COMPLETE" not in stack.stack_status:
lcv += 1
if "ROLLBACK" in stack.stack_status:
print "\nStack is being rolled back. Check the cloudformation events for your stack to troubleshoot: " + stackname
sys.exit(2)
if lcv > 90:
print "\nStack did not update."
print "Sending cfn update cancel: \n"
cfnconn.cancel_update_stack(stackname)
sys.exit(2)
time.sleep(10)
stacks = cfnconn.describe_stacks(stackname)
stack = stacks[0]
print "Stack update complete.\n"
# Get ELB Names
webelbname = ""
appelbname = ""
stacks = cfnconn.describe_stacks(stackname)
stack = stacks[0]
for output in stack.outputs:
if output.key == "WebELBName":
webelbname = output.value
elif output.key == "AppELBName":
appelbname = output.value
# Get starting IPs of instances
appinstanceip = ""
webinstanceip = ""
elbconn = boto.connect_elb(region)
ec2conn = boto.ec2.connect_to_region(region)
load_balancer = elbconn.get_all_load_balancers(appelbname)[0]
instance_ids = [ instance.id for instance in load_balancer.instances ]
reservations = ec2conn.get_all_instances(instance_ids)
instance_addresses = [ i.private_ip_address for r in reservations for i in r.instances ]
appinstanceip = "*\t\t"
for instanceip in instance_addresses:
appinstanceip = appinstanceip + instanceip + " "
load_balancer = elbconn.get_all_load_balancers(webelbname)[0]
instance_ids = [ instance.id for instance in load_balancer.instances ]
reservations = ec2conn.get_all_instances(instance_ids)
instance_addresses = [ i.private_ip_address for r in reservations for i in r.instances ]
webinstanceip = "*\t\t"
for instanceip in instance_addresses:
webinstanceip = webinstanceip + instanceip + " "
# Get ELB Endpoints
webelbendpoint = ""
appelbendpoint = ""
stacks = cfnconn.describe_stacks(stackname)
stack = stacks[0]
for output in stack.outputs:
if output.key == "WebELBURL":
webelbendpoint = output.value
elif output.key == "AppELBURL":
appelbendpoint = output.value
# Print out summary
print "******************************************************************************************"
print "*\tStack Name: " + stackname
print "*"
print "*\t" + app + " Web Info:"
print "*\tWeb ELB: " + webelbendpoint
print "*\tWeb Chef Roles: " + diction["WebChefRoles"].strip()
print "*\tStarting Web Instance IPs:"
print webinstanceip
print "*"
print "*\t" + app + " App Info:"
print "*\tApp ELB: " + appelbendpoint
print "*\tApp Chef Roles: " + diction["AppChefRoles"].strip()
print "*\tStarting App Instance IPs:"
print appinstanceip
print "******************************************************************************************"
if __name__ == "__main__":
main()