-
Notifications
You must be signed in to change notification settings - Fork 0
/
deletestackapi.py
152 lines (131 loc) · 5.16 KB
/
deletestackapi.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
import boto3
import json
import datetime
import os
cf = boto3.client('cloudformation')
dynamo_client = boto3.client('dynamodb')
dynamodb = boto3.resource('dynamodb')
ecs = boto3.client('ecs')
ecr = boto3.client('ecr')
sts = boto3.client('sts')
sns = boto3.client('sns')
### CROSSACCOUNT DYNAMO ACCESS TO SHARED ACCOUNT ###
stsrolearn = os.environ['STSROLEARN']
response = sts.assume_role(RoleArn=stsrolearn, RoleSessionName='CrossAccountECSDynamoTableAccess')
aws_access_key_id=response['Credentials']['AccessKeyId']
aws_secret_access_key=response['Credentials']['SecretAccessKey']
aws_session_token=response['Credentials']['SessionToken']
dynamo_client = boto3.client('dynamodb', aws_access_key_id=aws_access_key_id,aws_secret_access_key=aws_secret_access_key,aws_session_token=aws_session_token)
resource = boto3.resource('dynamodb', aws_access_key_id=aws_access_key_id,aws_secret_access_key=aws_secret_access_key,aws_session_token=aws_session_token)
nonprod_table = resource.Table('ECS_Inventory_NonProduction')
prod_table = resource.Table('ECS_Inventory_Production')
trainda_table = resource.Table('ECS_Inventory_Training_DA')
#### ###
### RETURN BODY FOR API ###
def return_body(status_code, message):
body = {
'statusCode': str(status_code),
'body': json.dumps(message),
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
}
}
return body
#### ####
### DELETE ECR ###
def delete_ecr(stackname):
ecr_name = stackname.lower()
resp = ecr.delete_repository(repositoryName=ecr_name, force=True)
#### ####
### SEND SNS NOTIFICATION ###
def sendnotification(stackname, nonprod_acc):
sns_arn = "arn:aws:sns:us-east-1:" + nonprod_acc + ":ECSNotifications-" + stackname
sns_message = "Deleting the Stack and all environments for " + stackname
subject = "Deleting the Stack for the Application " + stackname
response = sns.publish(TopicArn=sns_arn, Message=sns_message, Subject=subject)
print response
### Main Handler ###
def lambda_handler(event, context):
print event
body = json.loads(event['body'])
nonprod_acc = os.environ['NONPROD_ACC']
prod_acc = os.environ['PROD_ACC']
region = os.environ['REGION']
try:
stackname = body['stack']
if stackname == "":
status_code = 400
message = {"errorMessage": "Parameter Validation Error: stackname cannot be empty"}
return_message = return_body(status_code, message)
return return_message
except KeyError:
status_code = 400
message = {"errorMessage": "Parameter Validation Error: stackname needs to be mentioned"}
return_message = return_body(status_code, message)
return return_message
try:
delete_ecr(stackname)
except Exception as e:
print e
pass
try:
response = cf.delete_stack_instances(StackSetName=stackname, Accounts = [nonprod_acc, prod_acc], Regions=[region], RetainStacks=False)
print response
try:
resp = nonprod_table.delete_item(Key={'ApplicationName': stackname, 'Environment': 'DEV'})
except Exception as e:
print e
pass
try:
resp = nonprod_table.delete_item(Key={'ApplicationName': stackname, 'Environment': 'QA'})
except Exception as e:
print e
pass
try:
resp = nonprod_table.delete_item(Key={'ApplicationName': stackname, 'Environment': 'STAGE'})
except Exception as e:
print e
pass
try:
resp = prod_table.delete_item(Key={'ApplicationName': stackname, 'Environment': 'PROD1'})
except Exception as e:
print e
pass
try:
resp = prod_table.delete_item(Key={'ApplicationName': stackname, 'Environment': 'PROD2'})
except Exception as e:
print e
pass
try:
resp = trainda_table.delete_item(Key={'ApplicationName': stackname, 'Environment': 'TRAINING'})
except Exception as e:
print e
pass
try:
resp = trainda_table.delete_item(Key={'ApplicationName': stackname, 'Environment': 'DA'})
except Exception as e:
print e
pass
sendnotification(stackname.lower(), nonprod_acc)
status_code = 200
message = {'message': 'StackInstances Deletion Initiated', 'Warning': 'Please be aware to Remove StackSet been created in CloudFormation'}
return_message = return_body(status_code, message)
return return_message
except Exception as e:
print e
status_code = 409
message = {'message': 'Stack does not Exists'}
return_message = return_body(status_code, message)
return return_message
"""
try:
response = cf.delete_stack_set(StackSetName=stackname)
print response
except Exception as e:
print e
status_code = 409
message = {'message': 'Stack does not Exists'}
return_message = return_body(status_code, message)
return return_message
"""