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