forked from rebuy-de/aws-nuke
/
ec2-security-groups.go
92 lines (73 loc) · 1.81 KB
/
ec2-security-groups.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
package resources
import (
"fmt"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/rebuy-de/aws-nuke/pkg/types"
)
type EC2SecurityGroup struct {
svc *ec2.EC2
id *string
name *string
ingress []*ec2.IpPermission
egress []*ec2.IpPermission
}
func init() {
register("EC2SecurityGroup", ListEC2SecurityGroups)
}
func ListEC2SecurityGroups(sess *session.Session) ([]Resource, error) {
svc := ec2.New(sess)
params := &ec2.DescribeSecurityGroupsInput{}
resp, err := svc.DescribeSecurityGroups(params)
if err != nil {
return nil, err
}
resources := make([]Resource, 0)
for _, group := range resp.SecurityGroups {
resources = append(resources, &EC2SecurityGroup{
svc: svc,
id: group.GroupId,
name: group.GroupName,
ingress: group.IpPermissions,
egress: group.IpPermissionsEgress,
})
}
return resources, nil
}
func (sg *EC2SecurityGroup) Filter() error {
if *sg.name == "default" {
return fmt.Errorf("cannot delete group 'default'")
}
return nil
}
func (sg *EC2SecurityGroup) Remove() error {
if len(sg.egress) > 0 {
egressParams := &ec2.RevokeSecurityGroupEgressInput{
GroupId: sg.id,
IpPermissions: sg.egress,
}
_, _ = sg.svc.RevokeSecurityGroupEgress(egressParams)
}
if len(sg.ingress) > 0 {
ingressParams := &ec2.RevokeSecurityGroupIngressInput{
GroupId: sg.id,
IpPermissions: sg.ingress,
}
_, _ = sg.svc.RevokeSecurityGroupIngress(ingressParams)
}
params := &ec2.DeleteSecurityGroupInput{
GroupId: sg.id,
}
_, err := sg.svc.DeleteSecurityGroup(params)
if err != nil {
return err
}
return nil
}
func (sg *EC2SecurityGroup) Properties() types.Properties {
return types.NewProperties().
Set("Name", sg.name)
}
func (sg *EC2SecurityGroup) String() string {
return *sg.id
}