This repository has been archived by the owner on Sep 22, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 32
/
security_group.go
105 lines (86 loc) · 2.48 KB
/
security_group.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
package sg
import (
"fmt"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/coinbase/odin/aws"
"github.com/coinbase/step/utils/to"
)
// SecurityGroup struct
type SecurityGroup struct {
NameTag *string
ProjectNameTag *string
ConfigNameTag *string
ServiceNameTag *string
GroupID *string
}
// ProjectName returns tag
func (s *SecurityGroup) ProjectName() *string {
return s.ProjectNameTag
}
// ConfigName returns tag
func (s *SecurityGroup) ConfigName() *string {
return s.ConfigNameTag
}
// ServiceName returns tag
func (s *SecurityGroup) ServiceName() *string {
return s.ServiceNameTag
}
// Name returns tag
func (s *SecurityGroup) Name() *string {
return s.NameTag
}
// AllowedService returns which service is allowed to attach to it
func (s *SecurityGroup) AllowedService() *string {
return to.Strp(fmt.Sprintf("%s::%s::%s", *s.ProjectName(), *s.ConfigName(), *s.ServiceName()))
}
// Find returns the security groups with tags
func Find(ec2Client aws.EC2API, nameTags []*string) ([]*SecurityGroup, error) {
output, err := ec2Client.DescribeSecurityGroups(&ec2.DescribeSecurityGroupsInput{
Filters: []*ec2.Filter{
&ec2.Filter{
Name: to.Strp("tag:Name"),
Values: nameTags,
}}})
if err != nil {
return nil, err
}
sgs := newSGs(output.SecurityGroups)
// Need to validate that each Name tag matches Exactly one Security Group
for _, nameTag := range nameTags {
matches := 0
for _, sg := range sgs {
if sg.NameTag == nil {
return nil, fmt.Errorf("SecurityGroup '%v': incorrect Name Tag", *nameTag)
}
if *sg.NameTag == *nameTag {
matches += 1
}
}
switch matches {
case 0:
return nil, fmt.Errorf("SecurityGroup '%v': not found", *nameTag)
case 1:
// Do nothing
default:
return nil, fmt.Errorf("SecurityGroup '%v': too many found", *nameTag)
}
}
if len(sgs) != len(nameTags) {
// Last assurance that no additional security groups were found
return nil, fmt.Errorf("SecurityGroup: found %v required %v", len(sgs), len(nameTags))
}
return sgs, nil
}
func newSGs(output []*ec2.SecurityGroup) []*SecurityGroup {
sgs := []*SecurityGroup{}
for _, sg := range output {
sgs = append(sgs, &SecurityGroup{
GroupID: sg.GroupId,
NameTag: aws.FetchEc2Tag(sg.Tags, to.Strp("Name")),
ProjectNameTag: aws.FetchEc2Tag(sg.Tags, to.Strp("ProjectName")),
ConfigNameTag: aws.FetchEc2Tag(sg.Tags, to.Strp("ConfigName")),
ServiceNameTag: aws.FetchEc2Tag(sg.Tags, to.Strp("ServiceName")),
})
}
return sgs
}