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