forked from isovalent/aws-delete-vpc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
securitygroup.go
85 lines (78 loc) · 2.39 KB
/
securitygroup.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
package main
import (
"context"
"github.com/aws/aws-sdk-go-v2/service/ec2"
"github.com/aws/aws-sdk-go-v2/service/ec2/types"
"github.com/rs/zerolog/log"
"go.uber.org/multierr"
)
func deleteSecurityGroups(ctx context.Context, client *ec2.Client, vpcId string, securityGroups []types.SecurityGroup) (errs error) {
for _, securityGroup := range securityGroups {
if securityGroup.GroupId == nil {
continue
}
if securityGroup.VpcId == nil || *securityGroup.VpcId != vpcId {
continue
}
groupId := *securityGroup.GroupId
if securityGroupRules, err := listSecurityGroupRules(ctx, client, groupId); err != nil {
log.Err(err).
Str("groupId", groupId).
Msg("listSecurityGroupRules")
} else {
log.Info().
Str("groupId", groupId).
Strs("securityGroupRuleIds", securityGroupRuleIds(securityGroupRules)).
Msg("listSecurityGroupRules")
if len(securityGroupRules) > 0 {
err := deleteSecurityGroupRules(ctx, client, groupId, securityGroupRules)
log.Err(err).
Strs("securityGroupRuleIds", securityGroupRuleIds(securityGroupRules)).
Msg("deleteSecurityGroupRules")
if err != nil {
errs = multierr.Append(errs, err)
continue
}
}
}
_, err := client.DeleteSecurityGroup(ctx, &ec2.DeleteSecurityGroupInput{
GroupId: securityGroup.GroupId,
})
log.Err(err).
Str("GroupId", groupId).
Msg("DeleteSecurityGroup")
errs = multierr.Append(errs, err)
}
return
}
func listNonDefaultSecurityGroups(ctx context.Context, client *ec2.Client, vpcId string) ([]types.SecurityGroup, error) {
input := ec2.DescribeSecurityGroupsInput{
Filters: ec2VpcFilter(vpcId),
}
var securityGroups []types.SecurityGroup
for {
output, err := client.DescribeSecurityGroups(ctx, &input)
if err != nil {
return nil, err
}
for _, securityGroup := range output.SecurityGroups {
if securityGroup.GroupName != nil && *securityGroup.GroupName == "default" {
continue
}
securityGroups = append(securityGroups, securityGroup)
}
if output.NextToken == nil {
return securityGroups, nil
}
input.NextToken = output.NextToken
}
}
func securityGroupIds(securityGroups []types.SecurityGroup) []string {
securityGroupIds := make([]string, 0, len(securityGroups))
for _, securityGroup := range securityGroups {
if securityGroup.GroupId != nil {
securityGroupIds = append(securityGroupIds, *securityGroup.GroupId)
}
}
return securityGroupIds
}