-
Notifications
You must be signed in to change notification settings - Fork 1
/
cloudfront_manager.py
449 lines (358 loc) · 18 KB
/
cloudfront_manager.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
439
440
441
442
443
444
445
446
447
448
449
'''
Useful for Invalidate Cloudfront distribution, Enable/Disable or delete it for those using Windows OS.
The application is build using PySimpleGUI.
It expects you have setup the aws id/key in
Linux: /home/[username]/.aws
Windows: /Users/[username]/.aws
To do:
1: Display distribution detail for giving ID. Currently "Display Distribution"" function not implemented"
2: Move threading functions to seperate file and call the module
3: Move cloudfront functions to sperate file and call the module
4: Remove the region from the functions
'''
import PySimpleGUI as sg
import boto3
from botocore.config import Config
from boto3.session import Session
import threading
import time
#import datetime
from datetime import datetime,timedelta
import sys
session = boto3.session.Session()
distribution_list_data=[]
distribution_data=[]
sg.theme('Reddit')
#-----------------GUI Layout--------------------------------
Console =[
[sg.Text("Console")],
[sg.Multiline(size=(48, 14),key="-CONSOLEMSG-",disabled=True)],
[sg.B("Clear Console",size=(20, 1)),sg.B("Save Console",size=(21, 1))]
]
frame_layout = [
[sg.T('Id:'), sg.Text("",size=(45, 1),key="-text_id-"),sg.T(' Status:'), sg.Text("",size=(25, 1),key="-text_status-")],
[sg.T('Domain Name:'), sg.Text("",size=(50, 1),key="-text_domainname-")],
[sg.T('LastModifiedTime:'), sg.Text("",size=(60, 1),key="-text_lastmodifiedtime-")],
[sg.T('Logging:'), sg.Text("",size=(60, 1),key="-text_log-")],
[sg.T('Enabled:'), sg.Text("",size=(60, 1),key="-text_enabled-")],
[sg.T('HttpVersion:'), sg.Text("",size=(60, 1),key="-text_httpversion-")],
[sg.T('IsIPV6Enabled:'), sg.Text("",size=(60, 1),key="-text_ipv6-")],
[sg.T('InProgressInvalidationBatches:'), sg.Text("",size=(50, 1),key="-text_inprogress-")],
[sg.T('ARN:'), sg.Text("",size=(50, 1),key="-text_arn-")]
]
Desc =[
[sg.Frame('Description', frame_layout, font='Any 12', title_color='blue')]
#,[sg.Multiline(size=(82, 12),key="-CONSOLEMSG1-",disabled=True)]
]
dist =[
[sg.Text("Enter Distribution ID"),sg.InputText(key="-DistID-",size=(65, 1)), sg.B("Display Distribution",size=(25, 1)), sg.B("Show All",size=(30, 1)) ],
[sg.Table(values=distribution_list_data,key="_DIST_", headings=['ID', 'Domain Name','Description','Status','Enabled','Last modified'],auto_size_columns=False, col_widths=[27, 30, 30], num_rows=15,justification='left',right_click_menu=['&Right', ['Invalidate', 'Disable','Enable', 'Delete','Refresh']],enable_events=True )]
]
cfn_layout = [
[
sg.Column(dist)],
[
sg.Column(Desc,size=(700, 270))
,sg.VSeperator(),
sg.Column(Console)
]
]
config =[
[sg.Text('Enter Your AWS Id',size=(30, 1)), sg.InputText(key="-AWSID-",size=(30, 1))],
[sg.Text('Enter Your AWS Key',size=(30, 1)), sg.InputText(key="-AWSKEY-",size=(30, 1))],
[sg.Text('Enter Your Default Region',size=(30, 1)), sg.InputText(key="-DEFREGION-",size=(30, 1))],
[sg.B("Reset",size=(28, 1)),sg.B("Connect",size=(27, 1))]
]
config_layout = [[sg.Column(config)]]
tabgrp = [[sg.TabGroup([[sg.Tab('Config', config_layout)],[sg.Tab('Cloudfront', cfn_layout)]])]]
#--------------AWS Cloudfront specific Functions--------------------------------------
#get list of all the available queues in a region
def get_distribution_list(REGION_NAME,window):
REGION_CONFIG = Config(
region_name = REGION_NAME,
signature_version = 'v4',
retries = {
'max_attempts': 3
}
)
try:
CLIENT = session.client('cloudfront', config=REGION_CONFIG)
response = CLIENT.list_distributions(
MaxItems='100'
)
# print (response)
if response['DistributionList']['Quantity'] == 0:
distribution_list_data.clear()
window.write_event_value('-WRITE-',"There is no cloudfront distribution")
else:
distribution_list_data.clear()
for item in response['DistributionList']['Items']:
distribution_list_data.append([item['Id'], item['DomainName'], item['Comment'], item['Status'], item['Enabled'], item['LastModifiedTime']])
return distribution_list_data
except Exception as e:
return(e)
def get_distribution_detail(REGION_NAME,ID,window):
REGION_CONFIG = Config(
region_name = REGION_NAME,
signature_version = 'v4',
retries = {
'max_attempts': 3
}
)
try:
CLIENT = session.client('cloudfront', config=REGION_CONFIG)
response = CLIENT.get_distribution(
Id=ID
)
return response
except Exception as e:
return(e)
def get_single_distribution(REGION_NAME,ID,window):
REGION_CONFIG = Config(
region_name = REGION_NAME,
signature_version = 'v4',
retries = {
'max_attempts': 3
}
)
try:
CLIENT = session.client('cloudfront', config=REGION_CONFIG)
response = CLIENT.get_distribution(
Id=ID
)
distribution_list_data.clear()
#for item in response['Distribution']:
distribution_list_data.append([response['Distribution']['Id'],
response['Distribution']['DomainName'],
response['Distribution']['DistributionConfig']['Comment'],
response['Distribution']['Status'],
response['Distribution']['DistributionConfig']['Enabled'],
response['Distribution']['LastModifiedTime']])
return distribution_list_data
except Exception as e:
return(e)
def update_distribution(REGION_NAME,ID,enable_state,window):
REGION_CONFIG = Config(
region_name = REGION_NAME,
signature_version = 'v4',
retries = {
'max_attempts': 3
}
)
try:
CLIENT = session.client('cloudfront', config=REGION_CONFIG)
distribution_config_response = CLIENT.get_distribution_config(Id=ID)
#print(distribution_config_response)
distribution_config = distribution_config_response['DistributionConfig']
distribution_etag = distribution_config_response['ETag']
distribution_config_enabled = distribution_config_response['DistributionConfig']['Enabled']
if enable_state is True: #check if user requested to enable distribution
if distribution_config_enabled is False:
distribution_config_response['DistributionConfig']['Enabled'] = True
distribution_config_response = CLIENT.update_distribution(DistributionConfig=distribution_config,
Id=ID,
IfMatch=distribution_etag)
elif enable_state is False: #check if user requested to disable distribution
if distribution_config_enabled is True: #check if distribution is enabled
distribution_config_response['DistributionConfig']['Enabled'] = False
distribution_config_response = CLIENT.update_distribution(DistributionConfig=distribution_config,
Id=ID,
IfMatch=distribution_etag)
else:
print("ooooops")
window.write_event_value('-WRITE-',distribution_config_response)
except Exception as e:
window.write_event_value('-WRITE-',e)
def create_invalidation(REGION_NAME,ID, window):
REGION_CONFIG = Config(
region_name = REGION_NAME,
signature_version = 'v4',
retries = {
'max_attempts': 3
}
)
try:
CLIENT = session.client('cloudfront', config=REGION_CONFIG)
invalidate_response = CLIENT.create_invalidation(
DistributionId=ID,
InvalidationBatch={
'Paths': {
'Quantity': 1,
'Items': [
'/*'
]
},
'CallerReference': str(time.time()).replace(".", "")
}
)
invalidation_id = invalidate_response['Invalidation']['Id']
window.write_event_value('-WRITE-',"The invalidation id is: "+ invalidation_id)
except Exception as e:
window.write_event_value('-WRITE-',e)
def delete_distribution(REGION_NAME,ID, window):
REGION_CONFIG = Config(
region_name = REGION_NAME,
signature_version = 'v4',
retries = {
'max_attempts': 3
}
)
try:
CLIENT = session.client('cloudfront', config=REGION_CONFIG)
distribution_config_response = CLIENT.get_distribution_config(Id=ID)
distribution_config = distribution_config_response['DistributionConfig']
distribution_etag = distribution_config_response['ETag']
distribution_config_enabled = distribution_config_response['DistributionConfig']['Enabled']
if distribution_config_enabled is False:
delete_distribution_response = CLIENT.delete_distribution(Id=ID, IfMatch=distribution_etag)
window.write_event_value('-WRITE-',"Deleteing Distribution Completed "+ delete_distribution_response)
else:
distribution_config_response['DistributionConfig']['Enabled']=False
distribution_config_response = CLIENT.update_distribution(
DistributionConfig=distribution_config,
Id=ID,
IfMatch=distribution_etag)
#wait for distribution to disable....
window.write_event_value('-WRITE-',"It can take a while to disable distribution....")
timeout_mins=30
wait_until = datetime.now() + timedelta(minutes=timeout_mins)
notFinished=True
distribution_etag=""
while(notFinished):
if wait_until < datetime.now(): #timeout
window.write_event_value('-WRITE-',"Distribution took too long to disable. Exiting")
sys.exit(1)
distribution_status=CLIENT.get_distribution(Id=ID)
if(distribution_status['Distribution']['DistributionConfig']['Enabled']==False and distribution_status['Distribution']['Status']=='Deployed'):
distribution_etag=distribution_status['ETag']
notFinished=False
window.write_event_value('-WRITE-',"Disable not completed yet. Sleeping 30 seconds....")
time.sleep(30)
delete_distribution_response= CLIENT.delete_distribution(Id=ID, IfMatch=distribution_etag)
window.write_event_value('-WRITE-',"Deleteing Distribution Completed "+ delete_distribution_response)
except Exception as e:
window.write_event_value('-WRITE-',e)
def dist_list_worker_thread(region_name, window):
try:
data=[] #data=[]
data = get_distribution_list("ap-southeast-2",window)
window["_DIST_"].update(data)
except Exception as e:
window.write_event_value('-WRITE-',e)
def single_dist_worker_thread(region_name,ID, window):
try:
data=[]
data = get_single_distribution("ap-southeast-2",ID, window)
window["_DIST_"].update(data)
except Exception as e:
window.write_event_value('-WRITE-',e)
def delete_dist_worker_thread(region_name,ID, window):
try:
delete_distribution("ap-southeast-2",ID, window)
except Exception as e:
window.write_event_value('-WRITE-',e)
def dist_detail_worker_thread(region_name, ID, window):
try:
distribution_data.clear()
data = get_distribution_detail("ap-southeast-2",ID,window)
distribution_data.append([data['Distribution']['Id'],data['Distribution']['DomainName'],
data['Distribution']['ARN'],data['Distribution']['Status'],
data['Distribution']['LastModifiedTime'],
data['Distribution']['DistributionConfig']['Logging']['Enabled'],
data['Distribution']['DistributionConfig']['Enabled'],
data['Distribution']['DistributionConfig']['HttpVersion'],
data['Distribution']['DistributionConfig']['IsIPV6Enabled'],
data['Distribution']['InProgressInvalidationBatches']
])
window["-text_id-"].update(data['Distribution']['Id'])
window["-text_domainname-"].update(data['Distribution']['DomainName'])
window["-text_arn-"].update(data['Distribution']['ARN'])
window["-text_status-"].update(data['Distribution']['Status'])
window["-text_lastmodifiedtime-"].update(data['Distribution']['LastModifiedTime'])
window["-text_inprogress-"].update(data['Distribution']['InProgressInvalidationBatches'])
window["-text_log-"].update(data['Distribution']['DistributionConfig']['Logging']['Enabled'])
window["-text_enabled-"].update(data['Distribution']['DistributionConfig']['Enabled'])
window["-text_httpversion-"].update(data['Distribution']['DistributionConfig']['HttpVersion'])
window["-text_ipv6-"].update(data['Distribution']['DistributionConfig']['IsIPV6Enabled'])
except Exception as e:
window.write_event_value('-WRITE-',e)
#-----------------Main function------------------------------------
def main():
window = sg.Window('AWS Cloudfront Manager', tabgrp) #layout
while True: # The Event Loop
event, values = window.read()
if event == sg.WIN_CLOSED or event == 'Exit':
break
#---------Connection Tab-----------------------------
if event == 'Reset':
try:
window["-AWSID-"].update("")
window["-AWSKEY-"].update("")
window["-DEFREGION-"].update("")
window["-AWSID-"].SetFocus(force = True)
except Exception as e:
sg.popup(e)
if event == 'Connect':
try:
global session
if values['-DEFREGION-'] == "":
sg.popup("Region Field is missing")
elif values['-AWSID-'] == "":
sg.popup("AWS ID Field is missing")
elif values['-AWSKEY-'] == "":
sg.popup("AWS KEY Field is missing")
else:
session = Session(region_name=values['-DEFREGION-'], aws_access_key_id=values['-AWSID-'],
aws_secret_access_key=values['-AWSKEY-'])
#need to validate if connection is successful or not
sg.popup("Connection Established")
except Exception as e:
sg.popup(e)
#---------Cloudfront Tab------------------------
if event == 'Invalidate':
try:
get_distribution_list("ap-southeast-2",window)
except Exception as e:
window["-CONSOLEMSG-"].update(str(datetime.now().strftime("%Y-%m-%d %H:%M:%S")) +": "+str(e)+"\n", append=True )
if event == 'Refresh':
window.refresh()
threading.Thread(target=dist_list_worker_thread, args=("ap-southeast-2", window,), daemon=True).start()
if event == "Show All":
try:
threading.Thread(target=dist_list_worker_thread, args=("ap-southeast-2", window,), daemon=True).start()
except Exception as e:
window["-CONSOLEMSG-"].update(str(datetime.now().strftime("%Y-%m-%d %H:%M:%S")) +": "+str(e)+"\n", append=True )
if event == '-WRITE-':
window["-CONSOLEMSG-"].update(str(datetime.now().strftime("%Y-%m-%d %H:%M:%S")) +": "+str(values['-WRITE-'])+"\n", append=True)
if event == 'Disable':
update_distribution("ap-southeast-2",distribution_data[0][0],False,window)
if event == 'Enable':
update_distribution("ap-southeast-2",distribution_data[0][0],True,window)
if event == 'Delete':
threading.Thread(target=delete_dist_worker_thread, args=("ap-southeast-2",distribution_data[0][0],window,), daemon=True).start()
if event == 'Invalidate':
create_invalidation("ap-southeast-2",distribution_data[0][0], window)
if event == "_DIST_":
try:
data_selected = [distribution_list_data[row] for row in values[event]]
threading.Thread(target=dist_detail_worker_thread, args=("ap-southeast-2",data_selected[0][0],window,), daemon=True).start()
except Exception as e:
window["-CONSOLEMSG-"].update(str(datetime.now().strftime("%Y-%m-%d %H:%M:%S")) +": "+str(e)+"\n", append=True )
if event == "Display Distribution":
if not values['-DistID-']:
sg.popup("Missing Distribution ID")
else:
threading.Thread(target=single_dist_worker_thread, args=("ap-southeast-2",str(values['-DistID-']),window,), daemon=True).start()
if event == 'Save Console':
try:
file= open("output.txt", 'a+')
except FileNotFoundError:
file= open("output.txt", 'w+')
file.write(str(window["-CONSOLEMSG-"].get()))
file.close()
sg.popup("File Saved")
if event == 'Clear Console':
window["-CONSOLEMSG-"].update("")
window.close()
if __name__ == '__main__':
main()