forked from hashicorp/terraform
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resource_aws_db_subnet_group.go
257 lines (216 loc) · 7.05 KB
/
resource_aws_db_subnet_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
package aws
import (
"fmt"
"log"
"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 resourceAwsDbSubnetGroup() *schema.Resource {
return &schema.Resource{
Create: resourceAwsDbSubnetGroupCreate,
Read: resourceAwsDbSubnetGroupRead,
Update: resourceAwsDbSubnetGroupUpdate,
Delete: resourceAwsDbSubnetGroupDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"arn": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"name": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{"name_prefix"},
ValidateFunc: validateDbSubnetGroupName,
},
"name_prefix": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validateDbSubnetGroupNamePrefix,
},
"description": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Default: "Managed by Terraform",
},
"subnet_ids": &schema.Schema{
Type: schema.TypeSet,
Required: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
},
"tags": tagsSchema(),
},
}
}
func resourceAwsDbSubnetGroupCreate(d *schema.ResourceData, meta interface{}) error {
rdsconn := meta.(*AWSClient).rdsconn
tags := tagsFromMapRDS(d.Get("tags").(map[string]interface{}))
subnetIdsSet := d.Get("subnet_ids").(*schema.Set)
subnetIds := make([]*string, subnetIdsSet.Len())
for i, subnetId := range subnetIdsSet.List() {
subnetIds[i] = aws.String(subnetId.(string))
}
var groupName string
if v, ok := d.GetOk("name"); ok {
groupName = v.(string)
} else if v, ok := d.GetOk("name_prefix"); ok {
groupName = resource.PrefixedUniqueId(v.(string))
} else {
groupName = resource.UniqueId()
}
createOpts := rds.CreateDBSubnetGroupInput{
DBSubnetGroupName: aws.String(groupName),
DBSubnetGroupDescription: aws.String(d.Get("description").(string)),
SubnetIds: subnetIds,
Tags: tags,
}
log.Printf("[DEBUG] Create DB Subnet Group: %#v", createOpts)
_, err := rdsconn.CreateDBSubnetGroup(&createOpts)
if err != nil {
return fmt.Errorf("Error creating DB Subnet Group: %s", err)
}
d.SetId(*createOpts.DBSubnetGroupName)
log.Printf("[INFO] DB Subnet Group ID: %s", d.Id())
return resourceAwsDbSubnetGroupRead(d, meta)
}
func resourceAwsDbSubnetGroupRead(d *schema.ResourceData, meta interface{}) error {
rdsconn := meta.(*AWSClient).rdsconn
describeOpts := rds.DescribeDBSubnetGroupsInput{
DBSubnetGroupName: aws.String(d.Id()),
}
describeResp, err := rdsconn.DescribeDBSubnetGroups(&describeOpts)
if err != nil {
if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "DBSubnetGroupNotFoundFault" {
// Update state to indicate the db subnet no longer exists.
d.SetId("")
return nil
}
return err
}
if len(describeResp.DBSubnetGroups) == 0 {
return fmt.Errorf("Unable to find DB Subnet Group: %#v", describeResp.DBSubnetGroups)
}
var subnetGroup *rds.DBSubnetGroup
for _, s := range describeResp.DBSubnetGroups {
// AWS is down casing the name provided, so we compare lower case versions
// of the names. We lower case both our name and their name in the check,
// incase they change that someday.
if strings.ToLower(d.Id()) == strings.ToLower(*s.DBSubnetGroupName) {
subnetGroup = describeResp.DBSubnetGroups[0]
}
}
if subnetGroup.DBSubnetGroupName == nil {
return fmt.Errorf("Unable to find DB Subnet Group: %#v", describeResp.DBSubnetGroups)
}
d.Set("name", subnetGroup.DBSubnetGroupName)
d.Set("description", subnetGroup.DBSubnetGroupDescription)
subnets := make([]string, 0, len(subnetGroup.Subnets))
for _, s := range subnetGroup.Subnets {
subnets = append(subnets, *s.SubnetIdentifier)
}
d.Set("subnet_ids", subnets)
// list tags for resource
// set tags
conn := meta.(*AWSClient).rdsconn
arn, err := buildRDSsubgrpARN(d.Id(), meta.(*AWSClient).partition, meta.(*AWSClient).accountid, meta.(*AWSClient).region)
if err != nil {
log.Printf("[DEBUG] Error building ARN for DB Subnet Group, not setting Tags for group %s", *subnetGroup.DBSubnetGroupName)
} else {
d.Set("arn", arn)
resp, err := conn.ListTagsForResource(&rds.ListTagsForResourceInput{
ResourceName: aws.String(arn),
})
if err != nil {
log.Printf("[DEBUG] Error retreiving tags for ARN: %s", arn)
}
var dt []*rds.Tag
if len(resp.TagList) > 0 {
dt = resp.TagList
}
d.Set("tags", tagsToMapRDS(dt))
}
return nil
}
func resourceAwsDbSubnetGroupUpdate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).rdsconn
if d.HasChange("subnet_ids") || d.HasChange("description") {
_, n := d.GetChange("subnet_ids")
if n == nil {
n = new(schema.Set)
}
ns := n.(*schema.Set)
var sIds []*string
for _, s := range ns.List() {
sIds = append(sIds, aws.String(s.(string)))
}
_, err := conn.ModifyDBSubnetGroup(&rds.ModifyDBSubnetGroupInput{
DBSubnetGroupName: aws.String(d.Id()),
DBSubnetGroupDescription: aws.String(d.Get("description").(string)),
SubnetIds: sIds,
})
if err != nil {
return err
}
}
if arn, err := buildRDSsubgrpARN(d.Id(), meta.(*AWSClient).partition, meta.(*AWSClient).accountid, meta.(*AWSClient).region); err == nil {
if err := setTagsRDS(conn, d, arn); err != nil {
return err
} else {
d.SetPartial("tags")
}
}
return resourceAwsDbSubnetGroupRead(d, meta)
}
func resourceAwsDbSubnetGroupDelete(d *schema.ResourceData, meta interface{}) error {
stateConf := &resource.StateChangeConf{
Pending: []string{"pending"},
Target: []string{"destroyed"},
Refresh: resourceAwsDbSubnetGroupDeleteRefreshFunc(d, meta),
Timeout: 3 * time.Minute,
MinTimeout: 1 * time.Second,
}
_, err := stateConf.WaitForState()
return err
}
func resourceAwsDbSubnetGroupDeleteRefreshFunc(
d *schema.ResourceData,
meta interface{}) resource.StateRefreshFunc {
rdsconn := meta.(*AWSClient).rdsconn
return func() (interface{}, string, error) {
deleteOpts := rds.DeleteDBSubnetGroupInput{
DBSubnetGroupName: aws.String(d.Id()),
}
if _, err := rdsconn.DeleteDBSubnetGroup(&deleteOpts); err != nil {
rdserr, ok := err.(awserr.Error)
if !ok {
return d, "error", err
}
if rdserr.Code() != "DBSubnetGroupNotFoundFault" {
return d, "error", err
}
}
return d, "destroyed", nil
}
}
func buildRDSsubgrpARN(identifier, partition, accountid, region string) (string, error) {
if partition == "" {
return "", fmt.Errorf("Unable to construct RDS ARN because of missing AWS partition")
}
if accountid == "" {
return "", fmt.Errorf("Unable to construct RDS ARN because of missing AWS Account ID")
}
arn := fmt.Sprintf("arn:%s:rds:%s:%s:subgrp:%s", partition, region, accountid, identifier)
return arn, nil
}