github.com/andresvia/terraform@v0.6.15-0.20160412045437-d51c75946785/builtin/providers/aws/resource_aws_db_subnet_group.go (about) 1 package aws 2 3 import ( 4 "fmt" 5 "log" 6 "regexp" 7 "strings" 8 "time" 9 10 "github.com/aws/aws-sdk-go/aws" 11 "github.com/aws/aws-sdk-go/aws/awserr" 12 "github.com/aws/aws-sdk-go/service/iam" 13 "github.com/aws/aws-sdk-go/service/rds" 14 "github.com/hashicorp/terraform/helper/resource" 15 "github.com/hashicorp/terraform/helper/schema" 16 ) 17 18 func resourceAwsDbSubnetGroup() *schema.Resource { 19 return &schema.Resource{ 20 Create: resourceAwsDbSubnetGroupCreate, 21 Read: resourceAwsDbSubnetGroupRead, 22 Update: resourceAwsDbSubnetGroupUpdate, 23 Delete: resourceAwsDbSubnetGroupDelete, 24 25 Schema: map[string]*schema.Schema{ 26 "arn": &schema.Schema{ 27 Type: schema.TypeString, 28 Computed: true, 29 }, 30 31 "name": &schema.Schema{ 32 Type: schema.TypeString, 33 ForceNew: true, 34 Required: true, 35 ValidateFunc: validateSubnetGroupName, 36 }, 37 38 "description": &schema.Schema{ 39 Type: schema.TypeString, 40 Required: true, 41 }, 42 43 "subnet_ids": &schema.Schema{ 44 Type: schema.TypeSet, 45 Required: true, 46 Elem: &schema.Schema{Type: schema.TypeString}, 47 Set: schema.HashString, 48 }, 49 50 "tags": tagsSchema(), 51 }, 52 } 53 } 54 55 func resourceAwsDbSubnetGroupCreate(d *schema.ResourceData, meta interface{}) error { 56 rdsconn := meta.(*AWSClient).rdsconn 57 tags := tagsFromMapRDS(d.Get("tags").(map[string]interface{})) 58 59 subnetIdsSet := d.Get("subnet_ids").(*schema.Set) 60 subnetIds := make([]*string, subnetIdsSet.Len()) 61 for i, subnetId := range subnetIdsSet.List() { 62 subnetIds[i] = aws.String(subnetId.(string)) 63 } 64 65 createOpts := rds.CreateDBSubnetGroupInput{ 66 DBSubnetGroupName: aws.String(d.Get("name").(string)), 67 DBSubnetGroupDescription: aws.String(d.Get("description").(string)), 68 SubnetIds: subnetIds, 69 Tags: tags, 70 } 71 72 log.Printf("[DEBUG] Create DB Subnet Group: %#v", createOpts) 73 _, err := rdsconn.CreateDBSubnetGroup(&createOpts) 74 if err != nil { 75 return fmt.Errorf("Error creating DB Subnet Group: %s", err) 76 } 77 78 d.SetId(*createOpts.DBSubnetGroupName) 79 log.Printf("[INFO] DB Subnet Group ID: %s", d.Id()) 80 return resourceAwsDbSubnetGroupRead(d, meta) 81 } 82 83 func resourceAwsDbSubnetGroupRead(d *schema.ResourceData, meta interface{}) error { 84 rdsconn := meta.(*AWSClient).rdsconn 85 86 describeOpts := rds.DescribeDBSubnetGroupsInput{ 87 DBSubnetGroupName: aws.String(d.Id()), 88 } 89 90 describeResp, err := rdsconn.DescribeDBSubnetGroups(&describeOpts) 91 if err != nil { 92 if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "DBSubnetGroupNotFoundFault" { 93 // Update state to indicate the db subnet no longer exists. 94 d.SetId("") 95 return nil 96 } 97 return err 98 } 99 100 if len(describeResp.DBSubnetGroups) == 0 { 101 return fmt.Errorf("Unable to find DB Subnet Group: %#v", describeResp.DBSubnetGroups) 102 } 103 104 var subnetGroup *rds.DBSubnetGroup 105 for _, s := range describeResp.DBSubnetGroups { 106 // AWS is down casing the name provided, so we compare lower case versions 107 // of the names. We lower case both our name and their name in the check, 108 // incase they change that someday. 109 if strings.ToLower(d.Id()) == strings.ToLower(*s.DBSubnetGroupName) { 110 subnetGroup = describeResp.DBSubnetGroups[0] 111 } 112 } 113 114 if subnetGroup.DBSubnetGroupName == nil { 115 return fmt.Errorf("Unable to find DB Subnet Group: %#v", describeResp.DBSubnetGroups) 116 } 117 118 d.Set("name", subnetGroup.DBSubnetGroupName) 119 d.Set("description", subnetGroup.DBSubnetGroupDescription) 120 121 subnets := make([]string, 0, len(subnetGroup.Subnets)) 122 for _, s := range subnetGroup.Subnets { 123 subnets = append(subnets, *s.SubnetIdentifier) 124 } 125 d.Set("subnet_ids", subnets) 126 127 // list tags for resource 128 // set tags 129 conn := meta.(*AWSClient).rdsconn 130 arn, err := buildRDSsubgrpARN(d, meta) 131 if err != nil { 132 log.Printf("[DEBUG] Error building ARN for DB Subnet Group, not setting Tags for group %s", *subnetGroup.DBSubnetGroupName) 133 } else { 134 d.Set("arn", arn) 135 resp, err := conn.ListTagsForResource(&rds.ListTagsForResourceInput{ 136 ResourceName: aws.String(arn), 137 }) 138 139 if err != nil { 140 log.Printf("[DEBUG] Error retreiving tags for ARN: %s", arn) 141 } 142 143 var dt []*rds.Tag 144 if len(resp.TagList) > 0 { 145 dt = resp.TagList 146 } 147 d.Set("tags", tagsToMapRDS(dt)) 148 } 149 150 return nil 151 } 152 153 func resourceAwsDbSubnetGroupUpdate(d *schema.ResourceData, meta interface{}) error { 154 conn := meta.(*AWSClient).rdsconn 155 if d.HasChange("subnet_ids") || d.HasChange("description") { 156 _, n := d.GetChange("subnet_ids") 157 if n == nil { 158 n = new(schema.Set) 159 } 160 ns := n.(*schema.Set) 161 162 var sIds []*string 163 for _, s := range ns.List() { 164 sIds = append(sIds, aws.String(s.(string))) 165 } 166 167 _, err := conn.ModifyDBSubnetGroup(&rds.ModifyDBSubnetGroupInput{ 168 DBSubnetGroupName: aws.String(d.Id()), 169 DBSubnetGroupDescription: aws.String(d.Get("description").(string)), 170 SubnetIds: sIds, 171 }) 172 173 if err != nil { 174 return err 175 } 176 } 177 178 if arn, err := buildRDSsubgrpARN(d, meta); err == nil { 179 if err := setTagsRDS(conn, d, arn); err != nil { 180 return err 181 } else { 182 d.SetPartial("tags") 183 } 184 } 185 186 return resourceAwsDbSubnetGroupRead(d, meta) 187 } 188 189 func resourceAwsDbSubnetGroupDelete(d *schema.ResourceData, meta interface{}) error { 190 stateConf := &resource.StateChangeConf{ 191 Pending: []string{"pending"}, 192 Target: []string{"destroyed"}, 193 Refresh: resourceAwsDbSubnetGroupDeleteRefreshFunc(d, meta), 194 Timeout: 3 * time.Minute, 195 MinTimeout: 1 * time.Second, 196 } 197 _, err := stateConf.WaitForState() 198 return err 199 } 200 201 func resourceAwsDbSubnetGroupDeleteRefreshFunc( 202 d *schema.ResourceData, 203 meta interface{}) resource.StateRefreshFunc { 204 rdsconn := meta.(*AWSClient).rdsconn 205 206 return func() (interface{}, string, error) { 207 208 deleteOpts := rds.DeleteDBSubnetGroupInput{ 209 DBSubnetGroupName: aws.String(d.Id()), 210 } 211 212 if _, err := rdsconn.DeleteDBSubnetGroup(&deleteOpts); err != nil { 213 rdserr, ok := err.(awserr.Error) 214 if !ok { 215 return d, "error", err 216 } 217 218 if rdserr.Code() != "DBSubnetGroupNotFoundFault" { 219 return d, "error", err 220 } 221 } 222 223 return d, "destroyed", nil 224 } 225 } 226 227 func buildRDSsubgrpARN(d *schema.ResourceData, meta interface{}) (string, error) { 228 iamconn := meta.(*AWSClient).iamconn 229 region := meta.(*AWSClient).region 230 // An zero value GetUserInput{} defers to the currently logged in user 231 resp, err := iamconn.GetUser(&iam.GetUserInput{}) 232 if err != nil { 233 return "", err 234 } 235 userARN := *resp.User.Arn 236 accountID := strings.Split(userARN, ":")[4] 237 arn := fmt.Sprintf("arn:aws:rds:%s:%s:subgrp:%s", region, accountID, d.Id()) 238 return arn, nil 239 } 240 241 func validateSubnetGroupName(v interface{}, k string) (ws []string, errors []error) { 242 value := v.(string) 243 if !regexp.MustCompile(`^[ .0-9a-z-_]+$`).MatchString(value) { 244 errors = append(errors, fmt.Errorf( 245 "only lowercase alphanumeric characters, hyphens, underscores, periods, and spaces allowed in %q", k)) 246 } 247 if len(value) > 255 { 248 errors = append(errors, fmt.Errorf( 249 "%q cannot be longer than 255 characters", k)) 250 } 251 if regexp.MustCompile(`(?i)^default$`).MatchString(value) { 252 errors = append(errors, fmt.Errorf( 253 "%q is not allowed as %q", "Default", k)) 254 } 255 return 256 }