forked from kubernetes/test-infra
/
main.go
1186 lines (1035 loc) · 33 KB
/
main.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
/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"net/url"
"os"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/autoscaling"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/golang/glog"
)
const defaultRegion = "us-east-1"
var maxTTL = flag.Duration("ttl", 24*time.Hour, "Maximum time before we attempt deletion of a resource. Set to 0s to nuke all non-default resources.")
var path = flag.String("path", "", "S3 path to store mark data in (required)")
type awsResourceType interface {
// MarkAndSweep queries the resource in a specific region, using
// the provided session (which has account-number acct), calling
// res.Mark(<resource>) on each resource and deleting
// appropriately.
MarkAndSweep(sess *session.Session, acct string, region string, res *awsResourceSet) error
}
// AWS resource types known to this script, in dependency order.
var awsResourceTypes = []awsResourceType{
autoScalingGroups{},
launchConfigurations{},
instances{},
// Addresses
// NetworkInterfaces
subnets{},
securityGroups{},
// NetworkACLs
// VPN Connections
internetGateways{},
routeTables{},
vpcs{},
dhcpOptions{},
volumes{},
addresses{},
// Note that order matters here - we can't delete roles until we've deleted the profiles
iamInstanceProfiles{},
iamRoles{},
}
type awsResource interface {
// ARN returns the AWS ARN for the resource
// (c.f. http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html). This
// is only used for uniqueness in the Mark set, but ARNs are
// intended to be globally unique across regions and accounts, so
// that works.
ARN() string
// ResourceKey() returns a per-resource key, because ARNs might conflict if two objects
// with the same name are created at different times (e.g. IAM roles)
ResourceKey() string
}
// awsResourceSet keeps track of the first time we saw a particular
// ARN, and the global TTL. See Mark() for more details.
type awsResourceSet struct {
firstSeen map[string]time.Time // ARN -> first time we saw
marked map[string]bool // ARN -> seen this run
swept []string // List of resources we attempted to sweep (to summarize)
ttl time.Duration
}
func LoadResourceSet(sess *session.Session, p *s3path, ttl time.Duration) (*awsResourceSet, error) {
s := &awsResourceSet{firstSeen: make(map[string]time.Time), marked: make(map[string]bool), ttl: ttl}
svc := s3.New(sess, &aws.Config{Region: aws.String(p.region)})
resp, err := svc.GetObject(&s3.GetObjectInput{Bucket: aws.String(p.bucket), Key: aws.String(p.key)})
if err != nil {
if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "NoSuchKey" {
return s, nil
}
return nil, err
}
defer resp.Body.Close()
if err := json.NewDecoder(resp.Body).Decode(&s.firstSeen); err != nil {
return nil, err
}
return s, nil
}
func (s *awsResourceSet) Save(sess *session.Session, p *s3path) error {
b, err := json.MarshalIndent(s.firstSeen, "", " ")
if err != nil {
return err
}
svc := s3.New(sess, &aws.Config{Region: aws.String(p.region)})
_, err = svc.PutObject(&s3.PutObjectInput{
Bucket: aws.String(p.bucket),
Key: aws.String(p.key),
Body: bytes.NewReader(b),
CacheControl: aws.String("max-age=0"),
})
return err
}
// Mark marks a particular resource as currently present, and advises
// on whether it should be deleted. If Mark(r) returns true, the TTL
// has expired for r and it should be deleted.
func (s *awsResourceSet) Mark(r awsResource) bool {
key := r.ResourceKey()
now := time.Now()
s.marked[key] = true
if t, ok := s.firstSeen[key]; ok {
since := now.Sub(t)
if since > s.ttl {
s.swept = append(s.swept, key)
return true
}
glog.V(1).Infof("%s: seen for %v", key, since)
return false
}
s.firstSeen[key] = now
glog.V(1).Infof("%s: first seen", key)
if s.ttl == 0 {
// If the TTL is 0, it should be deleted now.
s.swept = append(s.swept, key)
return true
}
return false
}
// MarkComplete figures out which ARNs were in previous passes but not
// this one, and eliminates them. It should only be run after all
// resources have been marked.
func (s *awsResourceSet) MarkComplete() int {
var gone []string
for key := range s.firstSeen {
if !s.marked[key] {
gone = append(gone, key)
}
}
for _, key := range gone {
glog.V(1).Infof("%s: deleted since last run", key)
delete(s.firstSeen, key)
}
if len(s.swept) > 0 {
glog.Errorf("%d resources swept: %v", len(s.swept), s.swept)
}
return len(s.swept)
}
// Instances: https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#EC2.DescribeInstances
type instances struct{}
func (instances) MarkAndSweep(sess *session.Session, acct string, region string, set *awsResourceSet) error {
svc := ec2.New(sess, &aws.Config{Region: aws.String(region)})
inp := &ec2.DescribeInstancesInput{
Filters: []*ec2.Filter{
{
Name: aws.String("instance-state-name"),
Values: []*string{aws.String("running"), aws.String("pending")},
},
},
}
var toDelete []*string // Paged call, defer deletion until we have the whole list.
if err := svc.DescribeInstancesPages(inp, func(page *ec2.DescribeInstancesOutput, _ bool) bool {
for _, res := range page.Reservations {
for _, inst := range res.Instances {
i := &instance{
Account: acct,
Region: region,
InstanceID: *inst.InstanceId,
}
if set.Mark(i) {
glog.Warningf("%s: deleting %T: %v", i.ARN(), inst, inst)
toDelete = append(toDelete, inst.InstanceId)
}
}
}
return true
}); err != nil {
return err
}
if len(toDelete) > 0 {
// TODO(zmerlynn): In theory this should be split up into
// blocks of 1000, but burn that bridge if it ever happens...
_, err := svc.TerminateInstances(&ec2.TerminateInstancesInput{InstanceIds: toDelete})
if err != nil {
glog.Warningf("termination failed: %v (for %v)", err, toDelete)
}
}
return nil
}
type instance struct {
Account string
Region string
InstanceID string
}
func (i instance) ARN() string {
return fmt.Sprintf("arn:aws:ec2:%s:%s:instance/%s", i.Region, i.Account, i.InstanceID)
}
func (i instance) ResourceKey() string {
return i.ARN()
}
// AutoScalingGroups: https://docs.aws.amazon.com/sdk-for-go/api/service/autoscaling/#AutoScaling.DescribeAutoScalingGroups
type autoScalingGroups struct{}
func (autoScalingGroups) MarkAndSweep(sess *session.Session, acct string, region string, set *awsResourceSet) error {
svc := autoscaling.New(sess, &aws.Config{Region: aws.String(region)})
var toDelete []*autoScalingGroup // Paged call, defer deletion until we have the whole list.
if err := svc.DescribeAutoScalingGroupsPages(nil, func(page *autoscaling.DescribeAutoScalingGroupsOutput, _ bool) bool {
for _, asg := range page.AutoScalingGroups {
a := &autoScalingGroup{ID: *asg.AutoScalingGroupARN, Name: *asg.AutoScalingGroupName}
if set.Mark(a) {
glog.Warningf("%s: deleting %T: %v", a.ARN(), asg, asg)
toDelete = append(toDelete, a)
}
}
return true
}); err != nil {
return err
}
for _, asg := range toDelete {
_, err := svc.DeleteAutoScalingGroup(
&autoscaling.DeleteAutoScalingGroupInput{
AutoScalingGroupName: aws.String(asg.Name),
ForceDelete: aws.Bool(true),
})
if err != nil {
glog.Warningf("%v: delete failed: %v", asg.ARN(), err)
}
}
// Block on ASGs finishing deletion. There are a lot of dependent
// resources, so this just makes the rest go more smoothly (and
// prevents a second pass).
for _, asg := range toDelete {
glog.Warningf("%v: waiting for delete", asg.ARN())
err := svc.WaitUntilGroupNotExists(
&autoscaling.DescribeAutoScalingGroupsInput{
AutoScalingGroupNames: []*string{aws.String(asg.Name)},
})
if err != nil {
glog.Warningf("%v: wait failed: %v", asg.ARN(), err)
}
}
return nil
}
type autoScalingGroup struct {
ID string
Name string
}
func (asg autoScalingGroup) ARN() string {
return asg.ID
}
func (asg autoScalingGroup) ResourceKey() string {
return asg.ARN()
}
// LaunchConfigurations: http://docs.aws.amazon.com/sdk-for-go/api/service/autoscaling/#AutoScaling.DescribeLaunchConfigurations
type launchConfigurations struct{}
func (launchConfigurations) MarkAndSweep(sess *session.Session, acct string, region string, set *awsResourceSet) error {
svc := autoscaling.New(sess, &aws.Config{Region: aws.String(region)})
var toDelete []*launchConfiguration // Paged call, defer deletion until we have the whole list.
if err := svc.DescribeLaunchConfigurationsPages(nil, func(page *autoscaling.DescribeLaunchConfigurationsOutput, _ bool) bool {
for _, lc := range page.LaunchConfigurations {
l := &launchConfiguration{ID: *lc.LaunchConfigurationARN, Name: *lc.LaunchConfigurationName}
if set.Mark(l) {
glog.Warningf("%s: deleting %T: %v", l.ARN(), lc, lc)
toDelete = append(toDelete, l)
}
}
return true
}); err != nil {
return err
}
for _, lc := range toDelete {
_, err := svc.DeleteLaunchConfiguration(
&autoscaling.DeleteLaunchConfigurationInput{
LaunchConfigurationName: aws.String(lc.Name),
})
if err != nil {
glog.Warningf("%v: delete failed: %v", lc.ARN(), err)
}
}
return nil
}
type launchConfiguration struct {
ID string
Name string
}
func (lc launchConfiguration) ARN() string {
return lc.ID
}
func (lc launchConfiguration) ResourceKey() string {
return lc.ARN()
}
// Subnets: https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#EC2.DescribeSubnets
type subnets struct{}
func (subnets) MarkAndSweep(sess *session.Session, acct string, region string, set *awsResourceSet) error {
svc := ec2.New(sess, &aws.Config{Region: aws.String(region)})
resp, err := svc.DescribeSubnets(&ec2.DescribeSubnetsInput{
Filters: []*ec2.Filter{
{
Name: aws.String("defaultForAz"),
Values: []*string{aws.String("false")},
},
},
})
if err != nil {
return err
}
for _, sub := range resp.Subnets {
s := &subnet{Account: acct, Region: region, ID: *sub.SubnetId}
if set.Mark(s) {
glog.Warningf("%s: deleting %T: %v", s.ARN(), sub, sub)
_, err := svc.DeleteSubnet(&ec2.DeleteSubnetInput{SubnetId: sub.SubnetId})
if err != nil {
glog.Warningf("%v: delete failed: %v", s.ARN(), err)
}
}
}
return nil
}
type subnet struct {
Account string
Region string
ID string
}
func (sub subnet) ARN() string {
return fmt.Sprintf("arn:aws:ec2:%s:%s:subnet/%s", sub.Region, sub.Account, sub.ID)
}
func (sub subnet) ResourceKey() string {
return sub.ARN()
}
// SecurityGroups: https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#EC2.DescribeSecurityGroups
type securityGroups struct{}
type sgRef struct {
id string
perm *ec2.IpPermission
}
func addRefs(refs map[string][]*sgRef, id string, acct string, perms []*ec2.IpPermission) {
for _, perm := range perms {
for _, pair := range perm.UserIdGroupPairs {
// Ignore cross-account for now, and skip circular refs.
if *pair.UserId == acct && *pair.GroupId != id {
refs[*pair.GroupId] = append(refs[*pair.GroupId], &sgRef{id: id, perm: perm})
}
}
}
}
func (securityGroups) MarkAndSweep(sess *session.Session, acct string, region string, set *awsResourceSet) error {
svc := ec2.New(sess, &aws.Config{Region: aws.String(region)})
resp, err := svc.DescribeSecurityGroups(nil)
if err != nil {
return err
}
var toDelete []*securityGroup // Deferred to disentangle referencing security groups
ingress := make(map[string][]*sgRef) // sg.GroupId -> [sg.GroupIds with this ingress]
egress := make(map[string][]*sgRef) // sg.GroupId -> [sg.GroupIds with this egress]
for _, sg := range resp.SecurityGroups {
if *sg.GroupName == "default" {
// TODO(zmerlynn): Is there really no better way to detect this?
continue
}
s := &securityGroup{Account: acct, Region: region, ID: *sg.GroupId}
addRefs(ingress, *sg.GroupId, acct, sg.IpPermissions)
addRefs(egress, *sg.GroupId, acct, sg.IpPermissionsEgress)
if set.Mark(s) {
glog.Warningf("%s: deleting %T: %v", s.ARN(), sg, sg)
toDelete = append(toDelete, s)
}
}
for _, sg := range toDelete {
for _, ref := range ingress[sg.ID] {
glog.Infof("%v: revoking reference from %v", sg.ARN(), ref.id)
_, err := svc.RevokeSecurityGroupIngress(&ec2.RevokeSecurityGroupIngressInput{
GroupId: aws.String(ref.id),
IpPermissions: []*ec2.IpPermission{ref.perm},
})
if err != nil {
glog.Warningf("%v: failed to revoke ingress reference from %v: %v", sg.ARN(), ref.id, err)
}
}
for _, ref := range egress[sg.ID] {
_, err := svc.RevokeSecurityGroupEgress(&ec2.RevokeSecurityGroupEgressInput{
GroupId: aws.String(ref.id),
IpPermissions: []*ec2.IpPermission{ref.perm},
})
if err != nil {
glog.Warningf("%v: failed to revoke egress reference from %v: %v", sg.ARN(), ref.id, err)
}
}
_, err := svc.DeleteSecurityGroup(&ec2.DeleteSecurityGroupInput{GroupId: aws.String(sg.ID)})
if err != nil {
glog.Warningf("%v: delete failed: %v", sg.ARN(), err)
}
}
return nil
}
type securityGroup struct {
Account string
Region string
ID string
}
func (sg securityGroup) ARN() string {
return fmt.Sprintf("arn:aws:ec2:%s:%s:security-group/%s", sg.Region, sg.Account, sg.ID)
}
func (sg securityGroup) ResourceKey() string {
return sg.ARN()
}
// InternetGateways: https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#EC2.DescribeInternetGateways
type internetGateways struct{}
func (internetGateways) MarkAndSweep(sess *session.Session, acct string, region string, set *awsResourceSet) error {
svc := ec2.New(sess, &aws.Config{Region: aws.String(region)})
resp, err := svc.DescribeInternetGateways(nil)
if err != nil {
return err
}
vpcResp, err := svc.DescribeVpcs(&ec2.DescribeVpcsInput{
Filters: []*ec2.Filter{
{
Name: aws.String("isDefault"),
Values: []*string{aws.String("true")},
},
},
})
if err != nil {
return err
}
defaultVpc := vpcResp.Vpcs[0]
for _, ig := range resp.InternetGateways {
i := &internetGateway{Account: acct, Region: region, ID: *ig.InternetGatewayId}
if set.Mark(i) {
isDefault := false
glog.Warningf("%s: deleting %T: %v", i.ARN(), ig, ig)
for _, att := range ig.Attachments {
if att.VpcId == defaultVpc.VpcId {
isDefault = true
break
}
_, err := svc.DetachInternetGateway(&ec2.DetachInternetGatewayInput{
InternetGatewayId: ig.InternetGatewayId,
VpcId: att.VpcId,
})
if err != nil {
glog.Warningf("%v: detach from %v failed: %v", i.ARN(), *att.VpcId, err)
}
}
if isDefault {
glog.Infof("%s: skipping delete as IGW is the default for the VPC %T: %v", i.ARN(), ig, ig)
continue
}
_, err := svc.DeleteInternetGateway(&ec2.DeleteInternetGatewayInput{InternetGatewayId: ig.InternetGatewayId})
if err != nil {
glog.Warningf("%v: delete failed: %v", i.ARN(), err)
}
}
}
return nil
}
type internetGateway struct {
Account string
Region string
ID string
}
func (ig internetGateway) ARN() string {
return fmt.Sprintf("arn:aws:ec2:%s:%s:internet-gateway/%s", ig.Region, ig.Account, ig.ID)
}
func (ig internetGateway) ResourceKey() string {
return ig.ARN()
}
// RouteTables: https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#EC2.DescribeRouteTables
type routeTables struct{}
func (routeTables) MarkAndSweep(sess *session.Session, acct string, region string, set *awsResourceSet) error {
svc := ec2.New(sess, &aws.Config{Region: aws.String(region)})
resp, err := svc.DescribeRouteTables(nil)
if err != nil {
return err
}
for _, rt := range resp.RouteTables {
// Filter out the RouteTables that have a main
// association. Given the documention for the main.association
// filter, you'd think we could filter on the Describe, but it
// doesn't actually work, see e.g.
// https://github.com/aws/aws-cli/issues/1810
main := false
for _, assoc := range rt.Associations {
main = main || *assoc.Main
}
if main {
continue
}
r := &routeTable{Account: acct, Region: region, ID: *rt.RouteTableId}
if set.Mark(r) {
for _, assoc := range rt.Associations {
glog.Infof("%v: disassociating from %v", r.ARN(), *assoc.SubnetId)
_, err := svc.DisassociateRouteTable(&ec2.DisassociateRouteTableInput{
AssociationId: assoc.RouteTableAssociationId})
if err != nil {
glog.Warningf("%v: disassociation from subnet %v failed: %v", r.ARN(), *assoc.SubnetId, err)
}
}
glog.Warningf("%s: deleting %T: %v", r.ARN(), rt, rt)
_, err := svc.DeleteRouteTable(&ec2.DeleteRouteTableInput{RouteTableId: rt.RouteTableId})
if err != nil {
glog.Warningf("%v: delete failed: %v", r.ARN(), err)
}
}
}
return nil
}
type routeTable struct {
Account string
Region string
ID string
}
func (rt routeTable) ARN() string {
return fmt.Sprintf("arn:aws:ec2:%s:%s:route-table/%s", rt.Region, rt.Account, rt.ID)
}
func (rt routeTable) ResourceKey() string {
return rt.ARN()
}
// VPCs: https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#EC2.DescribeVpcs
type vpcs struct{}
func (vpcs) MarkAndSweep(sess *session.Session, acct string, region string, set *awsResourceSet) error {
svc := ec2.New(sess, &aws.Config{Region: aws.String(region)})
resp, err := svc.DescribeVpcs(&ec2.DescribeVpcsInput{
Filters: []*ec2.Filter{
{
Name: aws.String("isDefault"),
Values: []*string{aws.String("false")},
},
},
})
if err != nil {
return err
}
for _, vp := range resp.Vpcs {
v := &vpc{Account: acct, Region: region, ID: *vp.VpcId}
if set.Mark(v) {
glog.Warningf("%s: deleting %T: %v", v.ARN(), vp, vp)
if vp.DhcpOptionsId != nil && *vp.DhcpOptionsId != "default" {
_, err := svc.AssociateDhcpOptions(&ec2.AssociateDhcpOptionsInput{
VpcId: vp.VpcId,
DhcpOptionsId: aws.String("default"),
})
if err != nil {
glog.Warning("%v: disassociating DHCP option set %v failed: %v", v.ARN(), vp.DhcpOptionsId, err)
}
}
_, err := svc.DeleteVpc(&ec2.DeleteVpcInput{VpcId: vp.VpcId})
if err != nil {
glog.Warningf("%v: delete failed: %v", v.ARN(), err)
}
}
}
return nil
}
type vpc struct {
Account string
Region string
ID string
}
func (vp vpc) ARN() string {
return fmt.Sprintf("arn:aws:ec2:%s:%s:vpc/%s", vp.Region, vp.Account, vp.ID)
}
func (vp vpc) ResourceKey() string {
return vp.ARN()
}
// DhcpOptions: https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#EC2.DescribeDhcpOptions
type dhcpOptions struct{}
func (dhcpOptions) MarkAndSweep(sess *session.Session, acct string, region string, set *awsResourceSet) error {
svc := ec2.New(sess, &aws.Config{Region: aws.String(region)})
// This is a little gross, but I can't find an easier way to
// figure out the DhcpOptions associated with the default VPC.
defaultRefs := make(map[string]bool)
{
resp, err := svc.DescribeVpcs(&ec2.DescribeVpcsInput{
Filters: []*ec2.Filter{
{
Name: aws.String("isDefault"),
Values: []*string{aws.String("true")},
},
},
})
if err != nil {
return err
}
for _, vpc := range resp.Vpcs {
defaultRefs[*vpc.DhcpOptionsId] = true
}
}
resp, err := svc.DescribeDhcpOptions(nil)
if err != nil {
return err
}
var defaults []string
for _, dhcp := range resp.DhcpOptions {
if defaultRefs[*dhcp.DhcpOptionsId] {
continue
}
// Separately, skip any "default looking" DHCP Option Sets. See comment below.
if defaultLookingDHCPOptions(dhcp, region) {
defaults = append(defaults, *dhcp.DhcpOptionsId)
continue
}
dh := &dhcpOption{Account: acct, Region: region, ID: *dhcp.DhcpOptionsId}
if set.Mark(dh) {
glog.Warningf("%s: deleting %T: %v", dh.ARN(), dhcp, dhcp)
_, err := svc.DeleteDhcpOptions(&ec2.DeleteDhcpOptionsInput{DhcpOptionsId: dhcp.DhcpOptionsId})
if err != nil {
glog.Warningf("%v: delete failed: %v", dh.ARN(), err)
}
}
}
if len(defaults) > 1 {
glog.Errorf("Found more than one default-looking DHCP option set: %v", defaults)
}
return nil
}
// defaultLookingDHCPOptions: This part is a little annoying. If
// you're running in a region with where there is no default-looking
// DHCP option set, when you create any VPC, AWS will create a
// default-looking DHCP option set for you. If you then re-associate
// or delete the VPC, the option set will hang around. However, if you
// have a default-looking DHCP option set (even with no default VPC)
// and create a VPC, AWS will associate the VPC with the DHCP option
// set of the default VPC. There's no signal as to whether the option
// set returned is the default or was created along with the
// VPC. Because of this, we just skip these during cleanup - there
// will only ever be one default set per region.
func defaultLookingDHCPOptions(dhcp *ec2.DhcpOptions, region string) bool {
if len(dhcp.Tags) != 0 {
return false
}
for _, conf := range dhcp.DhcpConfigurations {
if *conf.Key == "domain-name" {
var domain string
if region == "us-east-1" {
domain = "ec2.internal"
} else {
domain = region + ".compute.internal"
}
if len(conf.Values) != 1 || *conf.Values[0].Value != domain {
return false
}
} else if *conf.Key == "domain-name-servers" {
if len(conf.Values) != 1 || *conf.Values[0].Value != "AmazonProvidedDNS" {
return false
}
} else {
return false
}
}
return true
}
type dhcpOption struct {
Account string
Region string
ID string
}
func (dhcp dhcpOption) ARN() string {
return fmt.Sprintf("arn:aws:ec2:%s:%s:dhcp-option/%s", dhcp.Region, dhcp.Account, dhcp.ID)
}
func (dhcp dhcpOption) ResourceKey() string {
return dhcp.ARN()
}
// Volumes: https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#EC2.DescribeVolumes
type volumes struct{}
func (volumes) MarkAndSweep(sess *session.Session, acct string, region string, set *awsResourceSet) error {
svc := ec2.New(sess, &aws.Config{Region: aws.String(region)})
var toDelete []*volume // Paged call, defer deletion until we have the whole list.
if err := svc.DescribeVolumesPages(nil, func(page *ec2.DescribeVolumesOutput, _ bool) bool {
for _, vol := range page.Volumes {
v := &volume{Account: acct, Region: region, ID: *vol.VolumeId}
if set.Mark(v) {
glog.Warningf("%s: deleting %T: %v", v.ARN(), vol, vol)
toDelete = append(toDelete, v)
}
}
return true
}); err != nil {
return err
}
for _, vol := range toDelete {
_, err := svc.DeleteVolume(&ec2.DeleteVolumeInput{VolumeId: aws.String(vol.ID)})
if err != nil {
glog.Warningf("%v: delete failed: %v", vol.ARN(), err)
}
}
return nil
}
type volume struct {
Account string
Region string
ID string
}
func (vol volume) ARN() string {
return fmt.Sprintf("arn:aws:ec2:%s:%s:volume/%s", vol.Region, vol.Account, vol.ID)
}
func (vol volume) ResourceKey() string {
return vol.ARN()
}
// Elastic IPs: https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#EC2.DescribeAddresses
type addresses struct{}
func (addresses) MarkAndSweep(sess *session.Session, acct string, region string, set *awsResourceSet) error {
svc := ec2.New(sess, &aws.Config{Region: aws.String(region)})
resp, err := svc.DescribeAddresses(nil)
if err != nil {
return err
}
for _, addr := range resp.Addresses {
a := &address{Account: acct, Region: region, ID: *addr.AllocationId}
if set.Mark(a) {
glog.Warningf("%s: deleting %T: %v", a.ARN(), addr, addr)
if addr.AssociationId != nil {
glog.Warningf("%s: disassociating %T from active instance", a.ARN(), addr)
_, err := svc.DisassociateAddress(&ec2.DisassociateAddressInput{AssociationId: addr.AssociationId})
if err != nil {
glog.Warningf("%s: disassociating %T failed: %v", a.ARN(), addr, err)
}
}
_, err := svc.ReleaseAddress(&ec2.ReleaseAddressInput{AllocationId: addr.AllocationId})
if err != nil {
glog.Warningf("%v: delete failed: %v", a.ARN(), err)
}
}
}
return nil
}
type address struct {
Account string
Region string
ID string
}
func (addr address) ARN() string {
// This ARN is a complete hallucination - there doesn't seem to be
// an ARN for elastic IPs.
return fmt.Sprintf("arn:aws:ec2:%s:%s:address/%s", addr.Region, addr.Account, addr.ID)
}
func (addr address) ResourceKey() string {
return addr.ARN()
}
// IAM Roles
type iamRoles struct{}
// roleIsManaged checks if the role should be managed (and thus deleted) by us
// In particular, we want to avoid "system" AWS roles or roles that might support test-infra
func roleIsManaged(role *iam.Role) bool {
name := aws.StringValue(role.RoleName)
path := aws.StringValue(role.Path)
// Most AWS system roles are in a directory called `aws-service-role`
if strings.HasPrefix(path, "/aws-service-role/") {
return false
}
// kops roles have names start with `masters.` or `nodes.`
if strings.HasPrefix(name, "masters.") {
return true
}
if strings.HasPrefix(name, "nodes.") {
return true
}
glog.Infof("unknown role name=%q, path=%q; assuming not managed", name, path)
return false
}
func (iamRoles) MarkAndSweep(sess *session.Session, acct string, region string, set *awsResourceSet) error {
svc := iam.New(sess, &aws.Config{Region: aws.String(region)})
var toDelete []*iamRole // Paged call, defer deletion until we have the whole list.
if err := svc.ListRolesPages(&iam.ListRolesInput{}, func(page *iam.ListRolesOutput, _ bool) bool {
for _, r := range page.Roles {
if !roleIsManaged(r) {
continue
}
l := &iamRole{arn: aws.StringValue(r.Arn), roleID: aws.StringValue(r.RoleId), roleName: aws.StringValue(r.RoleName)}
if set.Mark(l) {
glog.Warningf("%s: deleting %T: %v", l.ARN(), r, r)
toDelete = append(toDelete, l)
}
}
return true
}); err != nil {
return err
}
for _, r := range toDelete {
if err := r.delete(svc); err != nil {
glog.Warningf("%v: delete failed: %v", r.ARN(), err)
}
}
return nil
}
type iamRole struct {
arn string
roleID string
roleName string
}
func (r iamRole) ARN() string {
return r.arn
}
func (r iamRole) ResourceKey() string {
return r.roleID + "::" + r.ARN()
}
func (r iamRole) delete(svc *iam.IAM) error {
roleName := r.roleName
var policyNames []string
{
request := &iam.ListRolePoliciesInput{
RoleName: aws.String(roleName),
}
err := svc.ListRolePoliciesPages(request, func(page *iam.ListRolePoliciesOutput, lastPage bool) bool {
for _, policyName := range page.PolicyNames {
policyNames = append(policyNames, aws.StringValue(policyName))
}
return true
})
if err != nil {
return fmt.Errorf("error listing IAM role policies for %q: %v", roleName, err)
}
}
for _, policyName := range policyNames {
glog.V(2).Infof("Deleting IAM role policy %q %q", roleName, policyName)
request := &iam.DeleteRolePolicyInput{
RoleName: aws.String(roleName),
PolicyName: aws.String(policyName),
}
_, err := svc.DeleteRolePolicy(request)
if err != nil {
return fmt.Errorf("error deleting IAM role policy %q %q: %v", roleName, policyName, err)
}
}
{
glog.V(2).Infof("Deleting IAM role %q", roleName)
request := &iam.DeleteRoleInput{
RoleName: aws.String(roleName),
}
_, err := svc.DeleteRole(request)
if err != nil {
return fmt.Errorf("error deleting IAM role %q: %v", roleName, err)
}
}
return nil
}
// IAM Instance Profiles
type iamInstanceProfiles struct{}
func (iamInstanceProfiles) MarkAndSweep(sess *session.Session, acct string, region string, set *awsResourceSet) error {
svc := iam.New(sess, &aws.Config{Region: aws.String(region)})
var toDelete []*iamInstanceProfile // Paged call, defer deletion until we have the whole list.
if err := svc.ListInstanceProfilesPages(&iam.ListInstanceProfilesInput{}, func(page *iam.ListInstanceProfilesOutput, _ bool) bool {
for _, p := range page.InstanceProfiles {
// We treat an instance profile as managed if all its roles are
managed := true
if len(p.Roles) == 0 {
// Just in case...
managed = false
}
for _, r := range p.Roles {
if !roleIsManaged(r) {
managed = false
}
}
if !managed {
glog.Infof("ignoring unmanaged profile %s", aws.StringValue(p.Arn))
continue
}
o := &iamInstanceProfile{profile: p}
if set.Mark(o) {
glog.Warningf("%s: deleting %T: %v", o.ARN(), o, o)
toDelete = append(toDelete, o)