forked from hashicorp/terraform
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resource_aws_redshift_security_group.go
400 lines (320 loc) · 10.5 KB
/
resource_aws_redshift_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
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
package aws
import (
"bytes"
"fmt"
"log"
"regexp"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/redshift"
"github.com/hashicorp/go-multierror"
"github.com/hashicorp/terraform/helper/hashcode"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
)
func resourceAwsRedshiftSecurityGroup() *schema.Resource {
return &schema.Resource{
Create: resourceAwsRedshiftSecurityGroupCreate,
Read: resourceAwsRedshiftSecurityGroupRead,
Update: resourceAwsRedshiftSecurityGroupUpdate,
Delete: resourceAwsRedshiftSecurityGroupDelete,
Importer: &schema.ResourceImporter{
State: resourceAwsRedshiftClusterImport,
},
Schema: map[string]*schema.Schema{
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validateRedshiftSecurityGroupName,
},
"description": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "Managed by Terraform",
},
"ingress": &schema.Schema{
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cidr": &schema.Schema{
Type: schema.TypeString,
Optional: true,
},
"security_group_name": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"security_group_owner_id": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
},
},
},
Set: resourceAwsRedshiftSecurityGroupIngressHash,
},
},
}
}
func resourceAwsRedshiftSecurityGroupCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).redshiftconn
var err error
var errs []error
name := d.Get("name").(string)
desc := d.Get("description").(string)
sgInput := &redshift.CreateClusterSecurityGroupInput{
ClusterSecurityGroupName: aws.String(name),
Description: aws.String(desc),
}
log.Printf("[DEBUG] Redshift security group create: name: %s, description: %s", name, desc)
_, err = conn.CreateClusterSecurityGroup(sgInput)
if err != nil {
return fmt.Errorf("Error creating RedshiftSecurityGroup: %s", err)
}
d.SetId(d.Get("name").(string))
log.Printf("[INFO] Redshift Security Group ID: %s", d.Id())
sg, err := resourceAwsRedshiftSecurityGroupRetrieve(d, meta)
if err != nil {
return err
}
ingresses := d.Get("ingress").(*schema.Set)
for _, ing := range ingresses.List() {
err := resourceAwsRedshiftSecurityGroupAuthorizeRule(ing, *sg.ClusterSecurityGroupName, conn)
if err != nil {
errs = append(errs, err)
}
}
if len(errs) > 0 {
return &multierror.Error{Errors: errs}
}
log.Println("[INFO] Waiting for Redshift Security Group Ingress Authorizations to be authorized")
stateConf := &resource.StateChangeConf{
Pending: []string{"authorizing"},
Target: []string{"authorized"},
Refresh: resourceAwsRedshiftSecurityGroupStateRefreshFunc(d, meta),
Timeout: 10 * time.Minute,
}
_, err = stateConf.WaitForState()
if err != nil {
return err
}
return resourceAwsRedshiftSecurityGroupRead(d, meta)
}
func resourceAwsRedshiftSecurityGroupRead(d *schema.ResourceData, meta interface{}) error {
sg, err := resourceAwsRedshiftSecurityGroupRetrieve(d, meta)
if err != nil {
return err
}
rules := &schema.Set{
F: resourceAwsRedshiftSecurityGroupIngressHash,
}
for _, v := range sg.IPRanges {
rule := map[string]interface{}{"cidr": *v.CIDRIP}
rules.Add(rule)
}
for _, g := range sg.EC2SecurityGroups {
rule := map[string]interface{}{
"security_group_name": *g.EC2SecurityGroupName,
"security_group_owner_id": *g.EC2SecurityGroupOwnerId,
}
rules.Add(rule)
}
d.Set("ingress", rules)
d.Set("name", *sg.ClusterSecurityGroupName)
d.Set("description", *sg.Description)
return nil
}
func resourceAwsRedshiftSecurityGroupUpdate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).redshiftconn
if d.HasChange("ingress") {
o, n := d.GetChange("ingress")
if o == nil {
o = new(schema.Set)
}
if n == nil {
n = new(schema.Set)
}
os := o.(*schema.Set)
ns := n.(*schema.Set)
removeIngressRules, err := expandRedshiftSGRevokeIngress(os.Difference(ns).List())
if err != nil {
return err
}
if len(removeIngressRules) > 0 {
for _, r := range removeIngressRules {
r.ClusterSecurityGroupName = aws.String(d.Id())
_, err := conn.RevokeClusterSecurityGroupIngress(&r)
if err != nil {
return err
}
}
}
addIngressRules, err := expandRedshiftSGAuthorizeIngress(ns.Difference(os).List())
if err != nil {
return err
}
if len(addIngressRules) > 0 {
for _, r := range addIngressRules {
r.ClusterSecurityGroupName = aws.String(d.Id())
_, err := conn.AuthorizeClusterSecurityGroupIngress(&r)
if err != nil {
return err
}
}
}
}
return resourceAwsRedshiftSecurityGroupRead(d, meta)
}
func resourceAwsRedshiftSecurityGroupDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).redshiftconn
log.Printf("[DEBUG] Redshift Security Group destroy: %v", d.Id())
opts := redshift.DeleteClusterSecurityGroupInput{
ClusterSecurityGroupName: aws.String(d.Id()),
}
log.Printf("[DEBUG] Redshift Security Group destroy configuration: %v", opts)
_, err := conn.DeleteClusterSecurityGroup(&opts)
if err != nil {
newerr, ok := err.(awserr.Error)
if ok && newerr.Code() == "InvalidRedshiftSecurityGroup.NotFound" {
return nil
}
return err
}
return nil
}
func resourceAwsRedshiftSecurityGroupRetrieve(d *schema.ResourceData, meta interface{}) (*redshift.ClusterSecurityGroup, error) {
conn := meta.(*AWSClient).redshiftconn
opts := redshift.DescribeClusterSecurityGroupsInput{
ClusterSecurityGroupName: aws.String(d.Id()),
}
log.Printf("[DEBUG] Redshift Security Group describe configuration: %#v", opts)
resp, err := conn.DescribeClusterSecurityGroups(&opts)
if err != nil {
return nil, fmt.Errorf("Error retrieving Redshift Security Groups: %s", err)
}
if len(resp.ClusterSecurityGroups) != 1 ||
*resp.ClusterSecurityGroups[0].ClusterSecurityGroupName != d.Id() {
return nil, fmt.Errorf("Unable to find Redshift Security Group: %#v", resp.ClusterSecurityGroups)
}
return resp.ClusterSecurityGroups[0], nil
}
func validateRedshiftSecurityGroupName(v interface{}, k string) (ws []string, errors []error) {
value := v.(string)
if value == "default" {
errors = append(errors, fmt.Errorf("the Redshift Security Group name cannot be %q", value))
}
if !regexp.MustCompile(`^[0-9a-z-]+$`).MatchString(value) {
errors = append(errors, fmt.Errorf(
"only lowercase alphanumeric characters and hyphens allowed in %q: %q",
k, value))
}
if len(value) > 255 {
errors = append(errors, fmt.Errorf(
"%q cannot be longer than 32 characters: %q", k, value))
}
return
}
func resourceAwsRedshiftSecurityGroupIngressHash(v interface{}) int {
var buf bytes.Buffer
m := v.(map[string]interface{})
if v, ok := m["cidr"]; ok {
buf.WriteString(fmt.Sprintf("%s-", v.(string)))
}
if v, ok := m["security_group_name"]; ok {
buf.WriteString(fmt.Sprintf("%s-", v.(string)))
}
if v, ok := m["security_group_owner_id"]; ok {
buf.WriteString(fmt.Sprintf("%s-", v.(string)))
}
return hashcode.String(buf.String())
}
func resourceAwsRedshiftSecurityGroupAuthorizeRule(ingress interface{}, redshiftSecurityGroupName string, conn *redshift.Redshift) error {
ing := ingress.(map[string]interface{})
opts := redshift.AuthorizeClusterSecurityGroupIngressInput{
ClusterSecurityGroupName: aws.String(redshiftSecurityGroupName),
}
if attr, ok := ing["cidr"]; ok && attr != "" {
opts.CIDRIP = aws.String(attr.(string))
}
if attr, ok := ing["security_group_name"]; ok && attr != "" {
opts.EC2SecurityGroupName = aws.String(attr.(string))
}
if attr, ok := ing["security_group_owner_id"]; ok && attr != "" {
opts.EC2SecurityGroupOwnerId = aws.String(attr.(string))
}
log.Printf("[DEBUG] Authorize ingress rule configuration: %#v", opts)
_, err := conn.AuthorizeClusterSecurityGroupIngress(&opts)
if err != nil {
return fmt.Errorf("Error authorizing security group ingress: %s", err)
}
return nil
}
func resourceAwsRedshiftSecurityGroupStateRefreshFunc(
d *schema.ResourceData, meta interface{}) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
v, err := resourceAwsRedshiftSecurityGroupRetrieve(d, meta)
if err != nil {
log.Printf("Error on retrieving Redshift Security Group when waiting: %s", err)
return nil, "", err
}
statuses := make([]string, 0, len(v.EC2SecurityGroups)+len(v.IPRanges))
for _, ec2g := range v.EC2SecurityGroups {
statuses = append(statuses, *ec2g.Status)
}
for _, ips := range v.IPRanges {
statuses = append(statuses, *ips.Status)
}
for _, stat := range statuses {
// Not done
if stat != "authorized" {
return nil, "authorizing", nil
}
}
return v, "authorized", nil
}
}
func expandRedshiftSGAuthorizeIngress(configured []interface{}) ([]redshift.AuthorizeClusterSecurityGroupIngressInput, error) {
var ingress []redshift.AuthorizeClusterSecurityGroupIngressInput
// Loop over our configured parameters and create
// an array of aws-sdk-go compatible objects
for _, pRaw := range configured {
data := pRaw.(map[string]interface{})
i := redshift.AuthorizeClusterSecurityGroupIngressInput{}
if v, ok := data["cidr"]; ok {
i.CIDRIP = aws.String(v.(string))
}
if v, ok := data["security_group_name"]; ok {
i.EC2SecurityGroupName = aws.String(v.(string))
}
if v, ok := data["security_group_owner_id"]; ok {
i.EC2SecurityGroupOwnerId = aws.String(v.(string))
}
ingress = append(ingress, i)
}
return ingress, nil
}
func expandRedshiftSGRevokeIngress(configured []interface{}) ([]redshift.RevokeClusterSecurityGroupIngressInput, error) {
var ingress []redshift.RevokeClusterSecurityGroupIngressInput
// Loop over our configured parameters and create
// an array of aws-sdk-go compatible objects
for _, pRaw := range configured {
data := pRaw.(map[string]interface{})
i := redshift.RevokeClusterSecurityGroupIngressInput{}
if v, ok := data["cidr"]; ok {
i.CIDRIP = aws.String(v.(string))
}
if v, ok := data["security_group_name"]; ok {
i.EC2SecurityGroupName = aws.String(v.(string))
}
if v, ok := data["security_group_owner_id"]; ok {
i.EC2SecurityGroupOwnerId = aws.String(v.(string))
}
ingress = append(ingress, i)
}
return ingress, nil
}