-
Notifications
You must be signed in to change notification settings - Fork 0
/
crc.py
1259 lines (1101 loc) · 42.9 KB
/
crc.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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) Yugabyte, Inc.
import argparse
import ast
import os
from typing import Dict, List, Union
from influxdb_client import InfluxDBClient, Point
from influxdb_client.client.write_api import SYNCHRONOUS
from slack_sdk import WebClient
# Import classes for interacting with different resources across different clouds
from crc.aws.elastic_ips import ElasticIPs
from crc.aws.keypairs import KeyPairs
from crc.aws.kms import Kms
from crc.aws.spot_instance_requests import SpotInstanceRequests
from crc.aws.vm import VM as AWS_VM
from crc.aws.vpc import VPC
from crc.azu.disk import Disk
from crc.azu.ip import IP as AZU_IP
from crc.azu.nic import NIC
from crc.azu.vm import VM as AZU_VM
from crc.gcp.disk import Disk as GCP_Disk
from crc.gcp.ip import IP as GCP_IP
from crc.gcp.vm import VM as GCP_VM
# List of supported clouds and resources
CLOUDS = ["aws", "azure", "gcp"]
RESOURCES = ["disk", "ip", "keypair", "vm", "kms", "nic"]
DELETED = "Deleted"
STOPPED = "Stopped"
NICS = "NIC"
DISKS = "Disk"
VMS = "VM"
IPS = "IP"
KEYPAIRS = "Keypair"
KMS = "KMS"
SPOT_INSTANCE_REQUEST = "SPOT_INSTANCE_REQUEST"
class CRC:
"""
Class for cleaning up resources across different clouds.
This also supports sending notification to Slack Channels
"""
def __init__(
self,
cloud: str,
dry_run: bool,
notags: dict,
slack_client: object,
influxdb_client: object,
project_id: str = None,
resource_group: str = None,
slack_channel: str = None,
influxdb_conn: dict = None,
) -> None:
"""
Initializes the object with required properties.
Parameters:
cloud (str): the name of the cloud platform ('aws', 'gcp' or 'azure')
dry_run (bool): flag to indicate whether the operation is a dry run or not
notags (dict): a dictionary containing a list of resources that don't have any tags
slack_client (object): the Slack client instance used to send messages
influxdb_client (object): the InfluxDB client instance used to send data
project_id (str, optional): the ID of the project (mandatory for GCP)
resource_group (str, optional): the resource group where azure resources reside (mandatory for Azure)
slack_channel (str, optional): the name of the Slack channel to send messages to
influxdb_conn (dict, optional): the Influx DB Connection string
"""
self.cloud = cloud
if cloud == "gcp" and not project_id:
raise ValueError("project_id is mandatory Parameter for GCP")
self.dry_run = dry_run
self.project_id = project_id
self.notags = notags
self.slack_client = slack_client
self.influxdb_client = influxdb_client
self.slack_channel = slack_channel
self.resource_group = resource_group
if influxdb_conn:
self.influxdb_bucket = influxdb_conn.get("bucket")
self.resource_suffix = influxdb_conn.get("resource_suffix")
def _delete_vm(self, vm, instance_state: List[str]):
"""
Delete the specified vm.
:param vm: The vm object to delete.
:param instance_state: List of instance states that should be deleted.
"""
if not instance_state:
vm.delete()
else:
vm.delete(instance_state)
def _get_vm(
self,
filter_tags: Dict[str, List[str]],
exception_tags: Dict[str, List[str]],
age: Dict[str, int],
custom_age_tag_key: str,
):
"""
Get the VM object for the specified cloud.
:param filter_tags: Dictionary of tags to filter the VM.
:param exception_tags: Dictionary of tags to exclude the VM.
:param age: Dictionary of age conditions to filter the VM.
:param custom_age_tag_key: Tag name to overwrite the age condition.
:return: VM object
"""
if self.cloud == "aws":
return AWS_VM(
self.dry_run,
filter_tags,
exception_tags,
age,
custom_age_tag_key,
self.notags,
)
if self.cloud == "azure":
return AZU_VM(
self.resource_group,
self.dry_run,
filter_tags,
exception_tags,
age,
custom_age_tag_key,
self.notags,
)
if self.cloud == "gcp":
return GCP_VM(
self.dry_run,
self.project_id,
filter_tags,
exception_tags,
age,
custom_age_tag_key,
self.notags,
)
raise ValueError(
f"Invalid cloud provided: {self.cloud}. Supported clouds are {CLOUDS}"
)
def _get_ip(
self,
filter_tags: Dict[str, List[str]],
exception_tags: Dict[str, List[str]],
name_regex: List[str],
exception_regex: List[str],
):
"""
Get the IP object for the specified cloud.
:param filter_tags: Dictionary of tags to filter the IP.
:param exception_tags: Dictionary of tags to exclude the IP.
:param name_regex: List of regex patterns to filter the IP.
:param exception_regex: List of regex patterns to exclude the IP.
:return: IP object
"""
if self.cloud == "aws":
return ElasticIPs(self.dry_run, filter_tags, exception_tags, self.notags)
if self.cloud == "azure":
return AZU_IP(
self.resource_group,
self.dry_run,
filter_tags,
exception_tags,
self.notags,
)
if self.cloud == "gcp":
return GCP_IP(self.dry_run, self.project_id, name_regex, exception_regex)
raise ValueError(
f"Invalid cloud provided: {self.cloud}. Supported clouds are {CLOUDS}"
)
def slack_lookup_user_by_email(self, email):
"""
Get the Slack User Id by email
:param email: String to search the user by email in Slack
:return: User Id
:rtype: str
"""
try:
user_info = self.slack_client.users_lookupByEmail(email=email)
return user_info["user"]["id"]
except:
return "not_found"
def get_user_groups_list(self):
"""
Get the Slack User Groups Lists
:return: User Groups List
:rtype: list
"""
try:
user_groups = self.slack_client.usergroups_list()
return user_groups["usergroups"]
except:
print("Something Went Wront! Could not get user_groups.")
return "not_found"
def ping_on_slack(self, resource: str, operation_type: str, operated_list: dict):
"""
Pings individuals 1:1 and groups/untagged into the channel on the Slack
:param resource: Cloud resource type (e.g. "nics", "vms", "ips", "keypairs", "disks")
:type resource: str
:param operation_type: Operation type (e.g. "Deleted", "Stopped")
:type operation_type: str
:param operated_list: Dict of operated resources.
:type operated_list: dict
:return: Message to be sent to the Slack channel
:rtype: str
"""
operated_list_length = 0
msg = ""
user_groups = self.get_user_groups_list()
for key in operated_list.keys():
operated_list_length += len(operated_list[key])
if self.dry_run:
msg = f"`Dry Run`: Will be {operation_type}:"
else:
msg = f"{operation_type} the following"
for key in operated_list.keys():
print(f"Pinging '{key}'")
member_id = self.slack_lookup_user_by_email(f"{key}@yugabyte.com")
operated_list_length = len(operated_list[key])
if member_id == "not_found":
for user_group in user_groups:
if user_group["handle"] == key:
member_id = user_group["id"]
break
if member_id == "not_found":
# Untagged
final_msg = (
msg
+ f"`{operated_list_length}` {self.cloud} {resource}(s):\n*{key}* disks `{operated_list[key]}`\n\n"
)
else:
# User Groups
final_msg = (
msg
+ f"`{operated_list_length}` {self.cloud} {resource}(s):\n<!subteam^{member_id}> disks `{operated_list[key]}`\n\n"
)
try:
self.slack_client.chat_postMessage(
channel="#" + self.slack_channel,
text=final_msg,
link_names=True,
)
except Exception as e:
print(
f"Failed to send message '{final_msg}' to Slack channel '{self.slack_channel}': {e}"
)
else:
# Individual User
final_msg = (
msg
+ f"`{operated_list_length}` {self.cloud} {resource}(s):\n<@{member_id}> disks `{operated_list[key]}`\n\n"
)
# Open Conversation between the bot and the user
users_in_conversation = [member_id]
response = self.slack_client.conversations_open(
users=users_in_conversation
)
channel_id = response["channel"]["id"]
try:
# Post Message
self.slack_client.chat_postMessage(
channel=channel_id, text=final_msg, link_names=True
)
except Exception as e:
print(
f"Failed to send message '{final_msg}' to Slack channel '{channel_id}': {e}"
)
def get_msg(self, resource: str, operation_type: str, operated_list: list) -> str:
"""
Returns a message to be sent to the Slack channel
:param resource: Cloud resource type (e.g. "nics", "vms", "ips", "keypairs", "disks")
:type resource: str
:param operation_type: Operation type (e.g. "Deleted", "Stopped")
:type operation_type: str
:param operated_list: List of operated resources.
:type operated_list: list
:return: Message to be sent to the Slack channel
:rtype: str
"""
operated_list_length = len(operated_list)
if self.dry_run:
return f"`Dry Run`: Will be {operation_type}: `{operated_list_length}` {self.cloud} {resource}(s):\n`{operated_list}`"
return f"{operation_type} the following `{operated_list_length}` {self.cloud} {resource}(s):\n`{operated_list}`"
def notify_deleted_nic_via_slack(self, nic: object):
"""
Sends a notification message to the Slack channel about deleted network interfaces
:param nic: Network interface object
:type nic: object
"""
msg = self.get_msg(NICS, DELETED, nic.get_deleted_nic)
try:
self.slack_client.chat_postMessage(
channel="#" + self.slack_channel, text=msg
)
except Exception as e:
print(
f"Failed to send message '{msg}' to Slack channel '{self.slack_channel}': {e}"
)
def notify_deleted_vm_via_slack(self, vm: object):
"""
Sends a notification message to the Slack channel about deleted virtual machines
:param vm: Virtual machine object
:type vm: object
"""
msg = self.get_msg(VMS, DELETED, vm.get_deleted)
try:
self.slack_client.chat_postMessage(
channel="#" + self.slack_channel, text=msg
)
except Exception as e:
print(
f"Failed to send message '{msg}' to Slack channel '{self.slack_channel}': {e}"
)
if self.cloud == "azure":
self.notify_deleted_nic_via_slack(vm)
def notify_stopped_vm_via_slack(self, vm: object):
"""
Sends a notification message to the Slack channel about stopped virtual machines
:param vm: Virtual machine object
:type vm: object
"""
msg = self.get_msg(VMS, STOPPED, vm.get_stopped)
try:
self.slack_client.chat_postMessage(
channel="#" + self.slack_channel, text=msg
)
except Exception as e:
print(
f"Failed to send message '{msg}' to Slack channel '{self.slack_channel}': {e}"
)
def notify_deleted_spot_request_via_slack(self, spot_instance_request: object):
"""
Sends a notification message to the Slack channel about deleted spot_instance_request
:param spot_instance_request: spot_instance_request object
:type spot_instance_request: object
"""
msg = self.get_msg(
SPOT_INSTANCE_REQUEST, DELETED, spot_instance_request.get_deleted
)
try:
self.slack_client.chat_postMessage(
channel="#" + self.slack_channel, text=msg
)
except Exception as e:
print(
f"Failed to send message '{msg}' to Slack channel '{self.slack_channel}': {e}"
)
def notify_deleted_ip_via_slack(self, ip: object):
"""
Sends a message to a Slack channel about deleted IP instances.
Parameters:
ip (object): the deleted IP instance
"""
msg = self.get_msg(IPS, DELETED, ip.get_deleted)
try:
self.slack_client.chat_postMessage(
channel="#" + self.slack_channel, text=msg
)
except Exception as e:
print(
f"Failed to send message '{msg}' to Slack channel '{self.slack_channel}': {e}"
)
def notify_deleted_keypair_via_slack(self, keypair: object):
"""
Sends a notification message to the Slack channel about deleted Key Pairs
:param keypair: Key Pair object
:type vm: object
"""
msg = self.get_msg(KEYPAIRS, DELETED, keypair.get_deleted)
try:
self.slack_client.chat_postMessage(
channel="#" + self.slack_channel, text=msg
)
except Exception as e:
print(
f"Failed to send message '{msg}' to Slack channel '{self.slack_channel}': {e}"
)
def notify_deleted_nic_via_slack(self, nic: object):
"""
Sends a notification message to the Slack channel about deleted NICs
:param nic: NIC object
:type vm: object
"""
msg = self.get_msg(NICS, DELETED, nic.get_deleted)
try:
self.slack_client.chat_postMessage(
channel="#" + self.slack_channel, text=msg
)
except Exception as e:
print(
f"Failed to send message '{msg}' to Slack channel '{self.slack_channel}': {e}"
)
def notify_deleted_disk_via_slack(self, disk: object):
"""
Sends a notification message to the Slack channel about deleted Disks
:param disk: Disk object
:type vm: object
"""
if type(disk.get_deleted) == list:
# Send a one single message into the channel
msg = self.get_msg(DISKS, DELETED, disk.get_deleted)
try:
self.slack_client.chat_postMessage(
channel="#" + self.slack_channel, text=msg, link_names=True
)
except Exception as e:
print(
f"Failed to send message '{msg}' to Slack channel '{self.slack_channel}': {e}"
)
elif type(disk.get_deleted) == dict:
# Directly ping the individuals 1:1 and groups/untagged into channel
self.ping_on_slack(DISKS, DELETED, disk.get_deleted)
def notify_deleted_kms_via_slack(self, kms: object):
"""
Sends a notification message to the Slack channel about deleted KMS
:param keypair: KMS
:type vm: object
"""
msg = self.get_msg(KMS, DELETED, kms.get_deleted)
try:
self.slack_client.chat_postMessage(
channel="#" + self.slack_channel, text=msg
)
except Exception as e:
print(
f"Failed to send message '{msg}' to Slack channel '{self.slack_channel}': {e}"
)
def write_influxdb(self, resource_name: str, resources: List[str]) -> None:
"""
Writes data to InfluxDB.
Args:
resource_name (str): The name of the resource being written to InfluxDB.
resources (List[str]): A list of resources to be written to InfluxDB.
"""
try:
# Get the write API object from the InfluxDB client, with synchronous write options
write_api = self.influxdb_client.write_api(write_options=SYNCHRONOUS)
if self.resource_suffix:
resource_name = resource_name + "_" + self.resource_suffix
# Create a Point object with the resource name, tags for the names of the resources,
# and a field for the count of resources
point = (
Point(self.cloud)
.tag("resource", resource_name)
.field("names", str(resources))
.field("count", len(resources))
)
# Write the Point object to the InfluxDB bucket
write_api.write(bucket=self.influxdb_bucket, record=point)
except Exception as e:
print(f"Unable to push data to influxDB: {e}")
def delete_vm(
self,
filter_tags: Dict[str, List[str]],
exception_tags: Dict[str, List[str]],
age: Dict[str, int],
custom_age_tag_key: str,
instance_state: List[str],
):
"""
Delete virtual machines that match the specified criteria.
:param filter_tags: Dictionary of tags to filter the VM.
:param exception_tags: Dictionary of tags to exclude the VM.
:param age: Dictionary of age conditions to filter the VM.
:param custom_age_tag_key: Tag name to overwrite the age condition.
:param instance_state: List of instance states that should be deleted.
"""
vm = self._get_vm(filter_tags, exception_tags, age, custom_age_tag_key)
self._delete_vm(vm, instance_state)
if self.slack_client:
self.notify_deleted_vm_via_slack(vm)
if self.influxdb_client:
self.write_influxdb(VMS, vm.get_deleted)
if self.cloud == "azure":
self.write_influxdb(NICS, vm.get_deleted_nic)
def delete_spot_instance_requests(
self,
filter_tags: Dict[str, List[str]],
exception_tags: Dict[str, List[str]],
age: Dict[str, int],
custom_age_tag_key: str,
):
"""
Delete virtual machines that match the specified criteria.
:param filter_tags: Dictionary of tags to filter the VM.
:param exception_tags: Dictionary of tags to exclude the VM.
:param age: Dictionary of age conditions to filter the VM.
:param custom_age_tag_key: Tag name to overwrite the age condition.
"""
spot_instance_requests = SpotInstanceRequests(
self.dry_run,
filter_tags,
exception_tags,
age,
custom_age_tag_key,
self.notags,
)
spot_instance_requests.delete()
if self.slack_client:
self.notify_deleted_spot_request_via_slack(spot_instance_requests)
if self.influxdb_client:
# report this on VMS as well
self.write_influxdb(VMS, spot_instance_requests.get_deleted)
def stop_vm(
self,
filter_tags: Dict[str, List[str]],
exception_tags: Dict[str, List[str]],
age: Dict[str, int],
custom_age_tag_key: str,
):
"""
Stop virtual machines that match the specified criteria.
:param filter_tags: Dictionary of tags to filter the VM.
:param exception_tags: Dictionary of tags to exclude the VM.
:param age: Dictionary of age conditions to filter the VM.
:param custom_age_tag_key: Tag name to overwrite the age condition.
"""
vm = self._get_vm(filter_tags, exception_tags, age, custom_age_tag_key)
vm.stop()
if self.slack_client:
self.notify_stopped_vm_via_slack(vm)
if self.influxdb_client:
self.write_influxdb(VMS, vm.get_stopped)
def delete_ip(
self,
filter_tags: Dict[str, List[str]],
exception_tags: Dict[str, List[str]],
name_regex: List[str],
exception_regex: List[str],
):
"""
Delete IPs that match the specified criteria.
:param filter_tags: Dictionary of tags to filter the IP.
:param exception_tags: Dictionary of tags to exclude the IP.
:param name_regex: List of regex patterns to filter the IP.
:param exception_regex: List of regex patterns to exclude the IP.
"""
ip = self._get_ip(
filter_tags,
exception_tags,
name_regex,
exception_regex,
)
ip.delete()
if self.slack_client:
self.notify_deleted_ip_via_slack(ip)
if self.influxdb_client:
self.write_influxdb(IPS, ip.get_deleted)
def delete_keypairs(
self,
name_regex: List[str],
exception_regex: List[str],
age: Dict[str, int],
):
"""
Delete KeyPairs that match the specified criteria.
This method is only supported on AWS.
:param name_regex: List of regex patterns to filter the keypairs.
:param exception_regex: List of regex patterns to exclude the keypairs.
:param age: Dictionary of age conditions to filter the keypairs.
"""
if self.cloud != "aws":
raise ValueError("Keypair operation is only supported on AWS.")
keypair = KeyPairs(self.dry_run, name_regex, exception_regex, age)
keypair.delete()
if self.slack_client:
self.notify_deleted_keypair_via_slack(keypair)
if self.influxdb_client:
self.write_influxdb(KEYPAIRS, keypair.get_deleted)
def delete_nic(
self,
name_regex: List[str],
exception_regex: List[str],
):
"""
Delete NICs that match the specified criteria.
This method is only supported on Azure.
:param name_regex: List of regex patterns to filter the nics.
:param exception_regex: List of regex patterns to exclude the nics.
"""
if self.cloud != "azure":
raise ValueError("NICs operation is only supported on Azure.")
nic = NIC(self.resource_group, self.dry_run, name_regex, exception_regex)
nic.delete()
if self.slack_client:
self.notify_deleted_nic_via_slack(nic)
if self.influxdb_client:
self.write_influxdb(NICS, nic.get_deleted)
def delete_disks(
self,
filter_tags: Dict[str, List[str]],
exception_tags: Dict[str, List[str]],
age: Dict[str, int],
custom_age_tag_key: str,
detach_age: Dict[str, int],
name_regex: List[str],
exception_regex: List[str],
slack_notify_users: bool,
slack_user_label: str,
):
"""
Delete Disks that match the specified criteria.
This method is only supported on AZURE.
:param filter_tags: Dictionary of tags to filter the disks.
:param exception_tags: Dictionary of tags to exclude the disks.
:param age: Dictionary of age conditions to filter the disks.
:param custom_age_tag_key: Tag name to overwrite the age condition.
:param detach_age: Dictionary of detach age
:param name_regex: List of regex patterns to filter the disks.
:param exception_regex: List of regex patterns to exclude the disks.
:param slack_notify_users: Bool to ping the users/usergroups in the slack ping.
:param slack_user_label: String to lookup for the disks by matching disk label.
"""
if self.cloud not in ["azure", "gcp"]:
raise ValueError(
"Incorrect Cloud Provided. Disks operation is supported only on AZURE and GCP. AWS cleans the NICs, Disks along with VM"
)
if self.cloud == "azure":
disk = Disk(
self.resource_group,
self.dry_run,
filter_tags,
exception_tags,
age,
custom_age_tag_key,
self.notags,
)
if self.cloud == "gcp":
disk = GCP_Disk(
dry_run=self.dry_run,
project_id=self.project_id,
filter_labels=filter_tags,
exception_labels=exception_tags,
age=age,
custom_age_tag_key=custom_age_tag_key,
detach_age=detach_age,
notags=self.notags,
name_regex=name_regex,
exception_regex=exception_regex,
slack_notify_users=slack_notify_users,
slack_user_label=slack_user_label,
)
disk.delete()
if self.slack_client:
self.notify_deleted_disk_via_slack(disk)
if self.influxdb_client:
self.write_influxdb(DISKS, disk.get_deleted)
def delete_vpc(
self, filter_tags: Dict[str, List[str]], exception_tags: Dict[str, List[str]]
):
"""
Delete VPCs that match the specified criteria.
:param filter_tags: Dictionary of tags to filter the VM.
:param exception_tags: Dictionary of tags to exclude the VM.
"""
vpc = VPC(self.dry_run, filter_tags, exception_tags, self.notags)
vpc.delete()
def delete_kms(
self,
filter_tags: Dict[str, List[str]],
exception_tags: Dict[str, List[str]],
kms_key_description: str,
kms_user: str,
kms_pending_window: int,
age: Dict[str, int],
custom_age_tag_key: str,
):
"""
Delete KMS that match the specified criteria.
:param filter_tags: Dictionary of tags to filter the KMS.
:param exception_tage: Dictionary of tags to exclude the KMS.
:param kms_key_description: String to be present in KMS key description.
:param kms_user: AWS ARN of Jenkins slave for which associated keys will be deleted.
:param kms_pending_window: Number of days till which keys will be scheduled for deletion.
:param age: Time to live for keys.
:param custom_age_tag_key: Tag name to overwrite the age condition.
"""
if self.cloud != "aws":
raise ValueError("KMS operation is only supported on AWS.")
kms = Kms(
self.dry_run,
filter_tags,
exception_tags,
kms_key_description,
kms_user,
kms_pending_window,
age,
custom_age_tag_key,
)
kms.delete()
if self.slack_client:
self.notify_deleted_kms_via_slack(kms)
if self.influxdb_client:
self.write_influxdb(KMS, kms.get_deleted)
def get_argparser():
"""
Method to parse and return command line arguments.
:return: A dictionary containing all the command line arguments.
"""
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
description="Cleanup Resources across different clouds",
)
# Add Argument for Cloud
parser.add_argument(
"-c",
"--cloud",
choices=["aws", "azure", "gcp", "all"],
required=True,
metavar="CLOUD",
help="The cloud to operate on. Valid options are: 'aws', 'azure', 'gcp', 'all'. Example: -c or --cloud all",
)
# Add Argument for Resource Type
parser.add_argument(
"-r",
"--resource",
default="all",
choices=[
"disk",
"ip",
"keypair",
"vm",
"vpc",
"kms",
"nic",
"spot_instance_requests",
"all",
],
metavar="RESOURCE",
help="Type of resource to operate on. Valid options are: 'disk', 'ip', 'keypair', 'vm', 'all'. Default: 'all'. Example: -r or --resource vm",
)
# Add Argument for Project ID (GCP only)
parser.add_argument(
"-p",
"--project_id",
metavar="PROJECT_ID",
help="Project ID for GCP. Required only for GCP. Example: --project_id testing",
)
# Add Argument for Operation Type
parser.add_argument(
"-o",
"--operation_type",
default="delete",
choices=["delete", "stop"],
metavar="OPERATION",
help="Type of operation to perform on resource. Valid options are: 'delete', 'stop'. Default: 'delete'. Example: -o or --operation_type stop",
)
# Add argument for resource states
parser.add_argument(
"-s",
"--resource_states",
type=ast.literal_eval,
metavar="['state1', 'state2']",
help="State of the resource to filter. Example: --resource_states ['RUNNING', 'STOPPED']",
)
# Add argument for filter tags
parser.add_argument(
"-f",
"--filter_tags",
type=ast.literal_eval,
metavar="{key1: [value1, value2], key2: [value3, value4]}",
help="Tags to use for filtering resources. Example: --filter_tags {'test_task': ['test', 'stress-test']}",
)
# Add argument for exception tags
parser.add_argument(
"-e",
"--exception_tags",
type=ast.literal_eval,
metavar="{key1: [value1, value2], key2: [value3, value4]}",
help="Exception tags to use for filtering resources. Example: --exception_tags {'test_task': ['test-keep-resources', 'stress-test-keep-resources']}",
)
# Add Argument for Name Regex
parser.add_argument(
"-n",
"--name_regex",
type=ast.literal_eval,
metavar="['REGEX1','REGEX2']",
help="Name Regex used to filter resources. Only applies to AWS keypairs and GCP IPs. Example: -n or --name_regex ['perftest_','qa_']",
)
# Add Argument for Exception Regex
parser.add_argument(
"-x",
"--exception_regex",
type=ast.literal_eval,
metavar="['REGEX1','REGEX2']",
help="Exception Regex to filter out resources. Example: -x or --exception_regex ['perftest_keep_resources', 'test_keep_resources']",
)
# Add Argument for Age Threshold
parser.add_argument(
"-a",
"--age",
type=ast.literal_eval,
metavar="{'days': value1, 'hours': value2}",
help="Age Threshold for resources. Age is not respected for IPs. Example: -a or --age {'days': 3, 'hours': 12}",
)
# Add Argument for Custom Age Threshold Tag Key
parser.add_argument(
"--custom_age_tag_key",
metavar="CUSTOM_AGE_TAG_KEY",
help=(
"Define a custom tag key for the age threshold of resources. This tag is "
"ignored for IPs and Keypairs. Example usage: --custom_age_tag_key retention_age. "
"The value can be specified in a dictionary format (e.g., {'days': 3, 'hours': 6}) or as an "
"integer, which will be interpreted as days by default."
),
)
# Add argument for specifying the maximum age threshold for resources
parser.add_argument(
"--max_age",
metavar="MAX_AGE",
help=(
"Specify the maximum age threshold for resources. This value will override the value of the tag specified by 'custom_age_tag_key'. "
"Provide the age in dictionary format, e.g., {'days': 3, 'hours': 6}."
),
)
# Add Argument for Age Threshold
parser.add_argument(
"--detach_age",
type=ast.literal_eval,
metavar="{'days': value1, 'hours': value2}",
help="Age Threshold for last detached disk resources. Age is not respected for VM's & IPs. Example: --detach_age {'days': 3, 'hours': 12}",
)
# Add Argument for Dry Run Mode
parser.add_argument(
"-d",
"--dry_run",
action="store_true",
help="Enable dry_run only mode",
)
# Add Argument for Tag not present
parser.add_argument(
"-t",
"--notags",
type=ast.literal_eval,
help="Filter by Tags not Present. Leave value of Key empty to indicate 'any' value. Format: -t or --notags {'test_task': ['test'], 'test_owner': []}",
metavar="{key1: [value1, value2], key2: [value3, value4]}",
)
# Add Argument for Slack Channel
parser.add_argument(
"-m",
"--slack_channel",
metavar="SLACK_CHANNEL",
help="The Slack channel to send the notifications to. Example: --slack_channel testing",
)
# Add Argument for Slack Channel
parser.add_argument(
"--slack_notify_users",
action="store_true",
help="If true notify users in the Slack channel, currently only for GCP disk",
)
# Add Argument for label that need to be used for getting username
parser.add_argument(
"--slack_user_label",
metavar="SLACK_USER_LABEL",
help="The gcp label that can be used to get username. Example: --slack_user_label owner",
)
# Add Argument for InfluxDB
parser.add_argument(
"-i",
"--influxdb",
type=ast.literal_eval,
metavar="{'url': 'http://localhost:8086', 'org': 'Test', 'bucket': 'CRC'}",
help="InfluxDB connection details in the form of a dictionary. Example: -i or --influxdb {'url': 'http://localhost:8086', 'org': 'Test', 'bucket': 'CRC', 'resource_suffix': 'test'}",
)
# Add Argument for Pending Window
parser.add_argument(
"--kms_pending_window",
type=int,
default=7,
choices=range(7, 31),
metavar="KMS_PENDING_WINDOW",
help="The pending window(days) to schedule KMS deletion after this duration. Must be between 7 and 30 inclusive.",
)
# Add Argument for Key Description
parser.add_argument(
"--kms_key_description",
type=str,
metavar="KMS_KEY_DESCRIPTION",
help="The string/name to be present in Key description in the Key JSON policy.",
)
# Add Argument for Jenkins Username
parser.add_argument(
"--kms_user",
type=str,
metavar="JENKINS_USERNAME",
help="The Jenkins username for which associated KMS keys will be deleted.",