forked from hashicorp/terraform
-
Notifications
You must be signed in to change notification settings - Fork 2
/
resource_aws_rds_cluster_instance.go
374 lines (308 loc) · 9.93 KB
/
resource_aws_rds_cluster_instance.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
package aws
import (
"fmt"
"log"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/rds"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
)
func resourceAwsRDSClusterInstance() *schema.Resource {
return &schema.Resource{
Create: resourceAwsRDSClusterInstanceCreate,
Read: resourceAwsRDSClusterInstanceRead,
Update: resourceAwsRDSClusterInstanceUpdate,
Delete: resourceAwsRDSClusterInstanceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"identifier": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validateRdsId,
},
"db_subnet_group_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
"writer": {
Type: schema.TypeBool,
Computed: true,
},
"cluster_identifier": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"endpoint": {
Type: schema.TypeString,
Computed: true,
},
"port": {
Type: schema.TypeInt,
Computed: true,
},
"publicly_accessible": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"instance_class": {
Type: schema.TypeString,
Required: true,
},
"db_parameter_group_name": {
Type: schema.TypeString,
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": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"kms_key_id": {
Type: schema.TypeString,
Computed: true,
},
"storage_encrypted": {
Type: schema.TypeBool,
Computed: true,
},
"auto_minor_version_upgrade": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"monitoring_role_arn": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"monitoring_interval": {
Type: schema.TypeInt,
Optional: true,
Default: 0,
},
"promotion_tier": {
Type: schema.TypeInt,
Optional: true,
Default: 0,
},
"tags": tagsSchema(),
},
}
}
func resourceAwsRDSClusterInstanceCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).rdsconn
tags := tagsFromMapRDS(d.Get("tags").(map[string]interface{}))
createOpts := &rds.CreateDBInstanceInput{
DBInstanceClass: aws.String(d.Get("instance_class").(string)),
DBClusterIdentifier: aws.String(d.Get("cluster_identifier").(string)),
Engine: aws.String("aurora"),
PubliclyAccessible: aws.Bool(d.Get("publicly_accessible").(bool)),
PromotionTier: aws.Int64(int64(d.Get("promotion_tier").(int))),
AutoMinorVersionUpgrade: aws.Bool(d.Get("auto_minor_version_upgrade").(bool)),
Tags: tags,
}
if attr, ok := d.GetOk("db_parameter_group_name"); ok {
createOpts.DBParameterGroupName = aws.String(attr.(string))
}
if v := d.Get("identifier").(string); v != "" {
createOpts.DBInstanceIdentifier = aws.String(v)
} else {
createOpts.DBInstanceIdentifier = aws.String(resource.UniqueId())
}
if attr, ok := d.GetOk("db_subnet_group_name"); ok {
createOpts.DBSubnetGroupName = aws.String(attr.(string))
}
if attr, ok := d.GetOk("monitoring_role_arn"); ok {
createOpts.MonitoringRoleArn = aws.String(attr.(string))
}
if attr, ok := d.GetOk("monitoring_interval"); ok {
createOpts.MonitoringInterval = aws.Int64(int64(attr.(int)))
}
log.Printf("[DEBUG] Creating RDS DB Instance opts: %s", createOpts)
resp, err := conn.CreateDBInstance(createOpts)
if err != nil {
return err
}
d.SetId(*resp.DBInstance.DBInstanceIdentifier)
// reuse db_instance refresh func
stateConf := &resource.StateChangeConf{
Pending: []string{"creating", "backing-up", "modifying"},
Target: []string{"available"},
Refresh: resourceAwsDbInstanceStateRefreshFunc(d, meta),
Timeout: 40 * time.Minute,
MinTimeout: 10 * time.Second,
Delay: 10 * time.Second,
}
// Wait, catching any errors
_, err = stateConf.WaitForState()
if err != nil {
return err
}
return resourceAwsRDSClusterInstanceRead(d, meta)
}
func resourceAwsRDSClusterInstanceRead(d *schema.ResourceData, meta interface{}) error {
db, err := resourceAwsDbInstanceRetrieve(d, meta)
// Errors from this helper are always reportable
if err != nil {
return fmt.Errorf("[WARN] Error on retrieving RDS Cluster Instance (%s): %s", d.Id(), err)
}
// A nil response means "not found"
if db == nil {
log.Printf("[WARN] RDS Cluster Instance (%s): not found, removing from state.", d.Id())
d.SetId("")
return nil
}
// Retrieve DB Cluster information, to determine if this Instance is a writer
conn := meta.(*AWSClient).rdsconn
resp, err := conn.DescribeDBClusters(&rds.DescribeDBClustersInput{
DBClusterIdentifier: db.DBClusterIdentifier,
})
var dbc *rds.DBCluster
for _, c := range resp.DBClusters {
if *c.DBClusterIdentifier == *db.DBClusterIdentifier {
dbc = c
}
}
if dbc == nil {
return fmt.Errorf("[WARN] Error finding RDS Cluster (%s) for Cluster Instance (%s): %s",
*db.DBClusterIdentifier, *db.DBInstanceIdentifier, err)
}
for _, m := range dbc.DBClusterMembers {
if *db.DBInstanceIdentifier == *m.DBInstanceIdentifier {
if *m.IsClusterWriter == true {
d.Set("writer", true)
} else {
d.Set("writer", false)
}
}
}
if db.Endpoint != nil {
d.Set("endpoint", db.Endpoint.Address)
d.Set("port", db.Endpoint.Port)
}
d.Set("publicly_accessible", db.PubliclyAccessible)
d.Set("cluster_identifier", db.DBClusterIdentifier)
d.Set("instance_class", db.DBInstanceClass)
d.Set("identifier", db.DBInstanceIdentifier)
d.Set("storage_encrypted", db.StorageEncrypted)
d.Set("kms_key_id", db.KmsKeyId)
d.Set("auto_minor_version_upgrade", db.AutoMinorVersionUpgrade)
d.Set("promotion_tier", db.PromotionTier)
if db.MonitoringInterval != nil {
d.Set("monitoring_interval", db.MonitoringInterval)
}
if db.MonitoringRoleArn != nil {
d.Set("monitoring_role_arn", db.MonitoringRoleArn)
}
if len(db.DBParameterGroups) > 0 {
d.Set("db_parameter_group_name", db.DBParameterGroups[0].DBParameterGroupName)
}
// Fetch and save tags
arn, err := buildRDSARN(d.Id(), meta.(*AWSClient).partition, meta.(*AWSClient).accountid, meta.(*AWSClient).region)
if err != nil {
log.Printf("[DEBUG] Error building ARN for RDS Cluster Instance (%s), not setting Tags", *db.DBInstanceIdentifier)
} else {
if err := saveTagsRDS(conn, d, arn); err != nil {
log.Printf("[WARN] Failed to save tags for RDS Cluster Instance (%s): %s", *db.DBClusterIdentifier, err)
}
}
return nil
}
func resourceAwsRDSClusterInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).rdsconn
requestUpdate := false
req := &rds.ModifyDBInstanceInput{
ApplyImmediately: aws.Bool(d.Get("apply_immediately").(bool)),
DBInstanceIdentifier: aws.String(d.Id()),
}
if d.HasChange("db_parameter_group_name") {
req.DBParameterGroupName = aws.String(d.Get("db_parameter_group_name").(string))
requestUpdate = true
}
if d.HasChange("instance_class") {
req.DBInstanceClass = aws.String(d.Get("instance_class").(string))
requestUpdate = true
}
if d.HasChange("monitoring_role_arn") {
d.SetPartial("monitoring_role_arn")
req.MonitoringRoleArn = aws.String(d.Get("monitoring_role_arn").(string))
requestUpdate = true
}
if d.HasChange("monitoring_interval") {
d.SetPartial("monitoring_interval")
req.MonitoringInterval = aws.Int64(int64(d.Get("monitoring_interval").(int)))
requestUpdate = true
}
if d.HasChange("auto_minor_version_upgrade") {
d.SetPartial("auto_minor_version_upgrade")
req.AutoMinorVersionUpgrade = aws.Bool(d.Get("auto_minor_version_upgrade").(bool))
requestUpdate = true
}
if d.HasChange("promotion_tier") {
d.SetPartial("promotion_tier")
req.PromotionTier = aws.Int64(int64(d.Get("promotion_tier").(int)))
requestUpdate = true
}
log.Printf("[DEBUG] Send DB Instance Modification request: %#v", requestUpdate)
if requestUpdate {
log.Printf("[DEBUG] DB Instance Modification request: %#v", req)
_, err := conn.ModifyDBInstance(req)
if err != nil {
return fmt.Errorf("Error modifying DB Instance %s: %s", d.Id(), err)
}
// reuse db_instance refresh func
stateConf := &resource.StateChangeConf{
Pending: []string{"creating", "backing-up", "modifying"},
Target: []string{"available"},
Refresh: resourceAwsDbInstanceStateRefreshFunc(d, meta),
Timeout: 40 * time.Minute,
MinTimeout: 10 * time.Second,
Delay: 10 * time.Second,
}
// Wait, catching any errors
_, err = stateConf.WaitForState()
if err != nil {
return err
}
}
if arn, err := buildRDSARN(d.Id(), meta.(*AWSClient).partition, meta.(*AWSClient).accountid, meta.(*AWSClient).region); err == nil {
if err := setTagsRDS(conn, d, arn); err != nil {
return err
}
}
return resourceAwsRDSClusterInstanceRead(d, meta)
}
func resourceAwsRDSClusterInstanceDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).rdsconn
log.Printf("[DEBUG] RDS Cluster Instance destroy: %v", d.Id())
opts := rds.DeleteDBInstanceInput{DBInstanceIdentifier: aws.String(d.Id())}
log.Printf("[DEBUG] RDS Cluster Instance destroy configuration: %s", opts)
if _, err := conn.DeleteDBInstance(&opts); err != nil {
return err
}
// re-uses db_instance refresh func
log.Println("[INFO] Waiting for RDS Cluster Instance to be destroyed")
stateConf := &resource.StateChangeConf{
Pending: []string{"modifying", "deleting"},
Target: []string{},
Refresh: resourceAwsDbInstanceStateRefreshFunc(d, meta),
Timeout: 40 * time.Minute,
MinTimeout: 10 * time.Second,
}
if _, err := stateConf.WaitForState(); err != nil {
return err
}
return nil
}