Skip to content

Commit 53afa43

Browse files
committed
added existing stack name check.
1 parent 7f51832 commit 53afa43

File tree

1 file changed

+35
-14
lines changed

1 file changed

+35
-14
lines changed

buildstack.py

Lines changed: 35 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111

1212

1313
def buildstack(region):
14+
# Builds the stack
1415
try:
1516

1617
client = boto3.client('cloudformation',region_name=region)
@@ -26,7 +27,6 @@ def buildstack(region):
2627
)
2728

2829
stackuuid = create_stack_response['StackId']
29-
# stackuuid = str(uuid.uuid4())
3030
return stackuuid
3131

3232
except ClientError as e:
@@ -36,7 +36,7 @@ def buildstack(region):
3636
print("[ERROR]", e)
3737

3838
def checkstackstatus(region):
39-
39+
# Checks stack building status
4040
try:
4141

4242
stack_building = True
@@ -46,12 +46,10 @@ def checkstackstatus(region):
4646
event_list = client.describe_stack_events(StackName=stackname).get("StackEvents")
4747
stack_event = event_list[0]
4848

49-
if (stack_event.get('ResourceType') == 'AWS::CloudFormation::Stack' and
50-
stack_event.get('ResourceStatus') == 'CREATE_COMPLETE'):
49+
if (stack_event.get('ResourceType') == 'AWS::CloudFormation::Stack' and stack_event.get('ResourceStatus') == 'CREATE_COMPLETE'):
5150
stack_building = False
5251
print("Stack construction completed for region...", region)
53-
elif (stack_event.get('ResourceType') == 'AWS::CloudFormation::Stack' and
54-
stack_event.get('ResourceStatus') == 'ROLLBACK_COMPLETE'):
52+
elif (stack_event.get('ResourceType') == 'AWS::CloudFormation::Stack' and stack_event.get('ResourceStatus') == 'ROLLBACK_COMPLETE'):
5553
stack_building = False
5654
print("Stack construction failed for region...", region)
5755
sys.exit(1)
@@ -66,6 +64,25 @@ def checkstackstatus(region):
6664
except Exception as e:
6765
print("[ERROR]", e)
6866

67+
def checkstackname(region):
68+
# Checks if stackname exists. Returns true if it does, false if not.
69+
try:
70+
71+
client = boto3.client('cloudformation',region_name = region)
72+
response = client.list_stacks()
73+
for stacks in response['StackSummaries']:
74+
if (stacks['StackName'] == stackname):
75+
return True
76+
else:
77+
return False
78+
79+
except ClientError as e:
80+
print("[ERROR]",e)
81+
raise
82+
except Exception as e:
83+
print("[ERROR]", e)
84+
85+
6986

7087
def main():
7188
# Main routine
@@ -77,13 +94,12 @@ def main():
7794
parser.add_argument("-t","--template-body", default='managed-gdb-cft.yml', type=str, help="CloudFormation template file")
7895
parser.add_argument("-r","--region", type=str,help="List of regions seperated by commas, where the stack will be deployed")
7996
parser.add_argument("-s","--stack-name", type=str, help="CloudFormation Stack Name")
80-
parser.add_argument("-a","--agree-anonymous-data-collect", type=str, default='yes',help="Opt in for anonymous one time data collection.(yes/no). Only collects region name, creation time and uuid portion of the stack id (for uniqueness).")
81-
97+
parser.add_argument("-a","--agree-anonymous-data-collect", type=str, default='yes',help="Opt-in for anonymous one time data collection.(yes/no). Only collects region name, creation time, stack name and uuid portion of the stack id (for uniqueness).")
8298

8399
# process arguments
84100
args = parser.parse_args()
85101

86-
#region and stack ids
102+
# dictionary for region and stack ids
87103
stack_regions = {}
88104

89105
global stackname
@@ -114,7 +130,10 @@ def main():
114130
if not regionmatch:
115131
print ("Please provide a valid region name in region list. For example: us-east-1. Incorrect value", region)
116132
sys.exit(1)
117-
133+
elif checkstackname(region):
134+
print ("Stack Name", stackname, "already exists in region", region,". Quitting due to stack name conflict. Please choose another stack name.")
135+
sys.exit(1)
136+
118137

119138
# print (sys.platform)
120139

@@ -125,11 +144,13 @@ def main():
125144

126145
stackid = buildstack (region)
127146
stackids = stackid.split('/')
128-
stackid = stackids[2]
147+
stackid = stackids[2] # split stackid to isolate the uuid portion
129148
stack_regions[stackid] = region
130149
regionscount += 1
131150
buildtime = datetime.datetime.utcnow().isoformat() + 'Z'
132151
print("Started building stackid",stackid,"in Region",region, "at:",buildtime)
152+
153+
# This block gathers anonymous data on the stack, if consent is provided. Only data collected is name of the stack, region, timestamp and only UUID part of the stackid.
133154
payload = {
134155
'stack_uuid': stackid,
135156
'stack_name': stackname,
@@ -138,16 +159,16 @@ def main():
138159

139160
}
140161
if (args.agree_anonymous_data_collect == 'yes'):
141-
r = http.request('POST', "https://ksacb35t5m.execute-api.us-east-1.amazonaws.com/v1/track", body=json.dumps(payload).encode('utf-8'), headers={'Content-Type': 'application/json'})
162+
r = http.request('POST', "https://ksacb35t5m.execute-api.us-east-1.amazonaws.com/v1/track", body=json.dumps(payload).encode('utf-8'), headers={'Content-Type': 'application/json'})
142163
print("[INFO]", "Event tracking for UUID:", payload["stack_uuid"])
143164

144165

145166

146-
try_count = 1 #Initialize counter to keep track of regions
167+
try_count = 1 #Initialize counter to keep track of regions in a loop
147168

148169
while stack_building:
149170

150-
waitcount = 1 #Initialize counter for waiting 10 se
171+
waitcount = 1 #Initialize counter for the sleep loop
151172
for stack in stack_regions:
152173

153174
stackid = stack

0 commit comments

Comments
 (0)