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