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