forked from openshift/installer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
aws.go
1546 lines (1365 loc) · 40.4 KB
/
aws.go
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
package aws
import (
"fmt"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/arn"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/elb"
"github.com/aws/aws-sdk-go/service/elbv2"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/aws/aws-sdk-go/service/resourcegroupstaggingapi"
"github.com/aws/aws-sdk-go/service/route53"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"k8s.io/apimachinery/pkg/util/wait"
"github.com/openshift/installer/pkg/version"
)
var (
exists = struct{}{}
)
// Filter holds the key/value pairs for the tags we will be matching against.
//
// A resource matches the filter if all of the key/value pairs are in its tags.
type Filter map[string]string
// ClusterUninstaller holds the various options for the cluster we want to delete
type ClusterUninstaller struct {
// Filters is a slice of filters for matching resources. A
// resources matches the whole slice if it matches any of the
// entries. For example:
//
// filter := []map[string]string{
// {
// "a": "b",
// "c": "d:,
// },
// {
// "d": "e",
// },
// }
//
// will match resources with (a:b and c:d) or d:e.
Filters []Filter // filter(s) we will be searching for
Logger logrus.FieldLogger
Region string
ClusterID string
}
func (o *ClusterUninstaller) validate() error {
if len(o.Filters) == 0 {
return errors.Errorf("you must specify at least one tag filter")
}
return nil
}
// Run is the entrypoint to start the uninstall process
func (o *ClusterUninstaller) Run() error {
err := o.validate()
if err != nil {
return err
}
awsConfig := &aws.Config{Region: aws.String(o.Region)}
// Relying on appropriate AWS ENV vars (eg AWS_PROFILE, AWS_ACCESS_KEY_ID, etc)
awsSession, err := session.NewSession(awsConfig)
if err != nil {
return err
}
awsSession.Handlers.Build.PushBackNamed(request.NamedHandler{
Name: "openshiftInstaller.OpenshiftInstallerUserAgentHandler",
Fn: request.MakeAddToUserAgentHandler("OpenShift/4.x Destroyer", version.Raw),
})
tagClients := []*resourcegroupstaggingapi.ResourceGroupsTaggingAPI{
resourcegroupstaggingapi.New(awsSession),
}
tagClientNames := map[*resourcegroupstaggingapi.ResourceGroupsTaggingAPI]string{
tagClients[0]: o.Region,
}
if o.Region != "us-east-1" {
tagClient := resourcegroupstaggingapi.New(
awsSession, aws.NewConfig().WithRegion("us-east-1"),
)
tagClients = append(tagClients, tagClient)
tagClientNames[tagClient] = "us-east-1"
}
deleted := map[string]struct{}{}
iamClient := iam.New(awsSession)
iamRoleSearch := &iamRoleSearch{
client: iamClient,
filters: o.Filters,
logger: o.Logger,
}
iamUserSearch := &iamUserSearch{
client: iamClient,
filters: o.Filters,
logger: o.Logger,
}
err = wait.PollImmediateInfinite(
time.Second*10,
func() (done bool, err error) {
var loopError error
nextTagClients := tagClients[:0]
for _, tagClient := range tagClients {
matched := false
for _, filter := range o.Filters {
o.Logger.Debugf("search for and delete matching resources by tag in %s matching %#+v", tagClientNames[tagClient], filter)
tagFilters := make([]*resourcegroupstaggingapi.TagFilter, 0, len(filter))
for key, value := range filter {
tagFilters = append(tagFilters, &resourcegroupstaggingapi.TagFilter{
Key: aws.String(key),
Values: []*string{aws.String(value)},
})
}
err = tagClient.GetResourcesPages(
&resourcegroupstaggingapi.GetResourcesInput{TagFilters: tagFilters},
func(results *resourcegroupstaggingapi.GetResourcesOutput, lastPage bool) bool {
for _, resource := range results.ResourceTagMappingList {
arn := *resource.ResourceARN
if _, ok := deleted[arn]; !ok {
matched = true
err := deleteARN(awsSession, arn, filter, o.Logger)
if err != nil {
err = errors.Wrapf(err, "deleting %s", arn)
o.Logger.Debug(err)
continue
}
deleted[arn] = exists
}
}
return !lastPage
},
)
if err != nil {
err = errors.Wrap(err, "get tagged resources")
o.Logger.Info(err)
matched = true
loopError = err
}
}
if matched {
nextTagClients = append(nextTagClients, tagClient)
} else {
o.Logger.Debugf("no deletions from %s, removing client", tagClientNames[tagClient])
}
}
tagClients = nextTagClients
o.Logger.Debug("search for IAM roles")
arns, err := iamRoleSearch.arns()
if err != nil {
o.Logger.Info(err)
loopError = err
}
o.Logger.Debug("search for IAM users")
userARNs, err := iamUserSearch.arns()
if err != nil {
o.Logger.Info(err)
loopError = err
}
arns = append(arns, userARNs...)
if len(arns) > 0 {
o.Logger.Debug("delete IAM roles and users")
}
for _, arn := range arns {
if _, ok := deleted[arn]; !ok {
err = deleteARN(awsSession, arn, nil, o.Logger)
if err != nil {
err = errors.Wrapf(err, "deleting %s", arn)
o.Logger.Debug(err)
loopError = err
continue
}
deleted[arn] = exists
}
}
return len(tagClients) == 0 && loopError == nil, nil
},
)
if err != nil {
return err
}
o.Logger.Debug("search for untaggable resources")
if err := o.deleteUntaggedResources(awsSession); err != nil {
o.Logger.Debug(err)
return err
}
return nil
}
func splitSlash(name string, input string) (base string, suffix string, err error) {
segments := strings.SplitN(input, "/", 2)
if len(segments) != 2 {
return "", "", errors.Errorf("%s %q does not contain the expected slash", name, input)
}
return segments[0], segments[1], nil
}
func tagMatch(filters []Filter, tags map[string]string) bool {
for _, filter := range filters {
match := true
for filterKey, filterValue := range filter {
tagValue, ok := tags[filterKey]
if !ok {
match = false
break
}
if tagValue != filterValue {
match = false
break
}
}
if match {
return true
}
}
return len(filters) == 0
}
func tagsForFilter(filter Filter) []*ec2.Tag {
tags := make([]*ec2.Tag, 0, len(filter))
for key, value := range filter {
tags = append(tags, &ec2.Tag{
Key: aws.String(key),
Value: aws.String(value),
})
}
return tags
}
type iamRoleSearch struct {
client *iam.IAM
filters []Filter
logger logrus.FieldLogger
unmatched map[string]struct{}
}
func (search *iamRoleSearch) arns() ([]string, error) {
if search.unmatched == nil {
search.unmatched = map[string]struct{}{}
}
arns := []string{}
var lastError error
err := search.client.ListRolesPages(
&iam.ListRolesInput{},
func(results *iam.ListRolesOutput, lastPage bool) bool {
for _, role := range results.Roles {
if _, ok := search.unmatched[*role.Arn]; ok {
continue
}
// Unfortunately role.Tags is empty from ListRoles, so we need to query each one
response, err := search.client.GetRole(&iam.GetRoleInput{RoleName: role.RoleName})
if err != nil {
if err.(awserr.Error).Code() == iam.ErrCodeNoSuchEntityException {
search.unmatched[*role.Arn] = exists
} else {
if lastError != nil {
search.logger.Debug(lastError)
}
lastError = errors.Wrapf(err, "get tags for %s", *role.Arn)
}
} else {
role = response.Role
tags := make(map[string]string, len(role.Tags))
for _, tag := range role.Tags {
tags[*tag.Key] = *tag.Value
}
if tagMatch(search.filters, tags) {
arns = append(arns, *role.Arn)
} else {
search.unmatched[*role.Arn] = exists
}
}
}
return !lastPage
},
)
if lastError != nil {
return arns, lastError
}
return arns, err
}
type iamUserSearch struct {
client *iam.IAM
filters []Filter
logger logrus.FieldLogger
unmatched map[string]struct{}
}
func (search *iamUserSearch) arns() ([]string, error) {
if search.unmatched == nil {
search.unmatched = map[string]struct{}{}
}
arns := []string{}
var lastError error
err := search.client.ListUsersPages(
&iam.ListUsersInput{},
func(results *iam.ListUsersOutput, lastPage bool) bool {
for _, user := range results.Users {
if _, ok := search.unmatched[*user.Arn]; ok {
continue
}
// Unfortunately user.Tags is empty from ListUsers, so we need to query each one
response, err := search.client.GetUser(&iam.GetUserInput{UserName: aws.String(*user.UserName)})
if err != nil {
if err.(awserr.Error).Code() == iam.ErrCodeNoSuchEntityException {
search.unmatched[*user.Arn] = exists
} else {
if lastError != nil {
search.logger.Debug(lastError)
}
lastError = errors.Wrapf(err, "get tags for %s", *user.Arn)
}
} else {
user = response.User
tags := make(map[string]string, len(user.Tags))
for _, tag := range user.Tags {
tags[*tag.Key] = *tag.Value
}
if tagMatch(search.filters, tags) {
arns = append(arns, *user.Arn)
} else {
search.unmatched[*user.Arn] = exists
}
}
}
return !lastPage
},
)
if lastError != nil {
return arns, lastError
}
return arns, err
}
// getSharedHostedZone will find the ID of the non-Terraform-managed public route53 zone given the
// Terraform-managed zone's privateID.
func getSharedHostedZone(client *route53.Route53, privateID string, logger logrus.FieldLogger) (string, error) {
response, err := client.GetHostedZone(&route53.GetHostedZoneInput{
Id: aws.String(privateID),
})
if err != nil {
return "", err
}
privateName := *response.HostedZone.Name
if response.HostedZone.Config != nil && response.HostedZone.Config.PrivateZone != nil {
if !*response.HostedZone.Config.PrivateZone {
return "", errors.Errorf("getSharedHostedZone requires a private ID, but was passed the public %s", privateID)
}
} else {
logger.WithField("hosted zone", privateName).Warn("could not determine whether hosted zone is private")
}
domain := privateName
parents := []string{domain}
for {
idx := strings.Index(domain, ".")
if idx == -1 {
break
}
if len(domain[idx+1:]) > 0 {
parents = append(parents, domain[idx+1:])
}
domain = domain[idx+1:]
}
for _, p := range parents {
sZone, err := findPublicRoute53(client, p, logger)
if err != nil {
return "", err
}
if sZone != "" {
return sZone, nil
}
}
return "", nil
}
// findPublicRoute53 finds a public route53 zone matching the dnsName.
// It returns "", when no public route53 zone could be found.
func findPublicRoute53(client *route53.Route53, dnsName string, logger logrus.FieldLogger) (string, error) {
request := &route53.ListHostedZonesByNameInput{
DNSName: aws.String(dnsName),
}
for i := 0; true; i++ {
logger.Debugf("listing AWS hosted zones %q (page %d)", dnsName, i)
list, err := client.ListHostedZonesByName(request)
if err != nil {
return "", err
}
for _, zone := range list.HostedZones {
if *zone.Name != dnsName {
// No name after this can match dnsName
return "", nil
}
if zone.Config == nil || zone.Config.PrivateZone == nil {
logger.WithField("hosted zone", *zone.Name).Warn("could not determine whether hosted zone is private")
continue
}
if !*zone.Config.PrivateZone {
return *zone.Id, nil
}
}
if *list.IsTruncated && *list.NextDNSName == *request.DNSName {
request.HostedZoneId = list.NextHostedZoneId
continue
}
break
}
return "", nil
}
func deleteARN(session *session.Session, arnString string, filter Filter, logger logrus.FieldLogger) error {
logger = logger.WithField("arn", arnString)
parsed, err := arn.Parse(arnString)
if err != nil {
return err
}
switch parsed.Service {
case "ec2":
return deleteEC2(session, parsed, filter, logger)
case "elasticloadbalancing":
return deleteElasticLoadBalancing(session, parsed, logger)
case "iam":
return deleteIAM(session, parsed, logger)
case "route53":
return deleteRoute53(session, parsed, logger)
case "s3":
return deleteS3(session, parsed, logger)
default:
return errors.Errorf("unrecognized ARN service %s (%s)", parsed.Service, arnString)
}
}
func deleteEC2(session *session.Session, arn arn.ARN, filter Filter, logger logrus.FieldLogger) error {
client := ec2.New(session)
resourceType, id, err := splitSlash("resource", arn.Resource)
if err != nil {
return err
}
logger = logger.WithField("id", id)
switch resourceType {
case "dhcp-options":
return deleteEC2DHCPOptions(client, id, logger)
case "elastic-ip":
return deleteEC2ElasticIP(client, id, logger)
case "image":
return deleteEC2Image(client, id, filter, logger)
case "instance":
return deleteEC2Instance(client, iam.New(session), id, logger)
case "internet-gateway":
return deleteEC2InternetGateway(client, id, logger)
case "natgateway":
return deleteEC2NATGateway(client, id, logger)
case "route-table":
return deleteEC2RouteTable(client, id, logger)
case "security-group":
return deleteEC2SecurityGroup(client, id, logger)
case "snapshot":
return deleteEC2Snapshot(client, id, logger)
case "network-interface":
return deleteEC2NetworkInterface(client, id, logger)
case "subnet":
return deleteEC2Subnet(client, id, logger)
case "volume":
return deleteEC2Volume(client, id, logger)
case "vpc":
return deleteEC2VPC(client, elb.New(session), elbv2.New(session), id, logger)
default:
return errors.Errorf("unrecognized EC2 resource type %s", resourceType)
}
}
func deleteEC2DHCPOptions(client *ec2.EC2, id string, logger logrus.FieldLogger) error {
_, err := client.DeleteDhcpOptions(&ec2.DeleteDhcpOptionsInput{
DhcpOptionsId: &id,
})
if err != nil {
if err.(awserr.Error).Code() == "InvalidDhcpOptionsID.NotFound" {
return nil
}
return err
}
logger.Info("Deleted")
return nil
}
func deleteEC2Image(client *ec2.EC2, id string, filter Filter, logger logrus.FieldLogger) error {
// tag the snapshots used by the AMI so that the snapshots are matched
// by the filter and deleted
response, err := client.DescribeImages(&ec2.DescribeImagesInput{
ImageIds: []*string{&id},
})
if err != nil {
if err.(awserr.Error).Code() == "InvalidAMIID.NotFound" {
return nil
}
return err
}
snapshots := []*string{}
for _, image := range response.Images {
for _, bdm := range image.BlockDeviceMappings {
if bdm.Ebs != nil && bdm.Ebs.SnapshotId != nil {
snapshots = append(snapshots, bdm.Ebs.SnapshotId)
}
}
}
_, err = client.CreateTags(&ec2.CreateTagsInput{
Resources: snapshots,
Tags: tagsForFilter(filter),
})
if err != nil {
err = errors.Wrapf(err, "tagging snapshots for %s", id)
}
_, err = client.DeregisterImage(&ec2.DeregisterImageInput{
ImageId: &id,
})
if err != nil {
if err.(awserr.Error).Code() == "InvalidAMIID.NotFound" {
return nil
}
return err
}
logger.Info("Deleted")
return nil
}
func deleteEC2ElasticIP(client *ec2.EC2, id string, logger logrus.FieldLogger) error {
_, err := client.ReleaseAddress(&ec2.ReleaseAddressInput{
AllocationId: aws.String(id),
})
if err != nil {
if err.(awserr.Error).Code() == "InvalidAllocationID.NotFound" {
return nil
}
return err
}
logger.Info("Released")
return nil
}
func deleteEC2Instance(ec2Client *ec2.EC2, iamClient *iam.IAM, id string, logger logrus.FieldLogger) error {
response, err := ec2Client.DescribeInstances(&ec2.DescribeInstancesInput{
InstanceIds: []*string{aws.String(id)},
})
if err != nil {
if err.(awserr.Error).Code() == "InvalidInstanceID.NotFound" {
return nil
}
return err
}
for _, reservation := range response.Reservations {
for _, instance := range reservation.Instances {
// Skip 'terminated' instances since they take a while to really get cleaned up
if *instance.State.Name == "terminated" {
continue
}
if instance.IamInstanceProfile != nil {
parsed, err := arn.Parse(*instance.IamInstanceProfile.Arn)
if err != nil {
return errors.Wrap(err, "parse ARN for IAM instance profile")
}
err = deleteIAMInstanceProfile(iamClient, parsed, logger.WithField("IAM instance profile", parsed.String()))
if err != nil {
return errors.Wrapf(err, "deleting %s", parsed.String())
}
}
_, err := ec2Client.TerminateInstances(&ec2.TerminateInstancesInput{
InstanceIds: []*string{instance.InstanceId},
})
if err != nil {
return err
}
logger.Info("Deleted")
}
}
return nil
}
// This is a bit of hack. Some objects, like Instance Profiles, can not be tagged in AWS.
// We "normally" find those objects by their relation to other objects. We have found,
// however, that people regularly delete all of their instances and roles outside of
// openshift-install destroy cluster. This means that we are unable to find the Instance
// Profiles.
//
// This code is a place to find specific objects like this which might be dangling.
func (o *ClusterUninstaller) deleteUntaggedResources(awsSession *session.Session) error {
iamClient := iam.New(awsSession)
masterProfile := fmt.Sprintf("%s-master-profile", o.ClusterID)
if err := deleteIAMInstanceProfileByName(iamClient, &masterProfile, o.Logger); err != nil {
return err
}
workerProfile := fmt.Sprintf("%s-worker-profile", o.ClusterID)
if err := deleteIAMInstanceProfileByName(iamClient, &workerProfile, o.Logger); err != nil {
return err
}
return nil
}
func deleteEC2InternetGateway(client *ec2.EC2, id string, logger logrus.FieldLogger) error {
response, err := client.DescribeInternetGateways(&ec2.DescribeInternetGatewaysInput{
InternetGatewayIds: []*string{aws.String(id)},
})
if err != nil {
return err
}
for _, gateway := range response.InternetGateways {
for _, vpc := range gateway.Attachments {
if vpc.VpcId == nil {
logger.Warn("gateway does not have a VPC ID")
continue
}
_, err := client.DetachInternetGateway(&ec2.DetachInternetGatewayInput{
InternetGatewayId: gateway.InternetGatewayId,
VpcId: vpc.VpcId,
})
if err == nil {
logger.WithField("vpc", *vpc.VpcId).Debug("Detached")
} else if err.(awserr.Error).Code() != "Gateway.NotAttached" {
return errors.Wrapf(err, "detaching from %s", *vpc.VpcId)
}
}
}
_, err = client.DeleteInternetGateway(&ec2.DeleteInternetGatewayInput{
InternetGatewayId: &id,
})
if err != nil {
return err
}
logger.Info("Deleted")
return nil
}
func deleteEC2NATGateway(client *ec2.EC2, id string, logger logrus.FieldLogger) error {
_, err := client.DeleteNatGateway(&ec2.DeleteNatGatewayInput{
NatGatewayId: aws.String(id),
})
if err != nil {
return err
}
logger.Info("Deleted")
return nil
}
func deleteEC2RouteTable(client *ec2.EC2, id string, logger logrus.FieldLogger) error {
response, err := client.DescribeRouteTables(&ec2.DescribeRouteTablesInput{
RouteTableIds: []*string{aws.String(id)},
})
if err != nil {
if err.(awserr.Error).Code() == "InvalidRouteTableID.NotFound" {
return nil
}
return err
}
for _, table := range response.RouteTables {
err = deleteEC2RouteTableObject(client, table, logger)
if err != nil {
return err
}
}
return nil
}
func deleteEC2RouteTableObject(client *ec2.EC2, table *ec2.RouteTable, logger logrus.FieldLogger) error {
hasMain := false
for _, association := range table.Associations {
if *association.Main {
// can't remove the 'Main' association
hasMain = true
continue
}
_, err := client.DisassociateRouteTable(&ec2.DisassociateRouteTableInput{
AssociationId: association.RouteTableAssociationId,
})
if err != nil {
return errors.Wrapf(err, "dissociating %s", *association.RouteTableAssociationId)
}
logger.WithField("id", *association.RouteTableAssociationId).Info("Disassociated")
}
if hasMain {
// can't delete route table with the 'Main' association
// it will get cleaned up as part of deleting the VPC
return nil
}
_, err := client.DeleteRouteTable(&ec2.DeleteRouteTableInput{
RouteTableId: table.RouteTableId,
})
if err != nil {
return err
}
logger.Info("Deleted")
return nil
}
func deleteEC2RouteTablesByVPC(client *ec2.EC2, vpc string, logger logrus.FieldLogger) error {
var lastError error
err := client.DescribeRouteTablesPages(
&ec2.DescribeRouteTablesInput{
Filters: []*ec2.Filter{
{
Name: aws.String("vpc-id"),
Values: []*string{&vpc},
},
},
},
func(results *ec2.DescribeRouteTablesOutput, lastPage bool) bool {
for _, table := range results.RouteTables {
err := deleteEC2RouteTableObject(client, table, logger.WithField("table", *table.RouteTableId))
if err != nil {
if lastError != nil {
logger.Debug(err)
}
lastError = errors.Wrapf(err, "deleting EC2 route table %s", *table.RouteTableId)
}
}
return !lastPage
},
)
if lastError != nil {
return lastError
}
return err
}
func deleteEC2SecurityGroup(client *ec2.EC2, id string, logger logrus.FieldLogger) error {
response, err := client.DescribeSecurityGroups(&ec2.DescribeSecurityGroupsInput{
GroupIds: []*string{aws.String(id)},
})
if err != nil {
if err.(awserr.Error).Code() == "InvalidGroup.NotFound" {
return nil
}
return err
}
for _, group := range response.SecurityGroups {
if len(group.IpPermissions) > 0 {
_, err := client.RevokeSecurityGroupIngress(&ec2.RevokeSecurityGroupIngressInput{
GroupId: group.GroupId,
IpPermissions: group.IpPermissions,
})
if err != nil {
return errors.Wrap(err, "revoking ingress permissions")
}
logger.Debug("Revoked ingress permissions")
}
if len(group.IpPermissionsEgress) > 0 {
_, err := client.RevokeSecurityGroupEgress(&ec2.RevokeSecurityGroupEgressInput{
GroupId: group.GroupId,
IpPermissions: group.IpPermissionsEgress,
})
if err != nil {
return errors.Wrap(err, "revoking egress permissions")
}
logger.Debug("Revoked egress permissions")
}
}
_, err = client.DeleteSecurityGroup(&ec2.DeleteSecurityGroupInput{
GroupId: aws.String(id),
})
if err != nil {
if err.(awserr.Error).Code() == "InvalidGroup.NotFound" {
return nil
}
return err
}
logger.Info("Deleted")
return nil
}
func deleteEC2Snapshot(client *ec2.EC2, id string, logger logrus.FieldLogger) error {
_, err := client.DeleteSnapshot(&ec2.DeleteSnapshotInput{
SnapshotId: &id,
})
if err != nil {
if err.(awserr.Error).Code() == "InvalidSnapshotID.NotFound" {
return nil
}
return err
}
logger.Info("Deleted")
return nil
}
func deleteEC2NetworkInterface(client *ec2.EC2, id string, logger logrus.FieldLogger) error {
_, err := client.DeleteNetworkInterface(&ec2.DeleteNetworkInterfaceInput{
NetworkInterfaceId: aws.String(id),
})
if err != nil {
if err.(awserr.Error).Code() == "InvalidNetworkInterfaceID.NotFound" {
return nil
}
return err
}
logger.Info("Deleted")
return nil
}
func deleteEC2NetworkInterfaceByVPC(client *ec2.EC2, vpc string, logger logrus.FieldLogger) error {
var lastError error
err := client.DescribeNetworkInterfacesPages(
&ec2.DescribeNetworkInterfacesInput{
Filters: []*ec2.Filter{
{
Name: aws.String("vpc-id"),
Values: []*string{&vpc},
},
},
},
func(results *ec2.DescribeNetworkInterfacesOutput, lastPage bool) bool {
for _, networkInterface := range results.NetworkInterfaces {
err := deleteEC2NetworkInterface(client, *networkInterface.NetworkInterfaceId, logger.WithField("network interface", *networkInterface.NetworkInterfaceId))
if err != nil {
if lastError != nil {
logger.Debug(lastError)
}
lastError = errors.Wrapf(err, "deleting EC2 network interface %s", *networkInterface.NetworkInterfaceId)
}
}
return !lastPage
},
)
if lastError != nil {
return lastError
}
return err
}
func deleteEC2Subnet(client *ec2.EC2, id string, logger logrus.FieldLogger) error {
_, err := client.DeleteSubnet(&ec2.DeleteSubnetInput{
SubnetId: aws.String(id),
})
if err != nil {
if err.(awserr.Error).Code() == "InvalidSubnetID.NotFound" {
return nil
}
return err
}
logger.Info("Deleted")
return nil
}
func deleteEC2Volume(client *ec2.EC2, id string, logger logrus.FieldLogger) error {
_, err := client.DeleteVolume(&ec2.DeleteVolumeInput{
VolumeId: aws.String(id),
})
if err != nil {
if err.(awserr.Error).Code() == "InvalidVolume.NotFound" {
return nil
}
return err
}
logger.Info("Deleted")
return nil
}
func deleteEC2VPC(ec2Client *ec2.EC2, elbClient *elb.ELB, elbv2Client *elbv2.ELBV2, id string, logger logrus.FieldLogger) error {
// first delete any Load Balancers under this VPC (not all of them are tagged)
v1lbError := deleteElasticLoadBalancerClassicByVPC(elbClient, id, logger)
v2lbError := deleteElasticLoadBalancerV2ByVPC(elbv2Client, id, logger)
if v1lbError != nil {
if v2lbError != nil {
logger.Info(v2lbError)
}
return v1lbError
} else if v2lbError != nil {
return v2lbError
}
for _, helper := range [](func(client *ec2.EC2, vpc string, logger logrus.FieldLogger) error){
deleteEC2NetworkInterfaceByVPC, // not always tagged
deleteEC2RouteTablesByVPC, // not always tagged
deleteEC2VPCEndpointsByVPC, // not taggable
} {
err := helper(ec2Client, id, logger)
if err != nil {
return err
}
}
_, err := ec2Client.DeleteVpc(&ec2.DeleteVpcInput{
VpcId: aws.String(id),
})
if err != nil {
return err
}
logger.Info("Deleted")
return nil
}
func deleteEC2VPCEndpoint(client *ec2.EC2, id string, logger logrus.FieldLogger) error {
_, err := client.DeleteVpcEndpoints(&ec2.DeleteVpcEndpointsInput{
VpcEndpointIds: []*string{aws.String(id)},
})
if err != nil {
return errors.Wrapf(err, "cannot delete VPC endpoint %s", id)
}
logger.Info("Deleted")
return nil
}
func deleteEC2VPCEndpointsByVPC(client *ec2.EC2, vpc string, logger logrus.FieldLogger) error {
response, err := client.DescribeVpcEndpoints(&ec2.DescribeVpcEndpointsInput{
Filters: []*ec2.Filter{
{
Name: aws.String("vpc-id"),
Values: []*string{aws.String(vpc)},
},
},
})
if err != nil {
return err
}
for _, endpoint := range response.VpcEndpoints {
err := deleteEC2VPCEndpoint(client, *endpoint.VpcEndpointId, logger.WithField("VPC endpoint", *endpoint.VpcEndpointId))
if err != nil {
if err.(awserr.Error).Code() == "InvalidVpcID.NotFound" {
return nil
}
return err
}
}
return nil
}
func deleteElasticLoadBalancing(session *session.Session, arn arn.ARN, logger logrus.FieldLogger) error {
resourceType, id, err := splitSlash("resource", arn.Resource)