forked from hashicorp/terraform
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resource_aws_rds_cluster.go
630 lines (522 loc) · 18 KB
/
resource_aws_rds_cluster.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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
package aws
import (
"fmt"
"log"
"regexp"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/rds"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
)
func resourceAwsRDSCluster() *schema.Resource {
return &schema.Resource{
Create: resourceAwsRDSClusterCreate,
Read: resourceAwsRDSClusterRead,
Update: resourceAwsRDSClusterUpdate,
Delete: resourceAwsRDSClusterDelete,
Importer: &schema.ResourceImporter{
State: resourceAwsRdsClusterImport,
},
Schema: map[string]*schema.Schema{
"availability_zones": &schema.Schema{
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
Optional: true,
ForceNew: true,
Computed: true,
Set: schema.HashString,
},
"cluster_identifier": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validateRdsId,
},
"cluster_members": &schema.Schema{
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
Optional: true,
Computed: true,
Set: schema.HashString,
},
"database_name": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"db_subnet_group_name": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
// TODO: remove parameter_group_name
// See https://github.com/hashicorp/terraform/issues/7046
// Likely need migration to remove from state
"parameter_group_name": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
Deprecated: "Use db_cluster_parameter_group_name instead. This attribute will be removed in a future version",
},
"db_cluster_parameter_group_name": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"endpoint": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"engine": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"storage_encrypted": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
Default: false,
ForceNew: true,
},
"final_snapshot_identifier": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ValidateFunc: func(v interface{}, k string) (ws []string, es []error) {
value := v.(string)
if !regexp.MustCompile(`^[0-9A-Za-z-]+$`).MatchString(value) {
es = append(es, fmt.Errorf(
"only alphanumeric characters and hyphens allowed in %q", k))
}
if regexp.MustCompile(`--`).MatchString(value) {
es = append(es, fmt.Errorf("%q cannot contain two consecutive hyphens", k))
}
if regexp.MustCompile(`-$`).MatchString(value) {
es = append(es, fmt.Errorf("%q cannot end in a hyphen", k))
}
return
},
},
"skip_final_snapshot": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"master_username": &schema.Schema{
Type: schema.TypeString,
Computed: true,
Optional: true,
ForceNew: true,
},
"master_password": &schema.Schema{
Type: schema.TypeString,
Optional: true,
},
"snapshot_identifier": &schema.Schema{
Type: schema.TypeString,
Computed: false,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"port": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
Computed: true,
},
// apply_immediately is used to determine when the update modifications
// take place.
// See http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Overview.DBInstance.Modifying.html
"apply_immediately": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"vpc_security_group_ids": &schema.Schema{
Type: schema.TypeSet,
Optional: true,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
},
"preferred_backup_window": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"preferred_maintenance_window": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
StateFunc: func(val interface{}) string {
if val == nil {
return ""
}
return strings.ToLower(val.(string))
},
},
"backup_retention_period": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
Default: 1,
ValidateFunc: func(v interface{}, k string) (ws []string, es []error) {
value := v.(int)
if value > 35 {
es = append(es, fmt.Errorf(
"backup retention period cannot be more than 35 days"))
}
return
},
},
"kms_key_id": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"tags": tagsSchema(),
},
}
}
func resourceAwsRdsClusterImport(
d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
// Neither skip_final_snapshot nor final_snapshot_identifier can be fetched
// from any API call, so we need to default skip_final_snapshot to true so
// that final_snapshot_identifier is not required
d.Set("skip_final_snapshot", true)
return []*schema.ResourceData{d}, nil
}
func resourceAwsRDSClusterCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).rdsconn
tags := tagsFromMapRDS(d.Get("tags").(map[string]interface{}))
if _, ok := d.GetOk("snapshot_identifier"); ok {
opts := rds.RestoreDBClusterFromSnapshotInput{
DBClusterIdentifier: aws.String(d.Get("cluster_identifier").(string)),
SnapshotIdentifier: aws.String(d.Get("snapshot_identifier").(string)),
Engine: aws.String("aurora"),
Tags: tags,
}
if attr := d.Get("availability_zones").(*schema.Set); attr.Len() > 0 {
opts.AvailabilityZones = expandStringList(attr.List())
}
if attr, ok := d.GetOk("db_subnet_group_name"); ok {
opts.DBSubnetGroupName = aws.String(attr.(string))
}
if attr, ok := d.GetOk("database_name"); ok {
opts.DatabaseName = aws.String(attr.(string))
}
if attr, ok := d.GetOk("option_group_name"); ok {
opts.OptionGroupName = aws.String(attr.(string))
}
if attr, ok := d.GetOk("port"); ok {
opts.Port = aws.Int64(int64(attr.(int)))
}
var sgUpdate bool
if attr := d.Get("vpc_security_group_ids").(*schema.Set); attr.Len() > 0 {
sgUpdate = true
opts.VpcSecurityGroupIds = expandStringList(attr.List())
}
log.Printf("[DEBUG] RDS Cluster restore from snapshot configuration: %s", opts)
_, err := conn.RestoreDBClusterFromSnapshot(&opts)
if err != nil {
return fmt.Errorf("Error creating RDS Cluster: %s", err)
}
if sgUpdate {
log.Printf("[INFO] RDS Cluster is restoring from snapshot with default security, but custom security should be set, will now update after snapshot is restored!")
d.SetId(d.Get("cluster_identifier").(string))
log.Printf("[INFO] RDS Cluster Instance ID: %s", d.Id())
log.Println("[INFO] Waiting for RDS Cluster to be available")
stateConf := &resource.StateChangeConf{
Pending: []string{"creating", "backing-up", "modifying"},
Target: []string{"available"},
Refresh: resourceAwsRDSClusterStateRefreshFunc(d, meta),
Timeout: 15 * time.Minute,
MinTimeout: 3 * time.Second,
Delay: 30 * time.Second, // Wait 30 secs before starting
}
// Wait, catching any errors
_, err := stateConf.WaitForState()
if err != nil {
return err
}
err = resourceAwsRDSClusterInstanceUpdate(d, meta)
if err != nil {
return err
}
}
} else {
if _, ok := d.GetOk("master_password"); !ok {
return fmt.Errorf(`provider.aws: aws_rds_cluster: %s: "master_password": required field is not set`, d.Get("name").(string))
}
if _, ok := d.GetOk("master_username"); !ok {
return fmt.Errorf(`provider.aws: aws_rds_cluster: %s: "master_username": required field is not set`, d.Get("name").(string))
}
createOpts := &rds.CreateDBClusterInput{
DBClusterIdentifier: aws.String(d.Get("cluster_identifier").(string)),
Engine: aws.String("aurora"),
MasterUserPassword: aws.String(d.Get("master_password").(string)),
MasterUsername: aws.String(d.Get("master_username").(string)),
StorageEncrypted: aws.Bool(d.Get("storage_encrypted").(bool)),
Tags: tags,
}
if v := d.Get("database_name"); v.(string) != "" {
createOpts.DatabaseName = aws.String(v.(string))
}
if attr, ok := d.GetOk("port"); ok {
createOpts.Port = aws.Int64(int64(attr.(int)))
}
if attr, ok := d.GetOk("db_subnet_group_name"); ok {
createOpts.DBSubnetGroupName = aws.String(attr.(string))
}
if attr, ok := d.GetOk("parameter_group_name"); ok {
createOpts.DBClusterParameterGroupName = aws.String(attr.(string))
}
if attr, ok := d.GetOk("db_cluster_parameter_group_name"); ok {
createOpts.DBClusterParameterGroupName = aws.String(attr.(string))
}
if attr := d.Get("vpc_security_group_ids").(*schema.Set); attr.Len() > 0 {
createOpts.VpcSecurityGroupIds = expandStringList(attr.List())
}
if attr := d.Get("availability_zones").(*schema.Set); attr.Len() > 0 {
createOpts.AvailabilityZones = expandStringList(attr.List())
}
if v, ok := d.GetOk("backup_retention_period"); ok {
createOpts.BackupRetentionPeriod = aws.Int64(int64(v.(int)))
}
if v, ok := d.GetOk("preferred_backup_window"); ok {
createOpts.PreferredBackupWindow = aws.String(v.(string))
}
if v, ok := d.GetOk("preferred_maintenance_window"); ok {
createOpts.PreferredMaintenanceWindow = aws.String(v.(string))
}
if attr, ok := d.GetOk("kms_key_id"); ok {
createOpts.KmsKeyId = aws.String(attr.(string))
}
log.Printf("[DEBUG] RDS Cluster create options: %s", createOpts)
resp, err := conn.CreateDBCluster(createOpts)
if err != nil {
log.Printf("[ERROR] Error creating RDS Cluster: %s", err)
return err
}
log.Printf("[DEBUG]: RDS Cluster create response: %s", resp)
}
d.SetId(d.Get("cluster_identifier").(string))
log.Printf("[INFO] RDS Cluster ID: %s", d.Id())
log.Println(
"[INFO] Waiting for RDS Cluster to be available")
stateConf := &resource.StateChangeConf{
Pending: []string{"creating", "backing-up", "modifying"},
Target: []string{"available"},
Refresh: resourceAwsRDSClusterStateRefreshFunc(d, meta),
Timeout: 40 * time.Minute,
MinTimeout: 3 * time.Second,
}
// Wait, catching any errors
_, err := stateConf.WaitForState()
if err != nil {
return fmt.Errorf("[WARN] Error waiting for RDS Cluster state to be \"available\": %s", err)
}
return resourceAwsRDSClusterRead(d, meta)
}
func resourceAwsRDSClusterRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).rdsconn
resp, err := conn.DescribeDBClusters(&rds.DescribeDBClustersInput{
DBClusterIdentifier: aws.String(d.Id()),
})
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
if "DBClusterNotFoundFault" == awsErr.Code() {
d.SetId("")
log.Printf("[DEBUG] RDS Cluster (%s) not found", d.Id())
return nil
}
}
log.Printf("[DEBUG] Error describing RDS Cluster (%s)", d.Id())
return err
}
var dbc *rds.DBCluster
for _, c := range resp.DBClusters {
if *c.DBClusterIdentifier == d.Id() {
dbc = c
}
}
if dbc == nil {
log.Printf("[WARN] RDS Cluster (%s) not found", d.Id())
d.SetId("")
return nil
}
if err := d.Set("availability_zones", aws.StringValueSlice(dbc.AvailabilityZones)); err != nil {
return fmt.Errorf("[DEBUG] Error saving AvailabilityZones to state for RDS Cluster (%s): %s", d.Id(), err)
}
// Only set the DatabaseName if it is not nil. There is a known API bug where
// RDS accepts a DatabaseName but does not return it, causing a perpetual
// diff.
// See https://github.com/hashicorp/terraform/issues/4671 for backstory
if dbc.DatabaseName != nil {
d.Set("database_name", dbc.DatabaseName)
}
d.Set("cluster_identifier", dbc.DBClusterIdentifier)
d.Set("db_subnet_group_name", dbc.DBSubnetGroup)
d.Set("parameter_group_name", dbc.DBClusterParameterGroup)
d.Set("db_cluster_parameter_group_name", dbc.DBClusterParameterGroup)
d.Set("endpoint", dbc.Endpoint)
d.Set("engine", dbc.Engine)
d.Set("master_username", dbc.MasterUsername)
d.Set("port", dbc.Port)
d.Set("storage_encrypted", dbc.StorageEncrypted)
d.Set("backup_retention_period", dbc.BackupRetentionPeriod)
d.Set("preferred_backup_window", dbc.PreferredBackupWindow)
d.Set("preferred_maintenance_window", dbc.PreferredMaintenanceWindow)
d.Set("kms_key_id", dbc.KmsKeyId)
var vpcg []string
for _, g := range dbc.VpcSecurityGroups {
vpcg = append(vpcg, *g.VpcSecurityGroupId)
}
if err := d.Set("vpc_security_group_ids", vpcg); err != nil {
return fmt.Errorf("[DEBUG] Error saving VPC Security Group IDs to state for RDS Cluster (%s): %s", d.Id(), err)
}
var cm []string
for _, m := range dbc.DBClusterMembers {
cm = append(cm, *m.DBInstanceIdentifier)
}
if err := d.Set("cluster_members", cm); err != nil {
return fmt.Errorf("[DEBUG] Error saving RDS Cluster Members to state for RDS Cluster (%s): %s", d.Id(), err)
}
// Fetch and save tags
arn, err := buildRDSClusterARN(d.Id(), meta.(*AWSClient).accountid, meta.(*AWSClient).region)
if err != nil {
log.Printf("[DEBUG] Error building ARN for RDS Cluster (%s), not setting Tags", *dbc.DBClusterIdentifier)
} else {
if err := saveTagsRDS(conn, d, arn); err != nil {
log.Printf("[WARN] Failed to save tags for RDS Cluster (%s): %s", *dbc.DBClusterIdentifier, err)
}
}
return nil
}
func resourceAwsRDSClusterUpdate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).rdsconn
requestUpdate := false
req := &rds.ModifyDBClusterInput{
ApplyImmediately: aws.Bool(d.Get("apply_immediately").(bool)),
DBClusterIdentifier: aws.String(d.Id()),
}
if d.HasChange("master_password") {
req.MasterUserPassword = aws.String(d.Get("master_password").(string))
requestUpdate = true
}
if d.HasChange("vpc_security_group_ids") {
if attr := d.Get("vpc_security_group_ids").(*schema.Set); attr.Len() > 0 {
req.VpcSecurityGroupIds = expandStringList(attr.List())
} else {
req.VpcSecurityGroupIds = []*string{}
}
requestUpdate = true
}
if d.HasChange("preferred_backup_window") {
req.PreferredBackupWindow = aws.String(d.Get("preferred_backup_window").(string))
requestUpdate = true
}
if d.HasChange("preferred_maintenance_window") {
req.PreferredMaintenanceWindow = aws.String(d.Get("preferred_maintenance_window").(string))
requestUpdate = true
}
if d.HasChange("backup_retention_period") {
req.BackupRetentionPeriod = aws.Int64(int64(d.Get("backup_retention_period").(int)))
requestUpdate = true
}
if d.HasChange("parameter_group_name") {
d.SetPartial("parameter_group_name")
req.DBClusterParameterGroupName = aws.String(d.Get("parameter_group_name").(string))
requestUpdate = true
}
if d.HasChange("db_cluster_parameter_group_name") {
d.SetPartial("db_cluster_parameter_group_name")
req.DBClusterParameterGroupName = aws.String(d.Get("db_cluster_parameter_group_name").(string))
requestUpdate = true
}
if requestUpdate {
_, err := conn.ModifyDBCluster(req)
if err != nil {
return fmt.Errorf("[WARN] Error modifying RDS Cluster (%s): %s", d.Id(), err)
}
}
if arn, err := buildRDSClusterARN(d.Id(), meta.(*AWSClient).accountid, meta.(*AWSClient).region); err == nil {
if err := setTagsRDS(conn, d, arn); err != nil {
return err
} else {
d.SetPartial("tags")
}
}
return resourceAwsRDSClusterRead(d, meta)
}
func resourceAwsRDSClusterDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).rdsconn
log.Printf("[DEBUG] Destroying RDS Cluster (%s)", d.Id())
deleteOpts := rds.DeleteDBClusterInput{
DBClusterIdentifier: aws.String(d.Id()),
}
skipFinalSnapshot := d.Get("skip_final_snapshot").(bool)
deleteOpts.SkipFinalSnapshot = aws.Bool(skipFinalSnapshot)
if skipFinalSnapshot == false {
if name, present := d.GetOk("final_snapshot_identifier"); present {
deleteOpts.FinalDBSnapshotIdentifier = aws.String(name.(string))
} else {
return fmt.Errorf("RDS Cluster FinalSnapshotIdentifier is required when a final snapshot is required")
}
}
log.Printf("[DEBUG] RDS Cluster delete options: %s", deleteOpts)
_, err := conn.DeleteDBCluster(&deleteOpts)
stateConf := &resource.StateChangeConf{
Pending: []string{"available", "deleting", "backing-up", "modifying"},
Target: []string{"destroyed"},
Refresh: resourceAwsRDSClusterStateRefreshFunc(d, meta),
Timeout: 15 * time.Minute,
MinTimeout: 3 * time.Second,
}
// Wait, catching any errors
_, err = stateConf.WaitForState()
if err != nil {
return fmt.Errorf("[WARN] Error deleting RDS Cluster (%s): %s", d.Id(), err)
}
return nil
}
func resourceAwsRDSClusterStateRefreshFunc(
d *schema.ResourceData, meta interface{}) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
conn := meta.(*AWSClient).rdsconn
resp, err := conn.DescribeDBClusters(&rds.DescribeDBClustersInput{
DBClusterIdentifier: aws.String(d.Id()),
})
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
if "DBClusterNotFoundFault" == awsErr.Code() {
return 42, "destroyed", nil
}
}
log.Printf("[WARN] Error on retrieving DB Cluster (%s) when waiting: %s", d.Id(), err)
return nil, "", err
}
var dbc *rds.DBCluster
for _, c := range resp.DBClusters {
if *c.DBClusterIdentifier == d.Id() {
dbc = c
}
}
if dbc == nil {
return 42, "destroyed", nil
}
if dbc.Status != nil {
log.Printf("[DEBUG] DB Cluster status (%s): %s", d.Id(), *dbc.Status)
}
return dbc, *dbc.Status, nil
}
}
func buildRDSClusterARN(identifier, accountid, region string) (string, error) {
if accountid == "" {
return "", fmt.Errorf("Unable to construct RDS Cluster ARN because of missing AWS Account ID")
}
arn := fmt.Sprintf("arn:aws:rds:%s:%s:cluster:%s", region, accountid, identifier)
return arn, nil
}