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