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