forked from hashicorp/terraform
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resource_aws_db_instance.go
362 lines (300 loc) · 9.6 KB
/
resource_aws_db_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
package aws
import (
"fmt"
"log"
"strconv"
"strings"
"time"
"github.com/hashicorp/terraform/flatmap"
"github.com/hashicorp/terraform/helper/config"
"github.com/hashicorp/terraform/helper/diff"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
"github.com/mitchellh/goamz/rds"
)
func resource_aws_db_instance_create(
s *terraform.InstanceState,
d *terraform.InstanceDiff,
meta interface{}) (*terraform.InstanceState, error) {
p := meta.(*ResourceProvider)
conn := p.rdsconn
// Merge the diff into the state so that we have all the attributes
// properly.
rs := s.MergeDiff(d)
var err error
var attr string
opts := rds.CreateDBInstance{}
if attr = rs.Attributes["allocated_storage"]; attr != "" {
opts.AllocatedStorage, err = strconv.Atoi(attr)
opts.SetAllocatedStorage = true
}
if attr = rs.Attributes["backup_retention_period"]; attr != "" {
opts.BackupRetentionPeriod, err = strconv.Atoi(attr)
opts.SetBackupRetentionPeriod = true
}
if attr = rs.Attributes["iops"]; attr != "" {
opts.Iops, err = strconv.Atoi(attr)
opts.SetIops = true
}
if attr = rs.Attributes["port"]; attr != "" {
opts.Port, err = strconv.Atoi(attr)
opts.SetPort = true
}
if attr = rs.Attributes["availability_zone"]; attr != "" {
opts.AvailabilityZone = attr
}
if attr = rs.Attributes["instance_class"]; attr != "" {
opts.DBInstanceClass = attr
}
if attr = rs.Attributes["maintenance_window"]; attr != "" {
opts.PreferredMaintenanceWindow = attr
}
if attr = rs.Attributes["backup_window"]; attr != "" {
opts.PreferredBackupWindow = attr
}
if attr = rs.Attributes["multi_az"]; attr == "true" {
opts.MultiAZ = true
}
if attr = rs.Attributes["publicly_accessible"]; attr == "true" {
opts.PubliclyAccessible = true
}
if attr = rs.Attributes["db_subnet_group_name"]; attr != "" {
opts.DBSubnetGroupName = attr
}
if err != nil {
return nil, fmt.Errorf("Error parsing configuration: %s", err)
}
if _, ok := rs.Attributes["vpc_security_group_ids.#"]; ok {
opts.VpcSecurityGroupIds = expandStringList(flatmap.Expand(
rs.Attributes, "vpc_security_group_ids").([]interface{}))
}
if _, ok := rs.Attributes["security_group_names.#"]; ok {
opts.DBSecurityGroupNames = expandStringList(flatmap.Expand(
rs.Attributes, "security_group_names").([]interface{}))
}
opts.DBInstanceIdentifier = rs.Attributes["identifier"]
opts.DBName = rs.Attributes["name"]
opts.MasterUsername = rs.Attributes["username"]
opts.MasterUserPassword = rs.Attributes["password"]
opts.EngineVersion = rs.Attributes["engine_version"]
opts.Engine = rs.Attributes["engine"]
log.Printf("[DEBUG] DB Instance create configuration: %#v", opts)
_, err = conn.CreateDBInstance(&opts)
if err != nil {
return nil, fmt.Errorf("Error creating DB Instance: %s", err)
}
rs.ID = rs.Attributes["identifier"]
log.Printf("[INFO] DB Instance ID: %s", rs.ID)
log.Println(
"[INFO] Waiting for DB Instance to be available")
stateConf := &resource.StateChangeConf{
Pending: []string{"creating", "backing-up", "modifying"},
Target: "available",
Refresh: DBInstanceStateRefreshFunc(rs.ID, conn),
Timeout: 10 * time.Minute,
MinTimeout: 10 * time.Second,
Delay: 30 * time.Second, // Wait 30 secs before starting
}
// Wait, catching any errors
_, err = stateConf.WaitForState()
if err != nil {
return rs, err
}
v, err := resource_aws_db_instance_retrieve(rs.ID, conn)
if err != nil {
return rs, err
}
return resource_aws_db_instance_update_state(rs, v)
}
func resource_aws_db_instance_update(
s *terraform.InstanceState,
d *terraform.InstanceDiff,
meta interface{}) (*terraform.InstanceState, error) {
panic("Cannot update DB")
}
func resource_aws_db_instance_destroy(
s *terraform.InstanceState,
meta interface{}) error {
p := meta.(*ResourceProvider)
conn := p.rdsconn
log.Printf("[DEBUG] DB Instance destroy: %v", s.ID)
opts := rds.DeleteDBInstance{DBInstanceIdentifier: s.ID}
if s.Attributes["skip_final_snapshot"] == "true" {
opts.SkipFinalSnapshot = true
} else {
opts.FinalDBSnapshotIdentifier = s.Attributes["final_snapshot_identifier"]
}
log.Printf("[DEBUG] DB Instance destroy configuration: %v", opts)
if _, err := conn.DeleteDBInstance(&opts); err != nil {
return err
}
log.Println(
"[INFO] Waiting for DB Instance to be destroyed")
stateConf := &resource.StateChangeConf{
Pending: []string{"creating", "backing-up",
"modifying", "deleting", "available"},
Target: "",
Refresh: DBInstanceStateRefreshFunc(s.ID, conn),
Timeout: 10 * time.Minute,
MinTimeout: 10 * time.Second,
Delay: 30 * time.Second, // Wait 30 secs before starting
}
if _, err := stateConf.WaitForState(); err != nil {
return err
}
return nil
}
func resource_aws_db_instance_refresh(
s *terraform.InstanceState,
meta interface{}) (*terraform.InstanceState, error) {
p := meta.(*ResourceProvider)
conn := p.rdsconn
v, err := resource_aws_db_instance_retrieve(s.ID, conn)
if err != nil {
return s, err
}
if v == nil {
s.ID = ""
return s, nil
}
return resource_aws_db_instance_update_state(s, v)
}
func resource_aws_db_instance_diff(
s *terraform.InstanceState,
c *terraform.ResourceConfig,
meta interface{}) (*terraform.InstanceDiff, error) {
b := &diff.ResourceBuilder{
Attrs: map[string]diff.AttrType{
"allocated_storage": diff.AttrTypeCreate,
"availability_zone": diff.AttrTypeCreate,
"backup_retention_period": diff.AttrTypeCreate,
"backup_window": diff.AttrTypeCreate,
"engine": diff.AttrTypeCreate,
"engine_version": diff.AttrTypeCreate,
"identifier": diff.AttrTypeCreate,
"instance_class": diff.AttrTypeCreate,
"iops": diff.AttrTypeCreate,
"maintenance_window": diff.AttrTypeCreate,
"multi_az": diff.AttrTypeCreate,
"name": diff.AttrTypeCreate,
"password": diff.AttrTypeCreate,
"port": diff.AttrTypeCreate,
"publicly_accessible": diff.AttrTypeCreate,
"username": diff.AttrTypeCreate,
"vpc_security_group_ids": diff.AttrTypeCreate,
"security_group_names": diff.AttrTypeCreate,
"db_subnet_group_name": diff.AttrTypeCreate,
"skip_final_snapshot": diff.AttrTypeUpdate,
"final_snapshot_identifier": diff.AttrTypeUpdate,
},
ComputedAttrs: []string{
"address",
"availability_zone",
"backup_retention_period",
"backup_window",
"engine_version",
"maintenance_window",
"endpoint",
"status",
"multi_az",
"port",
"address",
"password",
},
}
return b.Diff(s, c)
}
func resource_aws_db_instance_update_state(
s *terraform.InstanceState,
v *rds.DBInstance) (*terraform.InstanceState, error) {
s.Attributes["address"] = v.Address
s.Attributes["allocated_storage"] = strconv.Itoa(v.AllocatedStorage)
s.Attributes["availability_zone"] = v.AvailabilityZone
s.Attributes["backup_retention_period"] = strconv.Itoa(v.BackupRetentionPeriod)
s.Attributes["backup_window"] = v.PreferredBackupWindow
s.Attributes["endpoint"] = fmt.Sprintf("%s:%s", s.Attributes["address"], strconv.Itoa(v.Port))
s.Attributes["engine"] = v.Engine
s.Attributes["engine_version"] = v.EngineVersion
s.Attributes["instance_class"] = v.DBInstanceClass
s.Attributes["maintenance_window"] = v.PreferredMaintenanceWindow
s.Attributes["multi_az"] = strconv.FormatBool(v.MultiAZ)
s.Attributes["name"] = v.DBName
s.Attributes["port"] = strconv.Itoa(v.Port)
s.Attributes["status"] = v.DBInstanceStatus
s.Attributes["username"] = v.MasterUsername
s.Attributes["db_subnet_group_name"] = v.DBSubnetGroup.Name
// Flatten our group values
toFlatten := make(map[string]interface{})
if len(v.DBSecurityGroupNames) > 0 && v.DBSecurityGroupNames[0] != "" {
toFlatten["security_group_names"] = v.DBSecurityGroupNames
}
if len(v.VpcSecurityGroupIds) > 0 && v.VpcSecurityGroupIds[0] != "" {
toFlatten["vpc_security_group_ids"] = v.VpcSecurityGroupIds
}
for k, v := range flatmap.Flatten(toFlatten) {
s.Attributes[k] = v
}
return s, nil
}
func resource_aws_db_instance_retrieve(id string, conn *rds.Rds) (*rds.DBInstance, error) {
opts := rds.DescribeDBInstances{
DBInstanceIdentifier: id,
}
log.Printf("[DEBUG] DB Instance describe configuration: %#v", opts)
resp, err := conn.DescribeDBInstances(&opts)
if err != nil {
if strings.Contains(err.Error(), "DBInstanceNotFound") {
return nil, nil
}
return nil, fmt.Errorf("Error retrieving DB Instances: %s", err)
}
if len(resp.DBInstances) != 1 ||
resp.DBInstances[0].DBInstanceIdentifier != id {
if err != nil {
return nil, nil
}
}
v := resp.DBInstances[0]
return &v, nil
}
func resource_aws_db_instance_validation() *config.Validator {
return &config.Validator{
Required: []string{
"allocated_storage",
"engine",
"engine_version",
"identifier",
"instance_class",
"name",
"password",
"username",
},
Optional: []string{
"availability_zone",
"backup_retention_period",
"backup_window",
"iops",
"maintenance_window",
"multi_az",
"port",
"publicly_accessible",
"vpc_security_group_ids.*",
"skip_final_snapshot",
"security_group_names.*",
"db_subnet_group_name",
},
}
}
func DBInstanceStateRefreshFunc(id string, conn *rds.Rds) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
v, err := resource_aws_db_instance_retrieve(id, conn)
if err != nil {
log.Printf("Error on retrieving DB Instance when waiting: %s", err)
return nil, "", err
}
if v == nil {
return nil, "", nil
}
return v, v.DBInstanceStatus, nil
}
}