forked from hashicorp/terraform
/
resource_aws_security_group_rule.go
343 lines (281 loc) · 8.06 KB
/
resource_aws_security_group_rule.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
package aws
import (
"bytes"
"fmt"
"log"
"sort"
"strings"
"github.com/awslabs/aws-sdk-go/aws"
"github.com/awslabs/aws-sdk-go/aws/awserr"
"github.com/awslabs/aws-sdk-go/service/ec2"
"github.com/hashicorp/terraform/helper/hashcode"
"github.com/hashicorp/terraform/helper/schema"
)
func resourceAwsSecurityGroupRule() *schema.Resource {
return &schema.Resource{
Create: resourceAwsSecurityGroupRuleCreate,
Read: resourceAwsSecurityGroupRuleRead,
Delete: resourceAwsSecurityGroupRuleDelete,
Schema: map[string]*schema.Schema{
"type": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "Type of rule, ingress (inbound) or egress (outbound).",
},
"from_port": &schema.Schema{
Type: schema.TypeInt,
Required: true,
ForceNew: true,
},
"to_port": &schema.Schema{
Type: schema.TypeInt,
Required: true,
ForceNew: true,
},
"protocol": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"cidr_blocks": &schema.Schema{
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"security_group_id": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"source_security_group_id": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
"self": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
Default: false,
ForceNew: true,
},
},
}
}
func resourceAwsSecurityGroupRuleCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn
sg_id := d.Get("security_group_id").(string)
sg, err := findResourceSecurityGroup(conn, sg_id)
if err != nil {
return fmt.Errorf("sorry")
}
perm := expandIPPerm(d, sg)
ruleType := d.Get("type").(string)
switch ruleType {
case "ingress":
log.Printf("[DEBUG] Authorizing security group %s %s rule: %#v",
sg_id, "Ingress", perm)
req := &ec2.AuthorizeSecurityGroupIngressInput{
GroupID: sg.GroupID,
IPPermissions: []*ec2.IPPermission{perm},
}
if sg.VPCID == nil || *sg.VPCID == "" {
req.GroupID = nil
req.GroupName = sg.GroupName
}
_, err := conn.AuthorizeSecurityGroupIngress(req)
if err != nil {
return fmt.Errorf(
"Error authorizing security group %s rules: %s",
"rules", err)
}
case "egress":
log.Printf("[DEBUG] Authorizing security group %s %s rule: %#v",
sg_id, "Egress", perm)
req := &ec2.AuthorizeSecurityGroupEgressInput{
GroupID: sg.GroupID,
IPPermissions: []*ec2.IPPermission{perm},
}
_, err = conn.AuthorizeSecurityGroupEgress(req)
if err != nil {
return fmt.Errorf(
"Error authorizing security group %s rules: %s",
"rules", err)
}
default:
return fmt.Errorf("Security Group Rule must be type 'ingress' or type 'egress'")
}
d.SetId(ipPermissionIDHash(ruleType, perm))
return resourceAwsSecurityGroupRuleRead(d, meta)
}
func resourceAwsSecurityGroupRuleRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn
sg_id := d.Get("security_group_id").(string)
sg, err := findResourceSecurityGroup(conn, sg_id)
if err != nil {
d.SetId("")
}
var rule *ec2.IPPermission
ruleType := d.Get("type").(string)
var rl []*ec2.IPPermission
switch ruleType {
case "ingress":
rl = sg.IPPermissions
default:
rl = sg.IPPermissionsEgress
}
for _, r := range rl {
if d.Id() == ipPermissionIDHash(ruleType, r) {
rule = r
}
}
if rule == nil {
log.Printf("[DEBUG] Unable to find matching %s Security Group Rule for Group %s",
ruleType, sg_id)
d.SetId("")
return nil
}
d.Set("from_port", rule.FromPort)
d.Set("to_port", rule.ToPort)
d.Set("protocol", rule.IPProtocol)
d.Set("type", ruleType)
var cb []string
for _, c := range rule.IPRanges {
cb = append(cb, *c.CIDRIP)
}
d.Set("cidr_blocks", cb)
if len(rule.UserIDGroupPairs) > 0 {
s := rule.UserIDGroupPairs[0]
d.Set("source_security_group_id", *s.GroupID)
}
return nil
}
func resourceAwsSecurityGroupRuleDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).ec2conn
sg_id := d.Get("security_group_id").(string)
sg, err := findResourceSecurityGroup(conn, sg_id)
if err != nil {
return fmt.Errorf("sorry")
}
perm := expandIPPerm(d, sg)
ruleType := d.Get("type").(string)
switch ruleType {
case "ingress":
log.Printf("[DEBUG] Revoking security group %#v %s rule: %#v",
sg_id, "ingress", perm)
req := &ec2.RevokeSecurityGroupIngressInput{
GroupID: sg.GroupID,
IPPermissions: []*ec2.IPPermission{perm},
}
_, err = conn.RevokeSecurityGroupIngress(req)
if err != nil {
return fmt.Errorf(
"Error revoking security group %s rules: %s",
sg_id, err)
}
case "egress":
log.Printf("[DEBUG] Revoking security group %#v %s rule: %#v",
sg_id, "egress", perm)
req := &ec2.RevokeSecurityGroupEgressInput{
GroupID: sg.GroupID,
IPPermissions: []*ec2.IPPermission{perm},
}
_, err = conn.RevokeSecurityGroupEgress(req)
if err != nil {
return fmt.Errorf(
"Error revoking security group %s rules: %s",
sg_id, err)
}
}
d.SetId("")
return nil
}
func findResourceSecurityGroup(conn *ec2.EC2, id string) (*ec2.SecurityGroup, error) {
req := &ec2.DescribeSecurityGroupsInput{
GroupIDs: []*string{aws.String(id)},
}
resp, err := conn.DescribeSecurityGroups(req)
if err != nil {
if ec2err, ok := err.(awserr.Error); ok {
if ec2err.Code() == "InvalidSecurityGroupID.NotFound" ||
ec2err.Code() == "InvalidGroup.NotFound" {
resp = nil
err = nil
}
}
if err != nil {
log.Printf("Error on findResourceSecurityGroup: %s", err)
return nil, err
}
}
return resp.SecurityGroups[0], nil
}
func ipPermissionIDHash(ruleType string, ip *ec2.IPPermission) string {
var buf bytes.Buffer
// for egress rules, an TCP rule of -1 is automatically added, in which case
// the to and from ports will be nil. We don't record this rule locally.
if ip.IPProtocol != nil && *ip.IPProtocol != "-1" {
buf.WriteString(fmt.Sprintf("%d-", *ip.FromPort))
buf.WriteString(fmt.Sprintf("%d-", *ip.ToPort))
buf.WriteString(fmt.Sprintf("%s-", *ip.IPProtocol))
}
buf.WriteString(fmt.Sprintf("%s-", ruleType))
// We need to make sure to sort the strings below so that we always
// generate the same hash code no matter what is in the set.
if len(ip.IPRanges) > 0 {
s := make([]string, len(ip.IPRanges))
for i, r := range ip.IPRanges {
s[i] = *r.CIDRIP
}
sort.Strings(s)
for _, v := range s {
buf.WriteString(fmt.Sprintf("%s-", v))
}
}
return fmt.Sprintf("sg-%d", hashcode.String(buf.String()))
}
func expandIPPerm(d *schema.ResourceData, sg *ec2.SecurityGroup) *ec2.IPPermission {
var perm ec2.IPPermission
perm.FromPort = aws.Long(int64(d.Get("from_port").(int)))
perm.ToPort = aws.Long(int64(d.Get("to_port").(int)))
perm.IPProtocol = aws.String(d.Get("protocol").(string))
var groups []string
if raw, ok := d.GetOk("source_security_group_id"); ok {
groups = append(groups, raw.(string))
}
if v, ok := d.GetOk("self"); ok && v.(bool) {
if sg.VPCID != nil && *sg.VPCID != "" {
groups = append(groups, *sg.GroupID)
} else {
groups = append(groups, *sg.GroupName)
}
}
if len(groups) > 0 {
perm.UserIDGroupPairs = make([]*ec2.UserIDGroupPair, len(groups))
for i, name := range groups {
ownerId, id := "", name
if items := strings.Split(id, "/"); len(items) > 1 {
ownerId, id = items[0], items[1]
}
perm.UserIDGroupPairs[i] = &ec2.UserIDGroupPair{
GroupID: aws.String(id),
UserID: aws.String(ownerId),
}
if sg.VPCID == nil || *sg.VPCID == "" {
perm.UserIDGroupPairs[i].GroupID = nil
perm.UserIDGroupPairs[i].GroupName = aws.String(id)
perm.UserIDGroupPairs[i].UserID = nil
}
}
}
if raw, ok := d.GetOk("cidr_blocks"); ok {
list := raw.([]interface{})
perm.IPRanges = make([]*ec2.IPRange, len(list))
for i, v := range list {
perm.IPRanges[i] = &ec2.IPRange{CIDRIP: aws.String(v.(string))}
}
}
return &perm
}