github.com/minamijoyo/terraform@v0.7.8-0.20161029001309-18b3736ba44b/builtin/providers/aws/resource_aws_db_instance_test.go (about)

     1  package aws
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"regexp"
     7  	"strings"
     8  
     9  	"math/rand"
    10  	"testing"
    11  	"time"
    12  
    13  	"github.com/hashicorp/terraform/helper/acctest"
    14  	"github.com/hashicorp/terraform/helper/resource"
    15  	"github.com/hashicorp/terraform/terraform"
    16  
    17  	"github.com/aws/aws-sdk-go/aws"
    18  	"github.com/aws/aws-sdk-go/aws/awserr"
    19  	"github.com/aws/aws-sdk-go/service/rds"
    20  )
    21  
    22  func TestAccAWSDBInstance_basic(t *testing.T) {
    23  	var v rds.DBInstance
    24  
    25  	resource.Test(t, resource.TestCase{
    26  		PreCheck:     func() { testAccPreCheck(t) },
    27  		Providers:    testAccProviders,
    28  		CheckDestroy: testAccCheckAWSDBInstanceDestroy,
    29  		Steps: []resource.TestStep{
    30  			resource.TestStep{
    31  				Config: testAccAWSDBInstanceConfig,
    32  				Check: resource.ComposeTestCheckFunc(
    33  					testAccCheckAWSDBInstanceExists("aws_db_instance.bar", &v),
    34  					testAccCheckAWSDBInstanceAttributes(&v),
    35  					resource.TestCheckResourceAttr(
    36  						"aws_db_instance.bar", "allocated_storage", "10"),
    37  					resource.TestCheckResourceAttr(
    38  						"aws_db_instance.bar", "engine", "mysql"),
    39  					resource.TestCheckResourceAttr(
    40  						"aws_db_instance.bar", "license_model", "general-public-license"),
    41  					resource.TestCheckResourceAttr(
    42  						"aws_db_instance.bar", "instance_class", "db.t1.micro"),
    43  					resource.TestCheckResourceAttr(
    44  						"aws_db_instance.bar", "name", "baz"),
    45  					resource.TestCheckResourceAttr(
    46  						"aws_db_instance.bar", "username", "foo"),
    47  					resource.TestCheckResourceAttr(
    48  						"aws_db_instance.bar", "parameter_group_name", "default.mysql5.6"),
    49  				),
    50  			},
    51  		},
    52  	})
    53  }
    54  
    55  func TestAccAWSDBInstance_kmsKey(t *testing.T) {
    56  	var v rds.DBInstance
    57  	keyRegex := regexp.MustCompile("^arn:aws:kms:")
    58  
    59  	ri := rand.New(rand.NewSource(time.Now().UnixNano())).Int()
    60  	config := fmt.Sprintf(testAccAWSDBInstanceConfigKmsKeyId, ri)
    61  
    62  	resource.Test(t, resource.TestCase{
    63  		PreCheck:     func() { testAccPreCheck(t) },
    64  		Providers:    testAccProviders,
    65  		CheckDestroy: testAccCheckAWSDBInstanceDestroy,
    66  		Steps: []resource.TestStep{
    67  			resource.TestStep{
    68  				Config: config,
    69  				Check: resource.ComposeTestCheckFunc(
    70  					testAccCheckAWSDBInstanceExists("aws_db_instance.bar", &v),
    71  					testAccCheckAWSDBInstanceAttributes(&v),
    72  					resource.TestMatchResourceAttr(
    73  						"aws_db_instance.bar", "kms_key_id", keyRegex),
    74  				),
    75  			},
    76  		},
    77  	})
    78  }
    79  
    80  func TestAccAWSDBInstance_optionGroup(t *testing.T) {
    81  	var v rds.DBInstance
    82  
    83  	resource.Test(t, resource.TestCase{
    84  		PreCheck:     func() { testAccPreCheck(t) },
    85  		Providers:    testAccProviders,
    86  		CheckDestroy: testAccCheckAWSDBInstanceDestroy,
    87  		Steps: []resource.TestStep{
    88  			resource.TestStep{
    89  				Config: testAccAWSDBInstanceConfigWithOptionGroup,
    90  				Check: resource.ComposeTestCheckFunc(
    91  					testAccCheckAWSDBInstanceExists("aws_db_instance.bar", &v),
    92  					testAccCheckAWSDBInstanceAttributes(&v),
    93  					resource.TestCheckResourceAttr(
    94  						"aws_db_instance.bar", "option_group_name", "option-group-test-terraform"),
    95  				),
    96  			},
    97  		},
    98  	})
    99  }
   100  
   101  func TestAccAWSDBInstanceReplica(t *testing.T) {
   102  	var s, r rds.DBInstance
   103  
   104  	resource.Test(t, resource.TestCase{
   105  		PreCheck:     func() { testAccPreCheck(t) },
   106  		Providers:    testAccProviders,
   107  		CheckDestroy: testAccCheckAWSDBInstanceDestroy,
   108  		Steps: []resource.TestStep{
   109  			resource.TestStep{
   110  				Config: testAccReplicaInstanceConfig(rand.New(rand.NewSource(time.Now().UnixNano())).Int()),
   111  				Check: resource.ComposeTestCheckFunc(
   112  					testAccCheckAWSDBInstanceExists("aws_db_instance.bar", &s),
   113  					testAccCheckAWSDBInstanceExists("aws_db_instance.replica", &r),
   114  					testAccCheckAWSDBInstanceReplicaAttributes(&s, &r),
   115  				),
   116  			},
   117  		},
   118  	})
   119  }
   120  
   121  func TestAccAWSDBInstanceSnapshot(t *testing.T) {
   122  	var snap rds.DBInstance
   123  
   124  	resource.Test(t, resource.TestCase{
   125  		PreCheck:  func() { testAccPreCheck(t) },
   126  		Providers: testAccProviders,
   127  		// testAccCheckAWSDBInstanceSnapshot verifies a database snapshot is
   128  		// created, and subequently deletes it
   129  		CheckDestroy: testAccCheckAWSDBInstanceSnapshot,
   130  		Steps: []resource.TestStep{
   131  			resource.TestStep{
   132  				Config: testAccSnapshotInstanceConfig(),
   133  				Check: resource.ComposeTestCheckFunc(
   134  					testAccCheckAWSDBInstanceExists("aws_db_instance.snapshot", &snap),
   135  				),
   136  			},
   137  		},
   138  	})
   139  }
   140  
   141  func TestAccAWSDBInstanceNoSnapshot(t *testing.T) {
   142  	var nosnap rds.DBInstance
   143  
   144  	resource.Test(t, resource.TestCase{
   145  		PreCheck:     func() { testAccPreCheck(t) },
   146  		Providers:    testAccProviders,
   147  		CheckDestroy: testAccCheckAWSDBInstanceNoSnapshot,
   148  		Steps: []resource.TestStep{
   149  			resource.TestStep{
   150  				Config: testAccNoSnapshotInstanceConfig(),
   151  				Check: resource.ComposeTestCheckFunc(
   152  					testAccCheckAWSDBInstanceExists("aws_db_instance.no_snapshot", &nosnap),
   153  				),
   154  			},
   155  		},
   156  	})
   157  }
   158  
   159  func TestAccAWSDBInstance_enhancedMonitoring(t *testing.T) {
   160  	var dbInstance rds.DBInstance
   161  	rName := acctest.RandString(5)
   162  
   163  	resource.Test(t, resource.TestCase{
   164  		PreCheck:     func() { testAccPreCheck(t) },
   165  		Providers:    testAccProviders,
   166  		CheckDestroy: testAccCheckAWSDBInstanceNoSnapshot,
   167  		Steps: []resource.TestStep{
   168  			resource.TestStep{
   169  				Config: testAccSnapshotInstanceConfig_enhancedMonitoring(rName),
   170  				Check: resource.ComposeTestCheckFunc(
   171  					testAccCheckAWSDBInstanceExists("aws_db_instance.enhanced_monitoring", &dbInstance),
   172  					resource.TestCheckResourceAttr(
   173  						"aws_db_instance.enhanced_monitoring", "monitoring_interval", "5"),
   174  				),
   175  			},
   176  		},
   177  	})
   178  }
   179  
   180  // Regression test for https://github.com/hashicorp/terraform/issues/3760 .
   181  // We apply a plan, then change just the iops. If the apply succeeds, we
   182  // consider this a pass, as before in 3760 the request would fail
   183  func TestAccAWS_separate_DBInstance_iops_update(t *testing.T) {
   184  	var v rds.DBInstance
   185  
   186  	rName := acctest.RandString(5)
   187  
   188  	resource.Test(t, resource.TestCase{
   189  		PreCheck:     func() { testAccPreCheck(t) },
   190  		Providers:    testAccProviders,
   191  		CheckDestroy: testAccCheckAWSDBInstanceDestroy,
   192  		Steps: []resource.TestStep{
   193  			resource.TestStep{
   194  				Config: testAccSnapshotInstanceConfig_iopsUpdate(rName, 1000),
   195  				Check: resource.ComposeTestCheckFunc(
   196  					testAccCheckAWSDBInstanceExists("aws_db_instance.bar", &v),
   197  					testAccCheckAWSDBInstanceAttributes(&v),
   198  				),
   199  			},
   200  
   201  			resource.TestStep{
   202  				Config: testAccSnapshotInstanceConfig_iopsUpdate(rName, 2000),
   203  				Check: resource.ComposeTestCheckFunc(
   204  					testAccCheckAWSDBInstanceExists("aws_db_instance.bar", &v),
   205  					testAccCheckAWSDBInstanceAttributes(&v),
   206  				),
   207  			},
   208  		},
   209  	})
   210  }
   211  
   212  func TestAccAWSDBInstance_portUpdate(t *testing.T) {
   213  	var v rds.DBInstance
   214  
   215  	rName := acctest.RandString(5)
   216  
   217  	resource.Test(t, resource.TestCase{
   218  		PreCheck:     func() { testAccPreCheck(t) },
   219  		Providers:    testAccProviders,
   220  		CheckDestroy: testAccCheckAWSDBInstanceDestroy,
   221  		Steps: []resource.TestStep{
   222  			resource.TestStep{
   223  				Config: testAccSnapshotInstanceConfig_mysqlPort(rName),
   224  				Check: resource.ComposeTestCheckFunc(
   225  					testAccCheckAWSDBInstanceExists("aws_db_instance.bar", &v),
   226  					resource.TestCheckResourceAttr(
   227  						"aws_db_instance.bar", "port", "3306"),
   228  				),
   229  			},
   230  
   231  			resource.TestStep{
   232  				Config: testAccSnapshotInstanceConfig_updateMysqlPort(rName),
   233  				Check: resource.ComposeTestCheckFunc(
   234  					testAccCheckAWSDBInstanceExists("aws_db_instance.bar", &v),
   235  					resource.TestCheckResourceAttr(
   236  						"aws_db_instance.bar", "port", "3305"),
   237  				),
   238  			},
   239  		},
   240  	})
   241  }
   242  
   243  func testAccCheckAWSDBInstanceDestroy(s *terraform.State) error {
   244  	conn := testAccProvider.Meta().(*AWSClient).rdsconn
   245  
   246  	for _, rs := range s.RootModule().Resources {
   247  		if rs.Type != "aws_db_instance" {
   248  			continue
   249  		}
   250  
   251  		// Try to find the Group
   252  		var err error
   253  		resp, err := conn.DescribeDBInstances(
   254  			&rds.DescribeDBInstancesInput{
   255  				DBInstanceIdentifier: aws.String(rs.Primary.ID),
   256  			})
   257  
   258  		if ae, ok := err.(awserr.Error); ok && ae.Code() == "DBInstanceNotFound" {
   259  			continue
   260  		}
   261  
   262  		if err == nil {
   263  			if len(resp.DBInstances) != 0 &&
   264  				*resp.DBInstances[0].DBInstanceIdentifier == rs.Primary.ID {
   265  				return fmt.Errorf("DB Instance still exists")
   266  			}
   267  		}
   268  
   269  		// Verify the error
   270  		newerr, ok := err.(awserr.Error)
   271  		if !ok {
   272  			return err
   273  		}
   274  		if newerr.Code() != "DBInstanceNotFound" {
   275  			return err
   276  		}
   277  	}
   278  
   279  	return nil
   280  }
   281  
   282  func testAccCheckAWSDBInstanceAttributes(v *rds.DBInstance) resource.TestCheckFunc {
   283  	return func(s *terraform.State) error {
   284  
   285  		if *v.Engine != "mysql" {
   286  			return fmt.Errorf("bad engine: %#v", *v.Engine)
   287  		}
   288  
   289  		if *v.EngineVersion == "" {
   290  			return fmt.Errorf("bad engine_version: %#v", *v.EngineVersion)
   291  		}
   292  
   293  		if *v.BackupRetentionPeriod != 0 {
   294  			return fmt.Errorf("bad backup_retention_period: %#v", *v.BackupRetentionPeriod)
   295  		}
   296  
   297  		return nil
   298  	}
   299  }
   300  
   301  func testAccCheckAWSDBInstanceReplicaAttributes(source, replica *rds.DBInstance) resource.TestCheckFunc {
   302  	return func(s *terraform.State) error {
   303  
   304  		if replica.ReadReplicaSourceDBInstanceIdentifier != nil && *replica.ReadReplicaSourceDBInstanceIdentifier != *source.DBInstanceIdentifier {
   305  			return fmt.Errorf("bad source identifier for replica, expected: '%s', got: '%s'", *source.DBInstanceIdentifier, *replica.ReadReplicaSourceDBInstanceIdentifier)
   306  		}
   307  
   308  		return nil
   309  	}
   310  }
   311  
   312  func testAccCheckAWSDBInstanceSnapshot(s *terraform.State) error {
   313  	conn := testAccProvider.Meta().(*AWSClient).rdsconn
   314  
   315  	for _, rs := range s.RootModule().Resources {
   316  		if rs.Type != "aws_db_instance" {
   317  			continue
   318  		}
   319  
   320  		var err error
   321  		resp, err := conn.DescribeDBInstances(
   322  			&rds.DescribeDBInstancesInput{
   323  				DBInstanceIdentifier: aws.String(rs.Primary.ID),
   324  			})
   325  
   326  		if err != nil {
   327  			newerr, _ := err.(awserr.Error)
   328  			if newerr.Code() != "DBInstanceNotFound" {
   329  				return err
   330  			}
   331  
   332  		} else {
   333  			if len(resp.DBInstances) != 0 &&
   334  				*resp.DBInstances[0].DBInstanceIdentifier == rs.Primary.ID {
   335  				return fmt.Errorf("DB Instance still exists")
   336  			}
   337  		}
   338  
   339  		log.Printf("[INFO] Trying to locate the DBInstance Final Snapshot")
   340  		snapshot_identifier := "foobarbaz-test-terraform-final-snapshot-1"
   341  		_, snapErr := conn.DescribeDBSnapshots(
   342  			&rds.DescribeDBSnapshotsInput{
   343  				DBSnapshotIdentifier: aws.String(snapshot_identifier),
   344  			})
   345  
   346  		if snapErr != nil {
   347  			newerr, _ := snapErr.(awserr.Error)
   348  			if newerr.Code() == "DBSnapshotNotFound" {
   349  				return fmt.Errorf("Snapshot %s not found", snapshot_identifier)
   350  			}
   351  		} else { // snapshot was found,
   352  			// verify we have the tags copied to the snapshot
   353  			instanceARN, err := buildRDSARN(snapshot_identifier, testAccProvider.Meta().(*AWSClient).partition, testAccProvider.Meta().(*AWSClient).accountid, testAccProvider.Meta().(*AWSClient).region)
   354  			// tags have a different ARN, just swapping :db: for :snapshot:
   355  			tagsARN := strings.Replace(instanceARN, ":db:", ":snapshot:", 1)
   356  			if err != nil {
   357  				return fmt.Errorf("Error building ARN for tags check with ARN (%s): %s", tagsARN, err)
   358  			}
   359  			resp, err := conn.ListTagsForResource(&rds.ListTagsForResourceInput{
   360  				ResourceName: aws.String(tagsARN),
   361  			})
   362  			if err != nil {
   363  				return fmt.Errorf("Error retrieving tags for ARN (%s): %s", tagsARN, err)
   364  			}
   365  
   366  			if resp.TagList == nil || len(resp.TagList) == 0 {
   367  				return fmt.Errorf("Tag list is nil or zero: %s", resp.TagList)
   368  			}
   369  
   370  			var found bool
   371  			for _, t := range resp.TagList {
   372  				if *t.Key == "Name" && *t.Value == "tf-tags-db" {
   373  					found = true
   374  				}
   375  			}
   376  			if !found {
   377  				return fmt.Errorf("Expected to find tag Name (%s), but wasn't found. Tags: %s", "tf-tags-db", resp.TagList)
   378  			}
   379  			// end tag search
   380  
   381  			log.Printf("[INFO] Deleting the Snapshot %s", snapshot_identifier)
   382  			_, snapDeleteErr := conn.DeleteDBSnapshot(
   383  				&rds.DeleteDBSnapshotInput{
   384  					DBSnapshotIdentifier: aws.String(snapshot_identifier),
   385  				})
   386  			if snapDeleteErr != nil {
   387  				return err
   388  			}
   389  		} // end snapshot was found
   390  	}
   391  
   392  	return nil
   393  }
   394  
   395  func testAccCheckAWSDBInstanceNoSnapshot(s *terraform.State) error {
   396  	conn := testAccProvider.Meta().(*AWSClient).rdsconn
   397  
   398  	for _, rs := range s.RootModule().Resources {
   399  		if rs.Type != "aws_db_instance" {
   400  			continue
   401  		}
   402  
   403  		var err error
   404  		resp, err := conn.DescribeDBInstances(
   405  			&rds.DescribeDBInstancesInput{
   406  				DBInstanceIdentifier: aws.String(rs.Primary.ID),
   407  			})
   408  
   409  		if err != nil {
   410  			newerr, _ := err.(awserr.Error)
   411  			if newerr.Code() != "DBInstanceNotFound" {
   412  				return err
   413  			}
   414  
   415  		} else {
   416  			if len(resp.DBInstances) != 0 &&
   417  				*resp.DBInstances[0].DBInstanceIdentifier == rs.Primary.ID {
   418  				return fmt.Errorf("DB Instance still exists")
   419  			}
   420  		}
   421  
   422  		snapshot_identifier := "foobarbaz-test-terraform-final-snapshot-2"
   423  		_, snapErr := conn.DescribeDBSnapshots(
   424  			&rds.DescribeDBSnapshotsInput{
   425  				DBSnapshotIdentifier: aws.String(snapshot_identifier),
   426  			})
   427  
   428  		if snapErr != nil {
   429  			newerr, _ := snapErr.(awserr.Error)
   430  			if newerr.Code() != "DBSnapshotNotFound" {
   431  				return fmt.Errorf("Snapshot %s found and it shouldn't have been", snapshot_identifier)
   432  			}
   433  		}
   434  	}
   435  
   436  	return nil
   437  }
   438  
   439  func testAccCheckAWSDBInstanceExists(n string, v *rds.DBInstance) resource.TestCheckFunc {
   440  	return func(s *terraform.State) error {
   441  		rs, ok := s.RootModule().Resources[n]
   442  		if !ok {
   443  			return fmt.Errorf("Not found: %s", n)
   444  		}
   445  
   446  		if rs.Primary.ID == "" {
   447  			return fmt.Errorf("No DB Instance ID is set")
   448  		}
   449  
   450  		conn := testAccProvider.Meta().(*AWSClient).rdsconn
   451  
   452  		opts := rds.DescribeDBInstancesInput{
   453  			DBInstanceIdentifier: aws.String(rs.Primary.ID),
   454  		}
   455  
   456  		resp, err := conn.DescribeDBInstances(&opts)
   457  
   458  		if err != nil {
   459  			return err
   460  		}
   461  
   462  		if len(resp.DBInstances) != 1 ||
   463  			*resp.DBInstances[0].DBInstanceIdentifier != rs.Primary.ID {
   464  			return fmt.Errorf("DB Instance not found")
   465  		}
   466  
   467  		*v = *resp.DBInstances[0]
   468  
   469  		return nil
   470  	}
   471  }
   472  
   473  // Database names cannot collide, and deletion takes so long, that making the
   474  // name a bit random helps so able we can kill a test that's just waiting for a
   475  // delete and not be blocked on kicking off another one.
   476  var testAccAWSDBInstanceConfig = `
   477  resource "aws_db_instance" "bar" {
   478  	allocated_storage = 10
   479  	engine = "MySQL"
   480  	engine_version = "5.6.21"
   481  	instance_class = "db.t1.micro"
   482  	name = "baz"
   483  	password = "barbarbarbar"
   484  	username = "foo"
   485  
   486  
   487  	# Maintenance Window is stored in lower case in the API, though not strictly 
   488  	# documented. Terraform will downcase this to match (as opposed to throw a 
   489  	# validation error).
   490  	maintenance_window = "Fri:09:00-Fri:09:30"
   491  
   492  	backup_retention_period = 0
   493  
   494  	parameter_group_name = "default.mysql5.6"
   495  }`
   496  
   497  var testAccAWSDBInstanceConfigKmsKeyId = `
   498  resource "aws_kms_key" "foo" {
   499      description = "Terraform acc test %s"
   500      policy = <<POLICY
   501  {
   502    "Version": "2012-10-17",
   503    "Id": "kms-tf-1",
   504    "Statement": [
   505      {
   506        "Sid": "Enable IAM User Permissions",
   507        "Effect": "Allow",
   508        "Principal": {
   509          "AWS": "*"
   510        },
   511        "Action": "kms:*",
   512        "Resource": "*"
   513      }
   514    ]
   515  }
   516  POLICY
   517  }
   518  
   519  resource "aws_db_instance" "bar" {
   520  	allocated_storage = 10
   521  	engine = "MySQL"
   522  	engine_version = "5.6.21"
   523  	instance_class = "db.m3.medium"
   524  	name = "baz"
   525  	password = "barbarbarbar"
   526  	username = "foo"
   527  
   528  
   529  	# Maintenance Window is stored in lower case in the API, though not strictly
   530  	# documented. Terraform will downcase this to match (as opposed to throw a
   531  	# validation error).
   532  	maintenance_window = "Fri:09:00-Fri:09:30"
   533  
   534  	backup_retention_period = 0
   535  	storage_encrypted = true
   536  	kms_key_id = "${aws_kms_key.foo.arn}"
   537  
   538  	parameter_group_name = "default.mysql5.6"
   539  }
   540  `
   541  
   542  var testAccAWSDBInstanceConfigWithOptionGroup = fmt.Sprintf(`
   543  
   544  resource "aws_db_option_group" "bar" {
   545  	name = "option-group-test-terraform"
   546  	option_group_description = "Test option group for terraform"
   547  	engine_name = "mysql"
   548  	major_engine_version = "5.6"
   549  }
   550  
   551  resource "aws_db_instance" "bar" {
   552  	identifier = "foobarbaz-test-terraform-%d"
   553  
   554  	allocated_storage = 10
   555  	engine = "MySQL"
   556  	instance_class = "db.m1.small"
   557  	name = "baz"
   558  	password = "barbarbarbar"
   559  	username = "foo"
   560  
   561  	backup_retention_period = 0
   562  
   563  	parameter_group_name = "default.mysql5.6"
   564  	option_group_name = "${aws_db_option_group.bar.name}"
   565  }`, acctest.RandInt())
   566  
   567  func testAccReplicaInstanceConfig(val int) string {
   568  	return fmt.Sprintf(`
   569  	resource "aws_db_instance" "bar" {
   570  		identifier = "foobarbaz-test-terraform-%d"
   571  
   572  		allocated_storage = 5
   573  		engine = "mysql"
   574  		engine_version = "5.6.21"
   575  		instance_class = "db.t1.micro"
   576  		name = "baz"
   577  		password = "barbarbarbar"
   578  		username = "foo"
   579  
   580  		backup_retention_period = 1
   581  
   582  		parameter_group_name = "default.mysql5.6"
   583  	}
   584  	
   585  	resource "aws_db_instance" "replica" {
   586  		identifier = "tf-replica-db-%d"
   587  		backup_retention_period = 0
   588  		replicate_source_db = "${aws_db_instance.bar.identifier}"
   589  		allocated_storage = "${aws_db_instance.bar.allocated_storage}"
   590  		engine = "${aws_db_instance.bar.engine}"
   591  		engine_version = "${aws_db_instance.bar.engine_version}"
   592  		instance_class = "${aws_db_instance.bar.instance_class}"
   593  		password = "${aws_db_instance.bar.password}"
   594  		username = "${aws_db_instance.bar.username}"
   595  		tags {
   596  			Name = "tf-replica-db"
   597  		}
   598  	}
   599  	`, val, val)
   600  }
   601  
   602  func testAccSnapshotInstanceConfig() string {
   603  	return fmt.Sprintf(`
   604  provider "aws" {
   605    region = "us-east-1"
   606  }
   607  resource "aws_db_instance" "snapshot" {
   608  	identifier = "tf-snapshot-%d"
   609  
   610  	allocated_storage = 5
   611  	engine = "mysql"
   612  	engine_version = "5.6.21"
   613  	instance_class = "db.t1.micro"
   614  	name = "baz"
   615  	password = "barbarbarbar"
   616  	username = "foo"
   617  	security_group_names = ["default"]
   618  	backup_retention_period = 1
   619  
   620  	publicly_accessible = true
   621  
   622  	parameter_group_name = "default.mysql5.6"
   623  
   624  	skip_final_snapshot = false
   625  	copy_tags_to_snapshot = true
   626  	final_snapshot_identifier = "foobarbaz-test-terraform-final-snapshot-1"
   627  	tags {
   628  		Name = "tf-tags-db"
   629  	}
   630  }`, acctest.RandInt())
   631  }
   632  
   633  func testAccNoSnapshotInstanceConfig() string {
   634  	return fmt.Sprintf(`
   635  provider "aws" {
   636    region = "us-east-1"
   637  }
   638  resource "aws_db_instance" "no_snapshot" {
   639  	identifier = "tf-test-%s"
   640  
   641  	allocated_storage = 5
   642  	engine = "mysql"
   643  	engine_version = "5.6.21"
   644  	instance_class = "db.t1.micro"
   645  	name = "baz"
   646  	password = "barbarbarbar"
   647  	publicly_accessible = true
   648  	username = "foo"
   649      security_group_names = ["default"]
   650  	backup_retention_period = 1
   651  
   652  	parameter_group_name = "default.mysql5.6"
   653  
   654  	skip_final_snapshot = true
   655  	final_snapshot_identifier = "foobarbaz-test-terraform-final-snapshot-2"
   656  }
   657  `, acctest.RandString(5))
   658  }
   659  
   660  func testAccSnapshotInstanceConfig_enhancedMonitoring(rName string) string {
   661  	return fmt.Sprintf(`
   662  resource "aws_iam_role" "enhanced_policy_role" {
   663      name = "enhanced-monitoring-role-%s"
   664      assume_role_policy = <<EOF
   665  {
   666    "Version": "2012-10-17",
   667    "Statement": [
   668      {
   669        "Sid": "",
   670        "Effect": "Allow",
   671        "Principal": {
   672          "Service": "monitoring.rds.amazonaws.com"
   673        },
   674        "Action": "sts:AssumeRole"
   675      }
   676    ]
   677  }
   678  EOF
   679  
   680  }
   681  
   682  resource "aws_iam_policy_attachment" "test-attach" {
   683      name = "enhanced-monitoring-attachment"
   684      roles = [
   685          "${aws_iam_role.enhanced_policy_role.name}",
   686      ]
   687  
   688      policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonRDSEnhancedMonitoringRole"
   689  }
   690  
   691  resource "aws_db_instance" "enhanced_monitoring" {
   692  	identifier = "foobarbaz-enhanced-monitoring-%s"
   693  	depends_on = ["aws_iam_policy_attachment.test-attach"]
   694  
   695  	allocated_storage = 5
   696  	engine = "mysql"
   697  	engine_version = "5.6.21"
   698  	instance_class = "db.m3.medium"
   699  	name = "baz"
   700  	password = "barbarbarbar"
   701  	username = "foo"
   702  	backup_retention_period = 1
   703  
   704  	parameter_group_name = "default.mysql5.6"
   705  
   706  	monitoring_role_arn = "${aws_iam_role.enhanced_policy_role.arn}"
   707  	monitoring_interval = "5"
   708  
   709  	skip_final_snapshot = true
   710  }`, rName, rName)
   711  }
   712  
   713  func testAccSnapshotInstanceConfig_iopsUpdate(rName string, iops int) string {
   714  	return fmt.Sprintf(`
   715  resource "aws_db_instance" "bar" {
   716    identifier           = "mydb-rds-%s"
   717    engine               = "mysql"
   718    engine_version       = "5.6.23"
   719    instance_class       = "db.t2.micro"
   720    name                 = "mydb"
   721    username             = "foo"
   722    password             = "barbarbar"
   723    parameter_group_name = "default.mysql5.6"
   724  
   725    apply_immediately = true
   726  
   727    storage_type      = "io1"
   728    allocated_storage = 200
   729    iops              = %d
   730  }`, rName, iops)
   731  }
   732  
   733  func testAccSnapshotInstanceConfig_mysqlPort(rName string) string {
   734  	return fmt.Sprintf(`
   735  resource "aws_db_instance" "bar" {
   736    identifier           = "mydb-rds-%s"
   737    engine               = "mysql"
   738    engine_version       = "5.6.23"
   739    instance_class       = "db.t2.micro"
   740    name                 = "mydb"
   741    username             = "foo"
   742    password             = "barbarbar"
   743    parameter_group_name = "default.mysql5.6"
   744    port = 3306
   745    allocated_storage = 10
   746  
   747    apply_immediately = true
   748  }`, rName)
   749  }
   750  
   751  func testAccSnapshotInstanceConfig_updateMysqlPort(rName string) string {
   752  	return fmt.Sprintf(`
   753  resource "aws_db_instance" "bar" {
   754    identifier           = "mydb-rds-%s"
   755    engine               = "mysql"
   756    engine_version       = "5.6.23"
   757    instance_class       = "db.t2.micro"
   758    name                 = "mydb"
   759    username             = "foo"
   760    password             = "barbarbar"
   761    parameter_group_name = "default.mysql5.6"
   762    port = 3305
   763    allocated_storage = 10
   764  
   765    apply_immediately = true
   766  }`, rName)
   767  }