github.com/rhenning/terraform@v0.8.0-beta2/builtin/providers/aws/resource_aws_db_instance.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/rds" 13 14 "github.com/hashicorp/terraform/helper/resource" 15 "github.com/hashicorp/terraform/helper/schema" 16 ) 17 18 func resourceAwsDbInstance() *schema.Resource { 19 return &schema.Resource{ 20 Create: resourceAwsDbInstanceCreate, 21 Read: resourceAwsDbInstanceRead, 22 Update: resourceAwsDbInstanceUpdate, 23 Delete: resourceAwsDbInstanceDelete, 24 Importer: &schema.ResourceImporter{ 25 State: resourceAwsDbInstanceImport, 26 }, 27 28 Schema: map[string]*schema.Schema{ 29 "name": &schema.Schema{ 30 Type: schema.TypeString, 31 Optional: true, 32 Computed: true, 33 ForceNew: true, 34 }, 35 36 "arn": &schema.Schema{ 37 Type: schema.TypeString, 38 Computed: true, 39 }, 40 41 "username": &schema.Schema{ 42 Type: schema.TypeString, 43 Optional: true, 44 Computed: true, 45 ForceNew: true, 46 }, 47 48 "password": &schema.Schema{ 49 Type: schema.TypeString, 50 Optional: true, 51 Sensitive: true, 52 }, 53 54 "engine": &schema.Schema{ 55 Type: schema.TypeString, 56 Optional: true, 57 Computed: true, 58 ForceNew: true, 59 StateFunc: func(v interface{}) string { 60 value := v.(string) 61 return strings.ToLower(value) 62 }, 63 }, 64 65 "engine_version": &schema.Schema{ 66 Type: schema.TypeString, 67 Optional: true, 68 Computed: true, 69 }, 70 71 "character_set_name": &schema.Schema{ 72 Type: schema.TypeString, 73 Optional: true, 74 Computed: true, 75 ForceNew: true, 76 }, 77 78 "storage_encrypted": &schema.Schema{ 79 Type: schema.TypeBool, 80 Optional: true, 81 ForceNew: true, 82 }, 83 84 "allocated_storage": &schema.Schema{ 85 Type: schema.TypeInt, 86 Optional: true, 87 Computed: true, 88 }, 89 90 "storage_type": &schema.Schema{ 91 Type: schema.TypeString, 92 Optional: true, 93 Computed: true, 94 }, 95 96 "identifier": &schema.Schema{ 97 Type: schema.TypeString, 98 Optional: true, 99 Computed: true, 100 ForceNew: true, 101 ValidateFunc: validateRdsId, 102 }, 103 104 "instance_class": &schema.Schema{ 105 Type: schema.TypeString, 106 Required: true, 107 }, 108 109 "availability_zone": &schema.Schema{ 110 Type: schema.TypeString, 111 Optional: true, 112 Computed: true, 113 ForceNew: true, 114 }, 115 116 "backup_retention_period": &schema.Schema{ 117 Type: schema.TypeInt, 118 Optional: true, 119 Computed: true, 120 }, 121 122 "backup_window": &schema.Schema{ 123 Type: schema.TypeString, 124 Optional: true, 125 Computed: true, 126 }, 127 128 "iops": &schema.Schema{ 129 Type: schema.TypeInt, 130 Optional: true, 131 }, 132 133 "license_model": &schema.Schema{ 134 Type: schema.TypeString, 135 Optional: true, 136 Computed: true, 137 }, 138 139 "maintenance_window": &schema.Schema{ 140 Type: schema.TypeString, 141 Optional: true, 142 Computed: true, 143 StateFunc: func(v interface{}) string { 144 if v != nil { 145 value := v.(string) 146 return strings.ToLower(value) 147 } 148 return "" 149 }, 150 }, 151 152 "multi_az": &schema.Schema{ 153 Type: schema.TypeBool, 154 Optional: true, 155 Computed: true, 156 }, 157 158 "port": &schema.Schema{ 159 Type: schema.TypeInt, 160 Optional: true, 161 Computed: true, 162 }, 163 164 "publicly_accessible": &schema.Schema{ 165 Type: schema.TypeBool, 166 Optional: true, 167 Default: false, 168 }, 169 170 "vpc_security_group_ids": &schema.Schema{ 171 Type: schema.TypeSet, 172 Optional: true, 173 Computed: true, 174 Elem: &schema.Schema{Type: schema.TypeString}, 175 Set: schema.HashString, 176 }, 177 178 "security_group_names": &schema.Schema{ 179 Type: schema.TypeSet, 180 Optional: true, 181 Elem: &schema.Schema{Type: schema.TypeString}, 182 Set: schema.HashString, 183 }, 184 185 "final_snapshot_identifier": &schema.Schema{ 186 Type: schema.TypeString, 187 Optional: true, 188 ValidateFunc: func(v interface{}, k string) (ws []string, es []error) { 189 value := v.(string) 190 if !regexp.MustCompile(`^[0-9A-Za-z-]+$`).MatchString(value) { 191 es = append(es, fmt.Errorf( 192 "only alphanumeric characters and hyphens allowed in %q", k)) 193 } 194 if regexp.MustCompile(`--`).MatchString(value) { 195 es = append(es, fmt.Errorf("%q cannot contain two consecutive hyphens", k)) 196 } 197 if regexp.MustCompile(`-$`).MatchString(value) { 198 es = append(es, fmt.Errorf("%q cannot end in a hyphen", k)) 199 } 200 return 201 }, 202 }, 203 204 "skip_final_snapshot": &schema.Schema{ 205 Type: schema.TypeBool, 206 Optional: true, 207 Default: true, 208 }, 209 210 "copy_tags_to_snapshot": &schema.Schema{ 211 Type: schema.TypeBool, 212 Optional: true, 213 Default: false, 214 }, 215 216 "db_subnet_group_name": &schema.Schema{ 217 Type: schema.TypeString, 218 Optional: true, 219 ForceNew: true, 220 Computed: true, 221 }, 222 223 "parameter_group_name": &schema.Schema{ 224 Type: schema.TypeString, 225 Optional: true, 226 Computed: true, 227 }, 228 229 "address": &schema.Schema{ 230 Type: schema.TypeString, 231 Computed: true, 232 }, 233 234 "endpoint": &schema.Schema{ 235 Type: schema.TypeString, 236 Computed: true, 237 }, 238 239 "hosted_zone_id": &schema.Schema{ 240 Type: schema.TypeString, 241 Computed: true, 242 }, 243 244 "status": &schema.Schema{ 245 Type: schema.TypeString, 246 Computed: true, 247 }, 248 249 // apply_immediately is used to determine when the update modifications 250 // take place. 251 // See http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Overview.DBInstance.Modifying.html 252 "apply_immediately": &schema.Schema{ 253 Type: schema.TypeBool, 254 Optional: true, 255 Computed: true, 256 }, 257 258 "replicate_source_db": &schema.Schema{ 259 Type: schema.TypeString, 260 Optional: true, 261 }, 262 263 "replicas": &schema.Schema{ 264 Type: schema.TypeList, 265 Computed: true, 266 Elem: &schema.Schema{Type: schema.TypeString}, 267 }, 268 269 "snapshot_identifier": &schema.Schema{ 270 Type: schema.TypeString, 271 Computed: false, 272 Optional: true, 273 ForceNew: true, 274 Elem: &schema.Schema{Type: schema.TypeString}, 275 }, 276 277 "auto_minor_version_upgrade": &schema.Schema{ 278 Type: schema.TypeBool, 279 Optional: true, 280 Default: true, 281 }, 282 283 "allow_major_version_upgrade": &schema.Schema{ 284 Type: schema.TypeBool, 285 Computed: false, 286 Optional: true, 287 }, 288 289 "monitoring_role_arn": &schema.Schema{ 290 Type: schema.TypeString, 291 Optional: true, 292 Computed: true, 293 }, 294 295 "monitoring_interval": &schema.Schema{ 296 Type: schema.TypeInt, 297 Optional: true, 298 Default: 0, 299 }, 300 301 "option_group_name": &schema.Schema{ 302 Type: schema.TypeString, 303 Optional: true, 304 Computed: true, 305 }, 306 307 "kms_key_id": &schema.Schema{ 308 Type: schema.TypeString, 309 Optional: true, 310 Computed: true, 311 ForceNew: true, 312 }, 313 314 "tags": tagsSchema(), 315 }, 316 } 317 } 318 319 func resourceAwsDbInstanceCreate(d *schema.ResourceData, meta interface{}) error { 320 conn := meta.(*AWSClient).rdsconn 321 tags := tagsFromMapRDS(d.Get("tags").(map[string]interface{})) 322 323 identifier := d.Get("identifier").(string) 324 // Generate a unique ID for the user 325 if identifier == "" { 326 identifier = resource.PrefixedUniqueId("tf-") 327 // SQL Server identifier size is max 15 chars, so truncate 328 if engine := d.Get("engine").(string); engine != "" { 329 if strings.Contains(strings.ToLower(engine), "sqlserver") { 330 identifier = identifier[:15] 331 } 332 } 333 d.Set("identifier", identifier) 334 } 335 336 if v, ok := d.GetOk("replicate_source_db"); ok { 337 opts := rds.CreateDBInstanceReadReplicaInput{ 338 SourceDBInstanceIdentifier: aws.String(v.(string)), 339 CopyTagsToSnapshot: aws.Bool(d.Get("copy_tags_to_snapshot").(bool)), 340 DBInstanceClass: aws.String(d.Get("instance_class").(string)), 341 DBInstanceIdentifier: aws.String(identifier), 342 PubliclyAccessible: aws.Bool(d.Get("publicly_accessible").(bool)), 343 Tags: tags, 344 } 345 if attr, ok := d.GetOk("iops"); ok { 346 opts.Iops = aws.Int64(int64(attr.(int))) 347 } 348 349 if attr, ok := d.GetOk("port"); ok { 350 opts.Port = aws.Int64(int64(attr.(int))) 351 } 352 353 if attr, ok := d.GetOk("availability_zone"); ok { 354 opts.AvailabilityZone = aws.String(attr.(string)) 355 } 356 357 if attr, ok := d.GetOk("storage_type"); ok { 358 opts.StorageType = aws.String(attr.(string)) 359 } 360 361 if attr, ok := d.GetOk("db_subnet_group_name"); ok { 362 opts.DBSubnetGroupName = aws.String(attr.(string)) 363 } 364 365 if attr, ok := d.GetOk("monitoring_role_arn"); ok { 366 opts.MonitoringRoleArn = aws.String(attr.(string)) 367 } 368 369 if attr, ok := d.GetOk("monitoring_interval"); ok { 370 opts.MonitoringInterval = aws.Int64(int64(attr.(int))) 371 } 372 373 if attr, ok := d.GetOk("option_group_name"); ok { 374 opts.OptionGroupName = aws.String(attr.(string)) 375 } 376 377 log.Printf("[DEBUG] DB Instance Replica create configuration: %#v", opts) 378 _, err := conn.CreateDBInstanceReadReplica(&opts) 379 if err != nil { 380 return fmt.Errorf("Error creating DB Instance: %s", err) 381 } 382 } else if _, ok := d.GetOk("snapshot_identifier"); ok { 383 opts := rds.RestoreDBInstanceFromDBSnapshotInput{ 384 DBInstanceClass: aws.String(d.Get("instance_class").(string)), 385 DBInstanceIdentifier: aws.String(d.Get("identifier").(string)), 386 DBSnapshotIdentifier: aws.String(d.Get("snapshot_identifier").(string)), 387 AutoMinorVersionUpgrade: aws.Bool(d.Get("auto_minor_version_upgrade").(bool)), 388 PubliclyAccessible: aws.Bool(d.Get("publicly_accessible").(bool)), 389 Tags: tags, 390 CopyTagsToSnapshot: aws.Bool(d.Get("copy_tags_to_snapshot").(bool)), 391 } 392 393 if attr, ok := d.GetOk("availability_zone"); ok { 394 opts.AvailabilityZone = aws.String(attr.(string)) 395 } 396 397 if attr, ok := d.GetOk("db_subnet_group_name"); ok { 398 opts.DBSubnetGroupName = aws.String(attr.(string)) 399 } 400 401 if attr, ok := d.GetOk("engine"); ok { 402 opts.Engine = aws.String(attr.(string)) 403 } 404 405 if attr, ok := d.GetOk("iops"); ok { 406 opts.Iops = aws.Int64(int64(attr.(int))) 407 } 408 409 if attr, ok := d.GetOk("license_model"); ok { 410 opts.LicenseModel = aws.String(attr.(string)) 411 } 412 413 if attr, ok := d.GetOk("multi_az"); ok { 414 opts.MultiAZ = aws.Bool(attr.(bool)) 415 } 416 417 if attr, ok := d.GetOk("option_group_name"); ok { 418 opts.OptionGroupName = aws.String(attr.(string)) 419 420 } 421 422 if attr, ok := d.GetOk("port"); ok { 423 opts.Port = aws.Int64(int64(attr.(int))) 424 } 425 426 if attr, ok := d.GetOk("tde_credential_arn"); ok { 427 opts.TdeCredentialArn = aws.String(attr.(string)) 428 } 429 430 if attr, ok := d.GetOk("storage_type"); ok { 431 opts.StorageType = aws.String(attr.(string)) 432 } 433 434 log.Printf("[DEBUG] DB Instance restore from snapshot configuration: %s", opts) 435 _, err := conn.RestoreDBInstanceFromDBSnapshot(&opts) 436 if err != nil { 437 return fmt.Errorf("Error creating DB Instance: %s", err) 438 } 439 440 var sgUpdate bool 441 if attr := d.Get("vpc_security_group_ids").(*schema.Set); attr.Len() > 0 { 442 sgUpdate = true 443 } 444 if attr := d.Get("security_group_names").(*schema.Set); attr.Len() > 0 { 445 sgUpdate = true 446 } 447 if sgUpdate { 448 log.Printf("[INFO] DB is restoring from snapshot with default security, but custom security should be set, will now update after snapshot is restored!") 449 450 // wait for instance to get up and then modify security 451 d.SetId(d.Get("identifier").(string)) 452 453 log.Printf("[INFO] DB Instance ID: %s", d.Id()) 454 455 log.Println( 456 "[INFO] Waiting for DB Instance to be available") 457 458 stateConf := &resource.StateChangeConf{ 459 Pending: []string{"creating", "backing-up", "modifying", "resetting-master-credentials", 460 "maintenance", "renaming", "rebooting", "upgrading"}, 461 Target: []string{"available"}, 462 Refresh: resourceAwsDbInstanceStateRefreshFunc(d, meta), 463 Timeout: 40 * time.Minute, 464 MinTimeout: 10 * time.Second, 465 Delay: 30 * time.Second, // Wait 30 secs before starting 466 } 467 468 // Wait, catching any errors 469 _, err := stateConf.WaitForState() 470 if err != nil { 471 return err 472 } 473 474 err = resourceAwsDbInstanceUpdate(d, meta) 475 if err != nil { 476 return err 477 } 478 479 } 480 } else { 481 if _, ok := d.GetOk("allocated_storage"); !ok { 482 return fmt.Errorf(`provider.aws: aws_db_instance: %s: "allocated_storage": required field is not set`, d.Get("name").(string)) 483 } 484 if _, ok := d.GetOk("engine"); !ok { 485 return fmt.Errorf(`provider.aws: aws_db_instance: %s: "engine": required field is not set`, d.Get("name").(string)) 486 } 487 if _, ok := d.GetOk("password"); !ok { 488 return fmt.Errorf(`provider.aws: aws_db_instance: %s: "password": required field is not set`, d.Get("name").(string)) 489 } 490 if _, ok := d.GetOk("username"); !ok { 491 return fmt.Errorf(`provider.aws: aws_db_instance: %s: "username": required field is not set`, d.Get("name").(string)) 492 } 493 opts := rds.CreateDBInstanceInput{ 494 AllocatedStorage: aws.Int64(int64(d.Get("allocated_storage").(int))), 495 DBName: aws.String(d.Get("name").(string)), 496 DBInstanceClass: aws.String(d.Get("instance_class").(string)), 497 DBInstanceIdentifier: aws.String(d.Get("identifier").(string)), 498 MasterUsername: aws.String(d.Get("username").(string)), 499 MasterUserPassword: aws.String(d.Get("password").(string)), 500 Engine: aws.String(d.Get("engine").(string)), 501 EngineVersion: aws.String(d.Get("engine_version").(string)), 502 StorageEncrypted: aws.Bool(d.Get("storage_encrypted").(bool)), 503 AutoMinorVersionUpgrade: aws.Bool(d.Get("auto_minor_version_upgrade").(bool)), 504 PubliclyAccessible: aws.Bool(d.Get("publicly_accessible").(bool)), 505 Tags: tags, 506 CopyTagsToSnapshot: aws.Bool(d.Get("copy_tags_to_snapshot").(bool)), 507 } 508 509 attr := d.Get("backup_retention_period") 510 opts.BackupRetentionPeriod = aws.Int64(int64(attr.(int))) 511 if attr, ok := d.GetOk("multi_az"); ok { 512 opts.MultiAZ = aws.Bool(attr.(bool)) 513 514 } 515 516 if attr, ok := d.GetOk("character_set_name"); ok { 517 opts.CharacterSetName = aws.String(attr.(string)) 518 } 519 520 if attr, ok := d.GetOk("maintenance_window"); ok { 521 opts.PreferredMaintenanceWindow = aws.String(attr.(string)) 522 } 523 524 if attr, ok := d.GetOk("backup_window"); ok { 525 opts.PreferredBackupWindow = aws.String(attr.(string)) 526 } 527 528 if attr, ok := d.GetOk("license_model"); ok { 529 opts.LicenseModel = aws.String(attr.(string)) 530 } 531 if attr, ok := d.GetOk("parameter_group_name"); ok { 532 opts.DBParameterGroupName = aws.String(attr.(string)) 533 } 534 535 if attr := d.Get("vpc_security_group_ids").(*schema.Set); attr.Len() > 0 { 536 var s []*string 537 for _, v := range attr.List() { 538 s = append(s, aws.String(v.(string))) 539 } 540 opts.VpcSecurityGroupIds = s 541 } 542 543 if attr := d.Get("security_group_names").(*schema.Set); attr.Len() > 0 { 544 var s []*string 545 for _, v := range attr.List() { 546 s = append(s, aws.String(v.(string))) 547 } 548 opts.DBSecurityGroups = s 549 } 550 if attr, ok := d.GetOk("storage_type"); ok { 551 opts.StorageType = aws.String(attr.(string)) 552 } 553 554 if attr, ok := d.GetOk("db_subnet_group_name"); ok { 555 opts.DBSubnetGroupName = aws.String(attr.(string)) 556 } 557 558 if attr, ok := d.GetOk("iops"); ok { 559 opts.Iops = aws.Int64(int64(attr.(int))) 560 } 561 562 if attr, ok := d.GetOk("port"); ok { 563 opts.Port = aws.Int64(int64(attr.(int))) 564 } 565 566 if attr, ok := d.GetOk("availability_zone"); ok { 567 opts.AvailabilityZone = aws.String(attr.(string)) 568 } 569 570 if attr, ok := d.GetOk("monitoring_role_arn"); ok { 571 opts.MonitoringRoleArn = aws.String(attr.(string)) 572 } 573 574 if attr, ok := d.GetOk("monitoring_interval"); ok { 575 opts.MonitoringInterval = aws.Int64(int64(attr.(int))) 576 } 577 578 if attr, ok := d.GetOk("option_group_name"); ok { 579 opts.OptionGroupName = aws.String(attr.(string)) 580 } 581 582 if attr, ok := d.GetOk("kms_key_id"); ok { 583 opts.KmsKeyId = aws.String(attr.(string)) 584 } 585 586 log.Printf("[DEBUG] DB Instance create configuration: %#v", opts) 587 var err error 588 err = resource.Retry(5*time.Minute, func() *resource.RetryError { 589 _, err = conn.CreateDBInstance(&opts) 590 if err != nil { 591 if awsErr, ok := err.(awserr.Error); ok { 592 if awsErr.Code() == "InvalidParameterValue" && strings.Contains(awsErr.Message(), "ENHANCED_MONITORING") { 593 return resource.RetryableError(awsErr) 594 } 595 } 596 return resource.NonRetryableError(err) 597 } 598 return nil 599 }) 600 if err != nil { 601 return fmt.Errorf("Error creating DB Instance: %s", err) 602 } 603 } 604 605 d.SetId(d.Get("identifier").(string)) 606 607 log.Printf("[INFO] DB Instance ID: %s", d.Id()) 608 609 log.Println( 610 "[INFO] Waiting for DB Instance to be available") 611 612 stateConf := &resource.StateChangeConf{ 613 Pending: []string{"creating", "backing-up", "modifying", "resetting-master-credentials", 614 "maintenance", "renaming", "rebooting", "upgrading", "configuring-enhanced-monitoring"}, 615 Target: []string{"available"}, 616 Refresh: resourceAwsDbInstanceStateRefreshFunc(d, meta), 617 Timeout: 40 * time.Minute, 618 MinTimeout: 10 * time.Second, 619 Delay: 30 * time.Second, // Wait 30 secs before starting 620 } 621 622 // Wait, catching any errors 623 _, err := stateConf.WaitForState() 624 if err != nil { 625 return err 626 } 627 628 return resourceAwsDbInstanceRead(d, meta) 629 } 630 631 func resourceAwsDbInstanceRead(d *schema.ResourceData, meta interface{}) error { 632 v, err := resourceAwsDbInstanceRetrieve(d, meta) 633 634 if err != nil { 635 return err 636 } 637 if v == nil { 638 d.SetId("") 639 return nil 640 } 641 642 d.Set("name", v.DBName) 643 d.Set("identifier", v.DBInstanceIdentifier) 644 d.Set("username", v.MasterUsername) 645 d.Set("engine", v.Engine) 646 d.Set("engine_version", v.EngineVersion) 647 d.Set("allocated_storage", v.AllocatedStorage) 648 d.Set("iops", v.Iops) 649 d.Set("copy_tags_to_snapshot", v.CopyTagsToSnapshot) 650 d.Set("auto_minor_version_upgrade", v.AutoMinorVersionUpgrade) 651 d.Set("storage_type", v.StorageType) 652 d.Set("instance_class", v.DBInstanceClass) 653 d.Set("availability_zone", v.AvailabilityZone) 654 d.Set("backup_retention_period", v.BackupRetentionPeriod) 655 d.Set("backup_window", v.PreferredBackupWindow) 656 d.Set("license_model", v.LicenseModel) 657 d.Set("maintenance_window", v.PreferredMaintenanceWindow) 658 d.Set("publicly_accessible", v.PubliclyAccessible) 659 d.Set("multi_az", v.MultiAZ) 660 d.Set("kms_key_id", v.KmsKeyId) 661 d.Set("port", v.DbInstancePort) 662 if v.DBSubnetGroup != nil { 663 d.Set("db_subnet_group_name", v.DBSubnetGroup.DBSubnetGroupName) 664 } 665 666 if v.CharacterSetName != nil { 667 d.Set("character_set_name", v.CharacterSetName) 668 } 669 670 if len(v.DBParameterGroups) > 0 { 671 d.Set("parameter_group_name", v.DBParameterGroups[0].DBParameterGroupName) 672 } 673 674 if v.Endpoint != nil { 675 d.Set("port", v.Endpoint.Port) 676 d.Set("address", v.Endpoint.Address) 677 d.Set("hosted_zone_id", v.Endpoint.HostedZoneId) 678 if v.Endpoint.Address != nil && v.Endpoint.Port != nil { 679 d.Set("endpoint", 680 fmt.Sprintf("%s:%d", *v.Endpoint.Address, *v.Endpoint.Port)) 681 } 682 } 683 684 d.Set("status", v.DBInstanceStatus) 685 d.Set("storage_encrypted", v.StorageEncrypted) 686 if v.OptionGroupMemberships != nil { 687 d.Set("option_group_name", v.OptionGroupMemberships[0].OptionGroupName) 688 } 689 690 if v.MonitoringInterval != nil { 691 d.Set("monitoring_interval", v.MonitoringInterval) 692 } 693 694 if v.MonitoringRoleArn != nil { 695 d.Set("monitoring_role_arn", v.MonitoringRoleArn) 696 } 697 698 // list tags for resource 699 // set tags 700 conn := meta.(*AWSClient).rdsconn 701 arn, err := buildRDSARN(d.Id(), meta.(*AWSClient).partition, meta.(*AWSClient).accountid, meta.(*AWSClient).region) 702 if err != nil { 703 name := "<empty>" 704 if v.DBName != nil && *v.DBName != "" { 705 name = *v.DBName 706 } 707 log.Printf("[DEBUG] Error building ARN for DB Instance, not setting Tags for DB %s", name) 708 } else { 709 d.Set("arn", arn) 710 resp, err := conn.ListTagsForResource(&rds.ListTagsForResourceInput{ 711 ResourceName: aws.String(arn), 712 }) 713 714 if err != nil { 715 log.Printf("[DEBUG] Error retrieving tags for ARN: %s", arn) 716 } 717 718 var dt []*rds.Tag 719 if len(resp.TagList) > 0 { 720 dt = resp.TagList 721 } 722 d.Set("tags", tagsToMapRDS(dt)) 723 } 724 725 // Create an empty schema.Set to hold all vpc security group ids 726 ids := &schema.Set{ 727 F: schema.HashString, 728 } 729 for _, v := range v.VpcSecurityGroups { 730 ids.Add(*v.VpcSecurityGroupId) 731 } 732 d.Set("vpc_security_group_ids", ids) 733 734 // Create an empty schema.Set to hold all security group names 735 sgn := &schema.Set{ 736 F: schema.HashString, 737 } 738 for _, v := range v.DBSecurityGroups { 739 sgn.Add(*v.DBSecurityGroupName) 740 } 741 d.Set("security_group_names", sgn) 742 743 // replica things 744 745 var replicas []string 746 for _, v := range v.ReadReplicaDBInstanceIdentifiers { 747 replicas = append(replicas, *v) 748 } 749 if err := d.Set("replicas", replicas); err != nil { 750 return fmt.Errorf("[DEBUG] Error setting replicas attribute: %#v, error: %#v", replicas, err) 751 } 752 753 d.Set("replicate_source_db", v.ReadReplicaSourceDBInstanceIdentifier) 754 755 return nil 756 } 757 758 func resourceAwsDbInstanceDelete(d *schema.ResourceData, meta interface{}) error { 759 conn := meta.(*AWSClient).rdsconn 760 761 log.Printf("[DEBUG] DB Instance destroy: %v", d.Id()) 762 763 opts := rds.DeleteDBInstanceInput{DBInstanceIdentifier: aws.String(d.Id())} 764 765 skipFinalSnapshot := d.Get("skip_final_snapshot").(bool) 766 opts.SkipFinalSnapshot = aws.Bool(skipFinalSnapshot) 767 768 if skipFinalSnapshot == false { 769 if name, present := d.GetOk("final_snapshot_identifier"); present { 770 opts.FinalDBSnapshotIdentifier = aws.String(name.(string)) 771 } else { 772 return fmt.Errorf("DB Instance FinalSnapshotIdentifier is required when a final snapshot is required") 773 } 774 } 775 776 log.Printf("[DEBUG] DB Instance destroy configuration: %v", opts) 777 if _, err := conn.DeleteDBInstance(&opts); err != nil { 778 return err 779 } 780 781 log.Println( 782 "[INFO] Waiting for DB Instance to be destroyed") 783 stateConf := &resource.StateChangeConf{ 784 Pending: []string{"creating", "backing-up", 785 "modifying", "deleting", "available"}, 786 Target: []string{}, 787 Refresh: resourceAwsDbInstanceStateRefreshFunc(d, meta), 788 Timeout: 40 * time.Minute, 789 MinTimeout: 10 * time.Second, 790 Delay: 30 * time.Second, // Wait 30 secs before starting 791 } 792 if _, err := stateConf.WaitForState(); err != nil { 793 return err 794 } 795 796 return nil 797 } 798 799 func resourceAwsDbInstanceUpdate(d *schema.ResourceData, meta interface{}) error { 800 conn := meta.(*AWSClient).rdsconn 801 802 d.Partial(true) 803 804 req := &rds.ModifyDBInstanceInput{ 805 ApplyImmediately: aws.Bool(d.Get("apply_immediately").(bool)), 806 DBInstanceIdentifier: aws.String(d.Id()), 807 } 808 d.SetPartial("apply_immediately") 809 810 requestUpdate := false 811 if d.HasChange("allocated_storage") || d.HasChange("iops") { 812 d.SetPartial("allocated_storage") 813 d.SetPartial("iops") 814 req.Iops = aws.Int64(int64(d.Get("iops").(int))) 815 req.AllocatedStorage = aws.Int64(int64(d.Get("allocated_storage").(int))) 816 requestUpdate = true 817 } 818 if d.HasChange("allow_major_version_upgrade") { 819 d.SetPartial("allow_major_version_upgrade") 820 req.AllowMajorVersionUpgrade = aws.Bool(d.Get("allow_major_version_upgrade").(bool)) 821 requestUpdate = true 822 } 823 if d.HasChange("backup_retention_period") { 824 d.SetPartial("backup_retention_period") 825 req.BackupRetentionPeriod = aws.Int64(int64(d.Get("backup_retention_period").(int))) 826 requestUpdate = true 827 } 828 if d.HasChange("copy_tags_to_snapshot") { 829 d.SetPartial("copy_tags_to_snapshot") 830 req.CopyTagsToSnapshot = aws.Bool(d.Get("copy_tags_to_snapshot").(bool)) 831 requestUpdate = true 832 } 833 if d.HasChange("instance_class") { 834 d.SetPartial("instance_class") 835 req.DBInstanceClass = aws.String(d.Get("instance_class").(string)) 836 requestUpdate = true 837 } 838 if d.HasChange("parameter_group_name") { 839 d.SetPartial("parameter_group_name") 840 req.DBParameterGroupName = aws.String(d.Get("parameter_group_name").(string)) 841 requestUpdate = true 842 } 843 if d.HasChange("engine_version") { 844 d.SetPartial("engine_version") 845 req.EngineVersion = aws.String(d.Get("engine_version").(string)) 846 req.AllowMajorVersionUpgrade = aws.Bool(d.Get("allow_major_version_upgrade").(bool)) 847 requestUpdate = true 848 } 849 if d.HasChange("backup_window") { 850 d.SetPartial("backup_window") 851 req.PreferredBackupWindow = aws.String(d.Get("backup_window").(string)) 852 requestUpdate = true 853 } 854 if d.HasChange("maintenance_window") { 855 d.SetPartial("maintenance_window") 856 req.PreferredMaintenanceWindow = aws.String(d.Get("maintenance_window").(string)) 857 requestUpdate = true 858 } 859 if d.HasChange("password") { 860 d.SetPartial("password") 861 req.MasterUserPassword = aws.String(d.Get("password").(string)) 862 requestUpdate = true 863 } 864 if d.HasChange("multi_az") { 865 d.SetPartial("multi_az") 866 req.MultiAZ = aws.Bool(d.Get("multi_az").(bool)) 867 requestUpdate = true 868 } 869 if d.HasChange("publicly_accessible") { 870 d.SetPartial("publicly_accessible") 871 req.PubliclyAccessible = aws.Bool(d.Get("publicly_accessible").(bool)) 872 requestUpdate = true 873 } 874 if d.HasChange("storage_type") { 875 d.SetPartial("storage_type") 876 req.StorageType = aws.String(d.Get("storage_type").(string)) 877 requestUpdate = true 878 879 if *req.StorageType == "io1" { 880 req.Iops = aws.Int64(int64(d.Get("iops").(int))) 881 } 882 } 883 if d.HasChange("auto_minor_version_upgrade") { 884 d.SetPartial("auto_minor_version_upgrade") 885 req.AutoMinorVersionUpgrade = aws.Bool(d.Get("auto_minor_version_upgrade").(bool)) 886 requestUpdate = true 887 } 888 889 if d.HasChange("monitoring_role_arn") { 890 d.SetPartial("monitoring_role_arn") 891 req.MonitoringRoleArn = aws.String(d.Get("monitoring_role_arn").(string)) 892 requestUpdate = true 893 } 894 895 if d.HasChange("monitoring_interval") { 896 d.SetPartial("monitoring_interval") 897 req.MonitoringInterval = aws.Int64(int64(d.Get("monitoring_interval").(int))) 898 requestUpdate = true 899 } 900 901 if d.HasChange("vpc_security_group_ids") { 902 if attr := d.Get("vpc_security_group_ids").(*schema.Set); attr.Len() > 0 { 903 var s []*string 904 for _, v := range attr.List() { 905 s = append(s, aws.String(v.(string))) 906 } 907 req.VpcSecurityGroupIds = s 908 } 909 requestUpdate = true 910 } 911 912 if d.HasChange("security_group_names") { 913 if attr := d.Get("security_group_names").(*schema.Set); attr.Len() > 0 { 914 var s []*string 915 for _, v := range attr.List() { 916 s = append(s, aws.String(v.(string))) 917 } 918 req.DBSecurityGroups = s 919 } 920 requestUpdate = true 921 } 922 923 if d.HasChange("option_group_name") { 924 d.SetPartial("option_group_name") 925 req.OptionGroupName = aws.String(d.Get("option_group_name").(string)) 926 requestUpdate = true 927 } 928 929 if d.HasChange("port") { 930 d.SetPartial("port") 931 req.DBPortNumber = aws.Int64(int64(d.Get("port").(int))) 932 requestUpdate = true 933 } 934 935 log.Printf("[DEBUG] Send DB Instance Modification request: %t", requestUpdate) 936 if requestUpdate { 937 log.Printf("[DEBUG] DB Instance Modification request: %s", req) 938 _, err := conn.ModifyDBInstance(req) 939 if err != nil { 940 return fmt.Errorf("Error modifying DB Instance %s: %s", d.Id(), err) 941 } 942 943 log.Println("[INFO] Waiting for DB Instance to be available") 944 945 stateConf := &resource.StateChangeConf{ 946 Pending: []string{"creating", "backing-up", "modifying", "resetting-master-credentials", 947 "maintenance", "renaming", "rebooting", "upgrading", "configuring-enhanced-monitoring"}, 948 Target: []string{"available"}, 949 Refresh: resourceAwsDbInstanceStateRefreshFunc(d, meta), 950 Timeout: 80 * time.Minute, 951 MinTimeout: 10 * time.Second, 952 Delay: 30 * time.Second, // Wait 30 secs before starting 953 } 954 955 // Wait, catching any errors 956 _, dbStateErr := stateConf.WaitForState() 957 if dbStateErr != nil { 958 return dbStateErr 959 } 960 } 961 962 // separate request to promote a database 963 if d.HasChange("replicate_source_db") { 964 if d.Get("replicate_source_db").(string) == "" { 965 // promote 966 opts := rds.PromoteReadReplicaInput{ 967 DBInstanceIdentifier: aws.String(d.Id()), 968 } 969 attr := d.Get("backup_retention_period") 970 opts.BackupRetentionPeriod = aws.Int64(int64(attr.(int))) 971 if attr, ok := d.GetOk("backup_window"); ok { 972 opts.PreferredBackupWindow = aws.String(attr.(string)) 973 } 974 _, err := conn.PromoteReadReplica(&opts) 975 if err != nil { 976 return fmt.Errorf("Error promoting database: %#v", err) 977 } 978 d.Set("replicate_source_db", "") 979 } else { 980 return fmt.Errorf("cannot elect new source database for replication") 981 } 982 } 983 984 if arn, err := buildRDSARN(d.Id(), meta.(*AWSClient).partition, meta.(*AWSClient).accountid, meta.(*AWSClient).region); err == nil { 985 if err := setTagsRDS(conn, d, arn); err != nil { 986 return err 987 } else { 988 d.SetPartial("tags") 989 } 990 } 991 d.Partial(false) 992 993 return resourceAwsDbInstanceRead(d, meta) 994 } 995 996 // resourceAwsDbInstanceRetrieve fetches DBInstance information from the AWS 997 // API. It returns an error if there is a communication problem or unexpected 998 // error with AWS. When the DBInstance is not found, it returns no error and a 999 // nil pointer. 1000 func resourceAwsDbInstanceRetrieve( 1001 d *schema.ResourceData, meta interface{}) (*rds.DBInstance, error) { 1002 conn := meta.(*AWSClient).rdsconn 1003 1004 opts := rds.DescribeDBInstancesInput{ 1005 DBInstanceIdentifier: aws.String(d.Id()), 1006 } 1007 1008 log.Printf("[DEBUG] DB Instance describe configuration: %#v", opts) 1009 1010 resp, err := conn.DescribeDBInstances(&opts) 1011 if err != nil { 1012 dbinstanceerr, ok := err.(awserr.Error) 1013 if ok && dbinstanceerr.Code() == "DBInstanceNotFound" { 1014 return nil, nil 1015 } 1016 return nil, fmt.Errorf("Error retrieving DB Instances: %s", err) 1017 } 1018 1019 if len(resp.DBInstances) != 1 || 1020 *resp.DBInstances[0].DBInstanceIdentifier != d.Id() { 1021 if err != nil { 1022 return nil, nil 1023 } 1024 } 1025 1026 return resp.DBInstances[0], nil 1027 } 1028 1029 func resourceAwsDbInstanceImport( 1030 d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { 1031 // Neither skip_final_snapshot nor final_snapshot_identifier can be fetched 1032 // from any API call, so we need to default skip_final_snapshot to true so 1033 // that final_snapshot_identifier is not required 1034 d.Set("skip_final_snapshot", true) 1035 return []*schema.ResourceData{d}, nil 1036 } 1037 1038 func resourceAwsDbInstanceStateRefreshFunc( 1039 d *schema.ResourceData, meta interface{}) resource.StateRefreshFunc { 1040 return func() (interface{}, string, error) { 1041 v, err := resourceAwsDbInstanceRetrieve(d, meta) 1042 1043 if err != nil { 1044 log.Printf("Error on retrieving DB Instance when waiting: %s", err) 1045 return nil, "", err 1046 } 1047 1048 if v == nil { 1049 return nil, "", nil 1050 } 1051 1052 if v.DBInstanceStatus != nil { 1053 log.Printf("[DEBUG] DB Instance status for instance %s: %s", d.Id(), *v.DBInstanceStatus) 1054 } 1055 1056 return v, *v.DBInstanceStatus, nil 1057 } 1058 } 1059 1060 func buildRDSARN(identifier, partition, accountid, region string) (string, error) { 1061 if partition == "" { 1062 return "", fmt.Errorf("Unable to construct RDS ARN because of missing AWS partition") 1063 } 1064 if accountid == "" { 1065 return "", fmt.Errorf("Unable to construct RDS ARN because of missing AWS Account ID") 1066 } 1067 arn := fmt.Sprintf("arn:%s:rds:%s:%s:db:%s", partition, region, accountid, identifier) 1068 return arn, nil 1069 }