forked from isovalent/aws-delete-vpc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
186 lines (164 loc) · 4.85 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
package main
// FIXME Delete CloudFormation resources?
// FIXME Delete CloudWatch log groups?
import (
"context"
"errors"
"flag"
"fmt"
"os"
"strings"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
autoscalingtypes "github.com/aws/aws-sdk-go-v2/service/autoscaling/types"
ekstypes "github.com/aws/aws-sdk-go-v2/service/eks/types"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
const (
instanceTerminatedWaiterMaxDuration = 5 * time.Minute
)
func main() {
if err := run(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func run() error {
excludeResources := newStringSet()
includeResources := newStringSet(
"AutoScalingGroups",
"Clusters",
"ElasticIps",
"InternetGateways",
"LoadBalancers",
"NatGateways",
"NetworkAcls",
"NetworkInterfaces",
"Reservations",
"RouteTables",
"SecurityGroups",
"Subnets",
"VpcPeeringConnections",
"VpnGateways",
)
autoScalingTagKey := flag.String("autoscaling-tag-key", "", "AutoScaling tag key")
autoScalingTagValue := flag.String("autoscaling-tag-value", "owned", `AutoScaling tag value (default "owner")`)
clusterName := flag.String("cluster-name", "", "cluster name")
flag.Var(excludeResources, "exclude", "resource types to exclude (default none)")
flag.Var(includeResources, "include", "resource types to include (default all)")
retryInterval := flag.Duration("retry-interval", 1*time.Minute, "Re-try interval")
tries := flag.Int("tries", 3, "tries")
vpcId := flag.String("vpc-id", "", "VPC ID")
flag.Parse()
ctx := context.Background()
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
config, err := config.LoadDefaultConfig(ctx)
if err != nil {
return err
}
clients := newClientsFromConfig(config)
var cluster *ekstypes.Cluster
if *clusterName != "" {
cluster, err = listCluster(ctx, clients.eks, *clusterName)
// if err != nil { V
// var operationErr *smithy.OperationError
// if !errors.As(err, &operationErr) || operationErr.
// }
// Ignore ResourceNotFoundExceptions in case the cluster has already been deleted.
var resourceNotFoundExceptionErr *ekstypes.ResourceNotFoundException
if err != nil && !errors.As(err, &resourceNotFoundExceptionErr) {
return err
}
// Retrieve the VPC ID from the cluster if it is not already known.
if *vpcId == "" && cluster != nil && cluster.ResourcesVpcConfig != nil && cluster.ResourcesVpcConfig.VpcId != nil {
vpcId = cluster.ResourcesVpcConfig.VpcId
}
// Retrieve the VPC ID by name if it is not already known. This assumes
// that the VPC has a tag with key Name and value equal to the cluster
// name.
if *vpcId == "" {
switch vpcs, err := findVpcsByName(ctx, clients.ec2, *clusterName); {
case err != nil:
return err
case len(vpcs) == 0:
// Do nothing.
case len(vpcs) == 1:
vpcId = vpcs[0].VpcId
default:
return fmt.Errorf("multiple VPCs with cluster name %q: %s", *clusterName, strings.Join(vpcIds(vpcs), ", "))
}
}
}
resources := includeResources.subtract(excludeResources)
// By default, use the tag k8s.io/cluster/$CLUSTER_NAME=owned to identify
// AutoScalingGroups.
//
// FIXME Find an alternative way to detect AutoScalingGroups associated with
// the VPC.
if *autoScalingTagKey == "" && *autoScalingTagValue == "owned" && *clusterName != "" {
autoScalingTagKey = aws.String("k8s.io/cluster/" + *clusterName)
}
var autoScalingFilters []autoscalingtypes.Filter
if *autoScalingTagKey != "" && *autoScalingTagValue != "" {
autoScalingFilters = []autoscalingtypes.Filter{
{
Name: aws.String("tag-key"),
Values: []string{*autoScalingTagKey},
},
{
Name: aws.String("tag-value"),
Values: []string{*autoScalingTagValue},
},
}
}
if *vpcId == "" {
return errors.New("VPC ID not set")
}
deleted, err := tryDeleteVpc(ctx, clients.ec2, *vpcId)
log.Err(err).
Bool("deleted", deleted).
Str("vpcId", *vpcId).
Msg("tryDeleteVpc")
switch {
case err != nil:
return err
case deleted:
if resources.contains("Clusters") {
if cluster != nil {
if err := deleteCluster(ctx, clients.eks, cluster); err != nil {
return err
}
}
}
return nil
}
for try := 0; try < *tries; try++ {
if try != 0 {
log.Info().
Dur("duration", *retryInterval).
Msg("Sleep")
time.Sleep(*retryInterval)
}
err := deleteVpcDependencies(ctx, clients, *clusterName, *vpcId, resources, autoScalingFilters)
log.Err(err).
Str("vpcId", *vpcId).
Msg("deleteVpcDependencies")
deleted, err := tryDeleteVpc(ctx, clients.ec2, *vpcId)
log.Err(err).
Bool("deleted", deleted).
Str("vpcId", *vpcId).
Msg("tryDeleteVpc")
if deleted {
if resources.contains("Clusters") && cluster != nil {
if err := deleteCluster(ctx, clients.eks, cluster); err != nil {
// retry is required if cluster has node-groups
continue
}
}
return nil
}
}
return errors.New("failed")
}