github.com/recobe182/terraform@v0.8.5-0.20170117231232-49ab22a935b7/builtin/providers/aws/resource_aws_rds_cluster_instance_test.go (about)

     1  package aws
     2  
     3  import (
     4  	"fmt"
     5  	"regexp"
     6  	"strings"
     7  	"testing"
     8  	"time"
     9  
    10  	"github.com/hashicorp/terraform/helper/acctest"
    11  	"github.com/hashicorp/terraform/helper/resource"
    12  	"github.com/hashicorp/terraform/terraform"
    13  
    14  	"github.com/aws/aws-sdk-go/aws"
    15  	"github.com/aws/aws-sdk-go/aws/awserr"
    16  	"github.com/aws/aws-sdk-go/service/rds"
    17  )
    18  
    19  func TestAccAWSRDSClusterInstance_basic(t *testing.T) {
    20  	var v rds.DBInstance
    21  
    22  	resource.Test(t, resource.TestCase{
    23  		PreCheck:     func() { testAccPreCheck(t) },
    24  		Providers:    testAccProviders,
    25  		CheckDestroy: testAccCheckAWSClusterDestroy,
    26  		Steps: []resource.TestStep{
    27  			{
    28  				Config: testAccAWSClusterInstanceConfig(acctest.RandInt()),
    29  				Check: resource.ComposeTestCheckFunc(
    30  					testAccCheckAWSClusterInstanceExists("aws_rds_cluster_instance.cluster_instances", &v),
    31  					testAccCheckAWSDBClusterInstanceAttributes(&v),
    32  					resource.TestCheckResourceAttr("aws_rds_cluster_instance.cluster_instances", "auto_minor_version_upgrade", "true"),
    33  				),
    34  			},
    35  			{
    36  				Config: testAccAWSClusterInstanceConfigModified(acctest.RandInt()),
    37  				Check: resource.ComposeTestCheckFunc(
    38  					testAccCheckAWSClusterInstanceExists("aws_rds_cluster_instance.cluster_instances", &v),
    39  					testAccCheckAWSDBClusterInstanceAttributes(&v),
    40  					resource.TestCheckResourceAttr("aws_rds_cluster_instance.cluster_instances", "auto_minor_version_upgrade", "false"),
    41  				),
    42  			},
    43  		},
    44  	})
    45  }
    46  
    47  func TestAccAWSRDSClusterInstance_kmsKey(t *testing.T) {
    48  	var v rds.DBInstance
    49  	keyRegex := regexp.MustCompile("^arn:aws:kms:")
    50  
    51  	resource.Test(t, resource.TestCase{
    52  		PreCheck:     func() { testAccPreCheck(t) },
    53  		Providers:    testAccProviders,
    54  		CheckDestroy: testAccCheckAWSClusterDestroy,
    55  		Steps: []resource.TestStep{
    56  			{
    57  				Config: testAccAWSClusterInstanceConfigKmsKey(acctest.RandInt()),
    58  				Check: resource.ComposeTestCheckFunc(
    59  					testAccCheckAWSClusterInstanceExists("aws_rds_cluster_instance.cluster_instances", &v),
    60  					resource.TestMatchResourceAttr(
    61  						"aws_rds_cluster_instance.cluster_instances", "kms_key_id", keyRegex),
    62  				),
    63  			},
    64  		},
    65  	})
    66  }
    67  
    68  // https://github.com/hashicorp/terraform/issues/5350
    69  func TestAccAWSRDSClusterInstance_disappears(t *testing.T) {
    70  	var v rds.DBInstance
    71  
    72  	resource.Test(t, resource.TestCase{
    73  		PreCheck:     func() { testAccPreCheck(t) },
    74  		Providers:    testAccProviders,
    75  		CheckDestroy: testAccCheckAWSClusterDestroy,
    76  		Steps: []resource.TestStep{
    77  			{
    78  				Config: testAccAWSClusterInstanceConfig(acctest.RandInt()),
    79  				Check: resource.ComposeTestCheckFunc(
    80  					testAccCheckAWSClusterInstanceExists("aws_rds_cluster_instance.cluster_instances", &v),
    81  					testAccAWSClusterInstanceDisappears(&v),
    82  				),
    83  				// A non-empty plan is what we want. A crash is what we don't want. :)
    84  				ExpectNonEmptyPlan: true,
    85  			},
    86  		},
    87  	})
    88  }
    89  
    90  func testAccCheckAWSClusterInstanceDestroy(s *terraform.State) error {
    91  	for _, rs := range s.RootModule().Resources {
    92  		if rs.Type != "aws_rds_cluster" {
    93  			continue
    94  		}
    95  
    96  		// Try to find the Group
    97  		conn := testAccProvider.Meta().(*AWSClient).rdsconn
    98  		var err error
    99  		resp, err := conn.DescribeDBInstances(
   100  			&rds.DescribeDBInstancesInput{
   101  				DBInstanceIdentifier: aws.String(rs.Primary.ID),
   102  			})
   103  
   104  		if err == nil {
   105  			if len(resp.DBInstances) != 0 &&
   106  				*resp.DBInstances[0].DBInstanceIdentifier == rs.Primary.ID {
   107  				return fmt.Errorf("DB Cluster Instance %s still exists", rs.Primary.ID)
   108  			}
   109  		}
   110  
   111  		// Return nil if the Cluster Instance is already destroyed
   112  		if awsErr, ok := err.(awserr.Error); ok {
   113  			if awsErr.Code() == "DBInstanceNotFound" {
   114  				return nil
   115  			}
   116  		}
   117  
   118  		return err
   119  
   120  	}
   121  
   122  	return nil
   123  }
   124  
   125  func testAccCheckAWSDBClusterInstanceAttributes(v *rds.DBInstance) resource.TestCheckFunc {
   126  	return func(s *terraform.State) error {
   127  
   128  		if *v.Engine != "aurora" {
   129  			return fmt.Errorf("bad engine, expected \"aurora\": %#v", *v.Engine)
   130  		}
   131  
   132  		if !strings.HasPrefix(*v.DBClusterIdentifier, "tf-aurora-cluster") {
   133  			return fmt.Errorf("Bad Cluster Identifier prefix:\nexpected: %s\ngot: %s", "tf-aurora-cluster", *v.DBClusterIdentifier)
   134  		}
   135  
   136  		return nil
   137  	}
   138  }
   139  
   140  func testAccAWSClusterInstanceDisappears(v *rds.DBInstance) resource.TestCheckFunc {
   141  	return func(s *terraform.State) error {
   142  		conn := testAccProvider.Meta().(*AWSClient).rdsconn
   143  		opts := &rds.DeleteDBInstanceInput{
   144  			DBInstanceIdentifier: v.DBInstanceIdentifier,
   145  		}
   146  		if _, err := conn.DeleteDBInstance(opts); err != nil {
   147  			return err
   148  		}
   149  		return resource.Retry(40*time.Minute, func() *resource.RetryError {
   150  			opts := &rds.DescribeDBInstancesInput{
   151  				DBInstanceIdentifier: v.DBInstanceIdentifier,
   152  			}
   153  			_, err := conn.DescribeDBInstances(opts)
   154  			if err != nil {
   155  				dbinstanceerr, ok := err.(awserr.Error)
   156  				if ok && dbinstanceerr.Code() == "DBInstanceNotFound" {
   157  					return nil
   158  				}
   159  				return resource.NonRetryableError(
   160  					fmt.Errorf("Error retrieving DB Instances: %s", err))
   161  			}
   162  			return resource.RetryableError(fmt.Errorf(
   163  				"Waiting for instance to be deleted: %v", v.DBInstanceIdentifier))
   164  		})
   165  	}
   166  }
   167  
   168  func testAccCheckAWSClusterInstanceExists(n string, v *rds.DBInstance) resource.TestCheckFunc {
   169  	return func(s *terraform.State) error {
   170  		rs, ok := s.RootModule().Resources[n]
   171  		if !ok {
   172  			return fmt.Errorf("Not found: %s", n)
   173  		}
   174  
   175  		if rs.Primary.ID == "" {
   176  			return fmt.Errorf("No DB Instance ID is set")
   177  		}
   178  
   179  		conn := testAccProvider.Meta().(*AWSClient).rdsconn
   180  		resp, err := conn.DescribeDBInstances(&rds.DescribeDBInstancesInput{
   181  			DBInstanceIdentifier: aws.String(rs.Primary.ID),
   182  		})
   183  
   184  		if err != nil {
   185  			return err
   186  		}
   187  
   188  		for _, d := range resp.DBInstances {
   189  			if *d.DBInstanceIdentifier == rs.Primary.ID {
   190  				*v = *d
   191  				return nil
   192  			}
   193  		}
   194  
   195  		return fmt.Errorf("DB Cluster (%s) not found", rs.Primary.ID)
   196  	}
   197  }
   198  
   199  func TestAccAWSRDSClusterInstance_withInstanceEnhancedMonitor(t *testing.T) {
   200  	var v rds.DBInstance
   201  
   202  	resource.Test(t, resource.TestCase{
   203  		PreCheck:     func() { testAccPreCheck(t) },
   204  		Providers:    testAccProviders,
   205  		CheckDestroy: testAccCheckAWSClusterDestroy,
   206  		Steps: []resource.TestStep{
   207  			{
   208  				Config: testAccAWSClusterInstanceEnhancedMonitor(acctest.RandInt()),
   209  				Check: resource.ComposeTestCheckFunc(
   210  					testAccCheckAWSClusterInstanceExists("aws_rds_cluster_instance.cluster_instances", &v),
   211  					testAccCheckAWSDBClusterInstanceAttributes(&v),
   212  				),
   213  			},
   214  		},
   215  	})
   216  }
   217  
   218  // Add some random to the name, to avoid collision
   219  func testAccAWSClusterInstanceConfig(n int) string {
   220  	return fmt.Sprintf(`
   221  resource "aws_rds_cluster" "default" {
   222    cluster_identifier = "tf-aurora-cluster-test-%d"
   223    availability_zones = ["us-west-2a", "us-west-2b", "us-west-2c"]
   224    database_name      = "mydb"
   225    master_username    = "foo"
   226    master_password    = "mustbeeightcharaters"
   227  }
   228  
   229  resource "aws_rds_cluster_instance" "cluster_instances" {
   230    identifier              = "tf-cluster-instance-%d"
   231    cluster_identifier      = "${aws_rds_cluster.default.id}"
   232    instance_class          = "db.r3.large"
   233    db_parameter_group_name = "${aws_db_parameter_group.bar.name}"
   234    promotion_tier          = "3"
   235  }
   236  
   237  resource "aws_db_parameter_group" "bar" {
   238    name   = "tfcluster-test-group-%d"
   239    family = "aurora5.6"
   240  
   241    parameter {
   242      name         = "back_log"
   243      value        = "32767"
   244      apply_method = "pending-reboot"
   245    }
   246  
   247    tags {
   248      foo = "bar"
   249    }
   250  }
   251  `, n, n, n)
   252  }
   253  
   254  func testAccAWSClusterInstanceConfigModified(n int) string {
   255  	return fmt.Sprintf(`
   256  resource "aws_rds_cluster" "default" {
   257    cluster_identifier = "tf-aurora-cluster-test-%d"
   258    availability_zones = ["us-west-2a", "us-west-2b", "us-west-2c"]
   259    database_name      = "mydb"
   260    master_username    = "foo"
   261    master_password    = "mustbeeightcharaters"
   262  }
   263  
   264  resource "aws_rds_cluster_instance" "cluster_instances" {
   265    identifier                 = "tf-cluster-instance-%d"
   266    cluster_identifier         = "${aws_rds_cluster.default.id}"
   267    instance_class             = "db.r3.large"
   268    db_parameter_group_name    = "${aws_db_parameter_group.bar.name}"
   269    auto_minor_version_upgrade = false
   270    promotion_tier             = "3"
   271  }
   272  
   273  resource "aws_db_parameter_group" "bar" {
   274    name   = "tfcluster-test-group-%d"
   275    family = "aurora5.6"
   276  
   277    parameter {
   278      name         = "back_log"
   279      value        = "32767"
   280      apply_method = "pending-reboot"
   281    }
   282  
   283    tags {
   284      foo = "bar"
   285    }
   286  }
   287  `, n, n, n)
   288  }
   289  
   290  func testAccAWSClusterInstanceConfigKmsKey(n int) string {
   291  	return fmt.Sprintf(`
   292  
   293  resource "aws_kms_key" "foo" {
   294      description = "Terraform acc test %d"
   295      policy = <<POLICY
   296  {
   297    "Version": "2012-10-17",
   298    "Id": "kms-tf-1",
   299    "Statement": [
   300      {
   301        "Sid": "Enable IAM User Permissions",
   302        "Effect": "Allow",
   303        "Principal": {
   304          "AWS": "*"
   305        },
   306        "Action": "kms:*",
   307        "Resource": "*"
   308      }
   309    ]
   310  }
   311  POLICY
   312  }
   313  
   314  resource "aws_rds_cluster" "default" {
   315    cluster_identifier = "tf-aurora-cluster-test-%d"
   316    availability_zones = ["us-west-2a", "us-west-2b", "us-west-2c"]
   317    database_name      = "mydb"
   318    master_username    = "foo"
   319    master_password    = "mustbeeightcharaters"
   320    storage_encrypted = true
   321    kms_key_id = "${aws_kms_key.foo.arn}"
   322  }
   323  
   324  resource "aws_rds_cluster_instance" "cluster_instances" {
   325    identifier              = "tf-cluster-instance-%d"
   326    cluster_identifier      = "${aws_rds_cluster.default.id}"
   327    instance_class          = "db.r3.large"
   328    db_parameter_group_name = "${aws_db_parameter_group.bar.name}"
   329  }
   330  
   331  resource "aws_db_parameter_group" "bar" {
   332    name   = "tfcluster-test-group-%d"
   333    family = "aurora5.6"
   334  
   335    parameter {
   336      name         = "back_log"
   337      value        = "32767"
   338      apply_method = "pending-reboot"
   339    }
   340  
   341    tags {
   342      foo = "bar"
   343    }
   344  }
   345  `, n, n, n, n)
   346  }
   347  
   348  func testAccAWSClusterInstanceEnhancedMonitor(n int) string {
   349  	return fmt.Sprintf(`
   350  resource "aws_rds_cluster" "default" {
   351    cluster_identifier = "tf-aurora-cluster-test-%d"
   352    availability_zones = ["us-west-2a", "us-west-2b", "us-west-2c"]
   353    database_name      = "mydb"
   354    master_username    = "foo"
   355    master_password    = "mustbeeightcharaters"
   356  }
   357  
   358  resource "aws_rds_cluster_instance" "cluster_instances" {
   359    identifier              = "tf-cluster-instance-%d"
   360    cluster_identifier      = "${aws_rds_cluster.default.id}"
   361    instance_class          = "db.r3.large"
   362    db_parameter_group_name = "${aws_db_parameter_group.bar.name}"
   363    monitoring_interval     = "60"
   364    monitoring_role_arn     = "${aws_iam_role.tf_enhanced_monitor_role.arn}"
   365  }
   366  
   367  resource "aws_iam_role" "tf_enhanced_monitor_role" {
   368      name = "tf_enhanced_monitor_role-%d"
   369      assume_role_policy = <<EOF
   370  {
   371              "Version": "2012-10-17",
   372              "Statement": [
   373                  {
   374                      "Action": "sts:AssumeRole",
   375                      "Principal": {
   376                          "Service": "monitoring.rds.amazonaws.com"
   377                      },
   378                      "Effect": "Allow",
   379                      "Sid": ""
   380                  }
   381              ]
   382     }
   383  EOF
   384  }
   385  
   386  resource "aws_iam_policy_attachment" "rds_m_attach" {
   387      name = "AmazonRDSEnhancedMonitoringRole"
   388      roles = ["${aws_iam_role.tf_enhanced_monitor_role.name}"]
   389      policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonRDSEnhancedMonitoringRole"
   390  }
   391  
   392  resource "aws_db_parameter_group" "bar" {
   393    name   = "tfcluster-test-group-%d"
   394    family = "aurora5.6"
   395  
   396    parameter {
   397      name         = "back_log"
   398      value        = "32767"
   399      apply_method = "pending-reboot"
   400    }
   401  
   402    tags {
   403      foo = "bar"
   404    }
   405  }
   406  `, n, n, n, n)
   407  }