github.com/richardbowden/terraform@v0.6.12-0.20160901200758-30ea22c25211/builtin/providers/aws/resource_aws_autoscaling_group_test.go (about)

     1  package aws
     2  
     3  import (
     4  	"fmt"
     5  	"reflect"
     6  	"regexp"
     7  	"sort"
     8  	"strings"
     9  	"testing"
    10  
    11  	"github.com/aws/aws-sdk-go/aws"
    12  	"github.com/aws/aws-sdk-go/aws/awserr"
    13  	"github.com/aws/aws-sdk-go/service/autoscaling"
    14  	"github.com/aws/aws-sdk-go/service/elbv2"
    15  	"github.com/hashicorp/terraform/helper/acctest"
    16  	"github.com/hashicorp/terraform/helper/resource"
    17  	"github.com/hashicorp/terraform/terraform"
    18  )
    19  
    20  func TestAccAWSAutoScalingGroup_basic(t *testing.T) {
    21  	var group autoscaling.Group
    22  	var lc autoscaling.LaunchConfiguration
    23  
    24  	randName := fmt.Sprintf("terraform-test-%s", acctest.RandString(10))
    25  
    26  	resource.Test(t, resource.TestCase{
    27  		PreCheck:        func() { testAccPreCheck(t) },
    28  		IDRefreshName:   "aws_autoscaling_group.bar",
    29  		IDRefreshIgnore: []string{"force_delete", "metrics_granularity", "wait_for_capacity_timeout"},
    30  		Providers:       testAccProviders,
    31  		CheckDestroy:    testAccCheckAWSAutoScalingGroupDestroy,
    32  		Steps: []resource.TestStep{
    33  			resource.TestStep{
    34  				Config: testAccAWSAutoScalingGroupConfig(randName),
    35  				Check: resource.ComposeTestCheckFunc(
    36  					testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
    37  					testAccCheckAWSAutoScalingGroupHealthyCapacity(&group, 2),
    38  					testAccCheckAWSAutoScalingGroupAttributes(&group, randName),
    39  					resource.TestCheckResourceAttr(
    40  						"aws_autoscaling_group.bar", "availability_zones.2487133097", "us-west-2a"),
    41  					resource.TestCheckResourceAttr(
    42  						"aws_autoscaling_group.bar", "name", randName),
    43  					resource.TestCheckResourceAttr(
    44  						"aws_autoscaling_group.bar", "max_size", "5"),
    45  					resource.TestCheckResourceAttr(
    46  						"aws_autoscaling_group.bar", "min_size", "2"),
    47  					resource.TestCheckResourceAttr(
    48  						"aws_autoscaling_group.bar", "health_check_grace_period", "300"),
    49  					resource.TestCheckResourceAttr(
    50  						"aws_autoscaling_group.bar", "health_check_type", "ELB"),
    51  					resource.TestCheckResourceAttr(
    52  						"aws_autoscaling_group.bar", "desired_capacity", "4"),
    53  					resource.TestCheckResourceAttr(
    54  						"aws_autoscaling_group.bar", "force_delete", "true"),
    55  					resource.TestCheckResourceAttr(
    56  						"aws_autoscaling_group.bar", "termination_policies.0", "OldestInstance"),
    57  					resource.TestCheckResourceAttr(
    58  						"aws_autoscaling_group.bar", "termination_policies.1", "ClosestToNextInstanceHour"),
    59  					resource.TestCheckResourceAttr(
    60  						"aws_autoscaling_group.bar", "protect_from_scale_in", "false"),
    61  				),
    62  			},
    63  
    64  			resource.TestStep{
    65  				Config: testAccAWSAutoScalingGroupConfigUpdate(randName),
    66  				Check: resource.ComposeTestCheckFunc(
    67  					testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
    68  					testAccCheckAWSLaunchConfigurationExists("aws_launch_configuration.new", &lc),
    69  					resource.TestCheckResourceAttr(
    70  						"aws_autoscaling_group.bar", "desired_capacity", "5"),
    71  					resource.TestCheckResourceAttr(
    72  						"aws_autoscaling_group.bar", "termination_policies.0", "ClosestToNextInstanceHour"),
    73  					resource.TestCheckResourceAttr(
    74  						"aws_autoscaling_group.bar", "protect_from_scale_in", "true"),
    75  					testLaunchConfigurationName("aws_autoscaling_group.bar", &lc),
    76  					testAccCheckAutoscalingTags(&group.Tags, "Bar", map[string]interface{}{
    77  						"value":               "bar-foo",
    78  						"propagate_at_launch": true,
    79  					}),
    80  				),
    81  			},
    82  		},
    83  	})
    84  }
    85  
    86  func TestAccAWSAutoScalingGroup_autoGeneratedName(t *testing.T) {
    87  	asgNameRegexp := regexp.MustCompile("^tf-asg-")
    88  
    89  	resource.Test(t, resource.TestCase{
    90  		PreCheck:     func() { testAccPreCheck(t) },
    91  		Providers:    testAccProviders,
    92  		CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
    93  		Steps: []resource.TestStep{
    94  			resource.TestStep{
    95  				Config: testAccAWSAutoScalingGroupConfig_autoGeneratedName,
    96  				Check: resource.ComposeTestCheckFunc(
    97  					resource.TestMatchResourceAttr(
    98  						"aws_autoscaling_group.bar", "name", asgNameRegexp),
    99  					resource.TestCheckResourceAttrSet(
   100  						"aws_autoscaling_group.bar", "arn"),
   101  				),
   102  			},
   103  		},
   104  	})
   105  }
   106  
   107  func TestAccAWSAutoScalingGroup_terminationPolicies(t *testing.T) {
   108  	resource.Test(t, resource.TestCase{
   109  		PreCheck:     func() { testAccPreCheck(t) },
   110  		Providers:    testAccProviders,
   111  		CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
   112  		Steps: []resource.TestStep{
   113  			resource.TestStep{
   114  				Config: testAccAWSAutoScalingGroupConfig_terminationPoliciesEmpty,
   115  				Check: resource.ComposeTestCheckFunc(
   116  					resource.TestCheckResourceAttr(
   117  						"aws_autoscaling_group.bar", "termination_policies.#", "0"),
   118  				),
   119  			},
   120  
   121  			resource.TestStep{
   122  				Config: testAccAWSAutoScalingGroupConfig_terminationPoliciesUpdate,
   123  				Check: resource.ComposeTestCheckFunc(
   124  					resource.TestCheckResourceAttr(
   125  						"aws_autoscaling_group.bar", "termination_policies.#", "1"),
   126  					resource.TestCheckResourceAttr(
   127  						"aws_autoscaling_group.bar", "termination_policies.0", "OldestInstance"),
   128  				),
   129  			},
   130  
   131  			resource.TestStep{
   132  				Config: testAccAWSAutoScalingGroupConfig_terminationPoliciesExplicitDefault,
   133  				Check: resource.ComposeTestCheckFunc(
   134  					resource.TestCheckResourceAttr(
   135  						"aws_autoscaling_group.bar", "termination_policies.#", "1"),
   136  					resource.TestCheckResourceAttr(
   137  						"aws_autoscaling_group.bar", "termination_policies.0", "Default"),
   138  				),
   139  			},
   140  
   141  			resource.TestStep{
   142  				Config: testAccAWSAutoScalingGroupConfig_terminationPoliciesEmpty,
   143  				Check: resource.ComposeTestCheckFunc(
   144  					resource.TestCheckResourceAttr(
   145  						"aws_autoscaling_group.bar", "termination_policies.#", "0"),
   146  				),
   147  			},
   148  		},
   149  	})
   150  }
   151  
   152  func TestAccAWSAutoScalingGroup_tags(t *testing.T) {
   153  	var group autoscaling.Group
   154  
   155  	randName := fmt.Sprintf("tfautotags-%s", acctest.RandString(5))
   156  
   157  	resource.Test(t, resource.TestCase{
   158  		PreCheck:     func() { testAccPreCheck(t) },
   159  		Providers:    testAccProviders,
   160  		CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
   161  		Steps: []resource.TestStep{
   162  			resource.TestStep{
   163  				Config: testAccAWSAutoScalingGroupConfig(randName),
   164  				Check: resource.ComposeTestCheckFunc(
   165  					testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
   166  					testAccCheckAutoscalingTags(&group.Tags, "Foo", map[string]interface{}{
   167  						"value":               "foo-bar",
   168  						"propagate_at_launch": true,
   169  					}),
   170  				),
   171  			},
   172  
   173  			resource.TestStep{
   174  				Config: testAccAWSAutoScalingGroupConfigUpdate(randName),
   175  				Check: resource.ComposeTestCheckFunc(
   176  					testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
   177  					testAccCheckAutoscalingTagNotExists(&group.Tags, "Foo"),
   178  					testAccCheckAutoscalingTags(&group.Tags, "Bar", map[string]interface{}{
   179  						"value":               "bar-foo",
   180  						"propagate_at_launch": true,
   181  					}),
   182  				),
   183  			},
   184  		},
   185  	})
   186  }
   187  
   188  func TestAccAWSAutoScalingGroup_VpcUpdates(t *testing.T) {
   189  	var group autoscaling.Group
   190  
   191  	resource.Test(t, resource.TestCase{
   192  		PreCheck:     func() { testAccPreCheck(t) },
   193  		Providers:    testAccProviders,
   194  		CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
   195  		Steps: []resource.TestStep{
   196  			resource.TestStep{
   197  				Config: testAccAWSAutoScalingGroupConfigWithAZ,
   198  				Check: resource.ComposeTestCheckFunc(
   199  					testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
   200  					resource.TestCheckResourceAttr(
   201  						"aws_autoscaling_group.bar", "availability_zones.#", "1"),
   202  					resource.TestCheckResourceAttr(
   203  						"aws_autoscaling_group.bar", "availability_zones.2487133097", "us-west-2a"),
   204  					resource.TestCheckResourceAttr(
   205  						"aws_autoscaling_group.bar", "vpc_zone_identifier.#", "1"),
   206  				),
   207  			},
   208  
   209  			resource.TestStep{
   210  				Config: testAccAWSAutoScalingGroupConfigWithVPCIdent,
   211  				Check: resource.ComposeTestCheckFunc(
   212  					testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
   213  					testAccCheckAWSAutoScalingGroupAttributesVPCZoneIdentifer(&group),
   214  					resource.TestCheckResourceAttr(
   215  						"aws_autoscaling_group.bar", "availability_zones.#", "1"),
   216  					resource.TestCheckResourceAttr(
   217  						"aws_autoscaling_group.bar", "availability_zones.2487133097", "us-west-2a"),
   218  					resource.TestCheckResourceAttr(
   219  						"aws_autoscaling_group.bar", "vpc_zone_identifier.#", "1"),
   220  				),
   221  			},
   222  		},
   223  	})
   224  }
   225  
   226  func TestAccAWSAutoScalingGroup_WithLoadBalancer(t *testing.T) {
   227  	var group autoscaling.Group
   228  
   229  	resource.Test(t, resource.TestCase{
   230  		PreCheck:     func() { testAccPreCheck(t) },
   231  		Providers:    testAccProviders,
   232  		CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
   233  		Steps: []resource.TestStep{
   234  			resource.TestStep{
   235  				Config: testAccAWSAutoScalingGroupConfigWithLoadBalancer,
   236  				Check: resource.ComposeTestCheckFunc(
   237  					testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
   238  					testAccCheckAWSAutoScalingGroupAttributesLoadBalancer(&group),
   239  				),
   240  			},
   241  		},
   242  	})
   243  }
   244  
   245  func TestAccAWSAutoScalingGroup_withPlacementGroup(t *testing.T) {
   246  	var group autoscaling.Group
   247  
   248  	randName := fmt.Sprintf("tf_placement_test-%s", acctest.RandString(5))
   249  	resource.Test(t, resource.TestCase{
   250  		PreCheck:     func() { testAccPreCheck(t) },
   251  		Providers:    testAccProviders,
   252  		CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
   253  		Steps: []resource.TestStep{
   254  			resource.TestStep{
   255  				Config: testAccAWSAutoScalingGroupConfig_withPlacementGroup(randName),
   256  				Check: resource.ComposeTestCheckFunc(
   257  					testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
   258  					resource.TestCheckResourceAttr(
   259  						"aws_autoscaling_group.bar", "placement_group", randName),
   260  				),
   261  			},
   262  		},
   263  	})
   264  }
   265  
   266  func TestAccAWSAutoScalingGroup_enablingMetrics(t *testing.T) {
   267  	var group autoscaling.Group
   268  	randName := fmt.Sprintf("terraform-test-%s", acctest.RandString(10))
   269  
   270  	resource.Test(t, resource.TestCase{
   271  		PreCheck:     func() { testAccPreCheck(t) },
   272  		Providers:    testAccProviders,
   273  		CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
   274  		Steps: []resource.TestStep{
   275  			resource.TestStep{
   276  				Config: testAccAWSAutoScalingGroupConfig(randName),
   277  				Check: resource.ComposeTestCheckFunc(
   278  					testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
   279  					resource.TestCheckResourceAttr(
   280  						"aws_autoscaling_group.bar", "enabled_metrics.#", ""),
   281  				),
   282  			},
   283  
   284  			resource.TestStep{
   285  				Config: testAccAWSAutoscalingMetricsCollectionConfig_updatingMetricsCollected,
   286  				Check: resource.ComposeTestCheckFunc(
   287  					testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
   288  					resource.TestCheckResourceAttr(
   289  						"aws_autoscaling_group.bar", "enabled_metrics.#", "5"),
   290  				),
   291  			},
   292  		},
   293  	})
   294  }
   295  
   296  func TestAccAWSAutoScalingGroup_withMetrics(t *testing.T) {
   297  	var group autoscaling.Group
   298  
   299  	resource.Test(t, resource.TestCase{
   300  		PreCheck:     func() { testAccPreCheck(t) },
   301  		Providers:    testAccProviders,
   302  		CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
   303  		Steps: []resource.TestStep{
   304  			resource.TestStep{
   305  				Config: testAccAWSAutoscalingMetricsCollectionConfig_allMetricsCollected,
   306  				Check: resource.ComposeTestCheckFunc(
   307  					testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
   308  					resource.TestCheckResourceAttr(
   309  						"aws_autoscaling_group.bar", "enabled_metrics.#", "7"),
   310  				),
   311  			},
   312  
   313  			resource.TestStep{
   314  				Config: testAccAWSAutoscalingMetricsCollectionConfig_updatingMetricsCollected,
   315  				Check: resource.ComposeTestCheckFunc(
   316  					testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
   317  					resource.TestCheckResourceAttr(
   318  						"aws_autoscaling_group.bar", "enabled_metrics.#", "5"),
   319  				),
   320  			},
   321  		},
   322  	})
   323  }
   324  
   325  func TestAccAWSAutoScalingGroup_ALB_TargetGroups(t *testing.T) {
   326  	var group autoscaling.Group
   327  	var tg elbv2.TargetGroup
   328  	var tg2 elbv2.TargetGroup
   329  
   330  	testCheck := func(targets []*elbv2.TargetGroup) resource.TestCheckFunc {
   331  		return func(*terraform.State) error {
   332  			var ts []string
   333  			var gs []string
   334  			for _, t := range targets {
   335  				ts = append(ts, *t.TargetGroupArn)
   336  			}
   337  
   338  			for _, s := range group.TargetGroupARNs {
   339  				gs = append(gs, *s)
   340  			}
   341  
   342  			sort.Strings(ts)
   343  			sort.Strings(gs)
   344  
   345  			if !reflect.DeepEqual(ts, gs) {
   346  				return fmt.Errorf("Error: target group match not found!\nASG Target groups: %#v\nTarget Group: %#v", ts, gs)
   347  			}
   348  			return nil
   349  		}
   350  	}
   351  
   352  	resource.Test(t, resource.TestCase{
   353  		PreCheck:     func() { testAccPreCheck(t) },
   354  		Providers:    testAccProviders,
   355  		CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
   356  		Steps: []resource.TestStep{
   357  			resource.TestStep{
   358  				Config: testAccAWSAutoScalingGroupConfig_ALB_TargetGroup_pre,
   359  				Check: resource.ComposeAggregateTestCheckFunc(
   360  					testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
   361  					testAccCheckAWSALBTargetGroupExists("aws_alb_target_group.test", &tg),
   362  					resource.TestCheckResourceAttr(
   363  						"aws_autoscaling_group.bar", "target_group_arns.#", "0"),
   364  				),
   365  			},
   366  
   367  			resource.TestStep{
   368  				Config: testAccAWSAutoScalingGroupConfig_ALB_TargetGroup_post_duo,
   369  				Check: resource.ComposeAggregateTestCheckFunc(
   370  					testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
   371  					testAccCheckAWSALBTargetGroupExists("aws_alb_target_group.test", &tg),
   372  					testAccCheckAWSALBTargetGroupExists("aws_alb_target_group.test_more", &tg2),
   373  					testCheck([]*elbv2.TargetGroup{&tg, &tg2}),
   374  					resource.TestCheckResourceAttr(
   375  						"aws_autoscaling_group.bar", "target_group_arns.#", "2"),
   376  				),
   377  			},
   378  
   379  			resource.TestStep{
   380  				Config: testAccAWSAutoScalingGroupConfig_ALB_TargetGroup_post,
   381  				Check: resource.ComposeAggregateTestCheckFunc(
   382  					testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
   383  					testAccCheckAWSALBTargetGroupExists("aws_alb_target_group.test", &tg),
   384  					testCheck([]*elbv2.TargetGroup{&tg}),
   385  					resource.TestCheckResourceAttr(
   386  						"aws_autoscaling_group.bar", "target_group_arns.#", "1"),
   387  				),
   388  			},
   389  
   390  			resource.TestStep{
   391  				Config: testAccAWSAutoScalingGroupConfig_ALB_TargetGroup_pre,
   392  				Check: resource.ComposeAggregateTestCheckFunc(
   393  					testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
   394  					resource.TestCheckResourceAttr(
   395  						"aws_autoscaling_group.bar", "target_group_arns.#", "0"),
   396  				),
   397  			},
   398  		},
   399  	})
   400  }
   401  
   402  func testAccCheckAWSAutoScalingGroupDestroy(s *terraform.State) error {
   403  	conn := testAccProvider.Meta().(*AWSClient).autoscalingconn
   404  
   405  	for _, rs := range s.RootModule().Resources {
   406  		if rs.Type != "aws_autoscaling_group" {
   407  			continue
   408  		}
   409  
   410  		// Try to find the Group
   411  		describeGroups, err := conn.DescribeAutoScalingGroups(
   412  			&autoscaling.DescribeAutoScalingGroupsInput{
   413  				AutoScalingGroupNames: []*string{aws.String(rs.Primary.ID)},
   414  			})
   415  
   416  		if err == nil {
   417  			if len(describeGroups.AutoScalingGroups) != 0 &&
   418  				*describeGroups.AutoScalingGroups[0].AutoScalingGroupName == rs.Primary.ID {
   419  				return fmt.Errorf("AutoScaling Group still exists")
   420  			}
   421  		}
   422  
   423  		// Verify the error
   424  		ec2err, ok := err.(awserr.Error)
   425  		if !ok {
   426  			return err
   427  		}
   428  		if ec2err.Code() != "InvalidGroup.NotFound" {
   429  			return err
   430  		}
   431  	}
   432  
   433  	return nil
   434  }
   435  
   436  func testAccCheckAWSAutoScalingGroupAttributes(group *autoscaling.Group, name string) resource.TestCheckFunc {
   437  	return func(s *terraform.State) error {
   438  		if *group.AvailabilityZones[0] != "us-west-2a" {
   439  			return fmt.Errorf("Bad availability_zones: %#v", group.AvailabilityZones[0])
   440  		}
   441  
   442  		if *group.AutoScalingGroupName != name {
   443  			return fmt.Errorf("Bad Autoscaling Group name, expected (%s), got (%s)", name, *group.AutoScalingGroupName)
   444  		}
   445  
   446  		if *group.MaxSize != 5 {
   447  			return fmt.Errorf("Bad max_size: %d", *group.MaxSize)
   448  		}
   449  
   450  		if *group.MinSize != 2 {
   451  			return fmt.Errorf("Bad max_size: %d", *group.MinSize)
   452  		}
   453  
   454  		if *group.HealthCheckType != "ELB" {
   455  			return fmt.Errorf("Bad health_check_type,\nexpected: %s\ngot: %s", "ELB", *group.HealthCheckType)
   456  		}
   457  
   458  		if *group.HealthCheckGracePeriod != 300 {
   459  			return fmt.Errorf("Bad health_check_grace_period: %d", *group.HealthCheckGracePeriod)
   460  		}
   461  
   462  		if *group.DesiredCapacity != 4 {
   463  			return fmt.Errorf("Bad desired_capacity: %d", *group.DesiredCapacity)
   464  		}
   465  
   466  		if *group.LaunchConfigurationName == "" {
   467  			return fmt.Errorf("Bad launch configuration name: %s", *group.LaunchConfigurationName)
   468  		}
   469  
   470  		t := &autoscaling.TagDescription{
   471  			Key:               aws.String("Foo"),
   472  			Value:             aws.String("foo-bar"),
   473  			PropagateAtLaunch: aws.Bool(true),
   474  			ResourceType:      aws.String("auto-scaling-group"),
   475  			ResourceId:        group.AutoScalingGroupName,
   476  		}
   477  
   478  		if !reflect.DeepEqual(group.Tags[0], t) {
   479  			return fmt.Errorf(
   480  				"Got:\n\n%#v\n\nExpected:\n\n%#v\n",
   481  				group.Tags[0],
   482  				t)
   483  		}
   484  
   485  		return nil
   486  	}
   487  }
   488  
   489  func testAccCheckAWSAutoScalingGroupAttributesLoadBalancer(group *autoscaling.Group) resource.TestCheckFunc {
   490  	return func(s *terraform.State) error {
   491  		if len(group.LoadBalancerNames) != 1 {
   492  			return fmt.Errorf("Bad load_balancers: %v", group.LoadBalancerNames)
   493  		}
   494  
   495  		return nil
   496  	}
   497  }
   498  
   499  func testAccCheckAWSAutoScalingGroupExists(n string, group *autoscaling.Group) resource.TestCheckFunc {
   500  	return func(s *terraform.State) error {
   501  		rs, ok := s.RootModule().Resources[n]
   502  		if !ok {
   503  			return fmt.Errorf("Not found: %s", n)
   504  		}
   505  
   506  		if rs.Primary.ID == "" {
   507  			return fmt.Errorf("No AutoScaling Group ID is set")
   508  		}
   509  
   510  		conn := testAccProvider.Meta().(*AWSClient).autoscalingconn
   511  
   512  		describeGroups, err := conn.DescribeAutoScalingGroups(
   513  			&autoscaling.DescribeAutoScalingGroupsInput{
   514  				AutoScalingGroupNames: []*string{aws.String(rs.Primary.ID)},
   515  			})
   516  
   517  		if err != nil {
   518  			return err
   519  		}
   520  
   521  		if len(describeGroups.AutoScalingGroups) != 1 ||
   522  			*describeGroups.AutoScalingGroups[0].AutoScalingGroupName != rs.Primary.ID {
   523  			return fmt.Errorf("AutoScaling Group not found")
   524  		}
   525  
   526  		*group = *describeGroups.AutoScalingGroups[0]
   527  
   528  		return nil
   529  	}
   530  }
   531  
   532  func testLaunchConfigurationName(n string, lc *autoscaling.LaunchConfiguration) resource.TestCheckFunc {
   533  	return func(s *terraform.State) error {
   534  		rs, ok := s.RootModule().Resources[n]
   535  		if !ok {
   536  			return fmt.Errorf("Not found: %s", n)
   537  		}
   538  
   539  		if *lc.LaunchConfigurationName != rs.Primary.Attributes["launch_configuration"] {
   540  			return fmt.Errorf("Launch configuration names do not match")
   541  		}
   542  
   543  		return nil
   544  	}
   545  }
   546  
   547  func testAccCheckAWSAutoScalingGroupHealthyCapacity(
   548  	g *autoscaling.Group, exp int) resource.TestCheckFunc {
   549  	return func(s *terraform.State) error {
   550  		healthy := 0
   551  		for _, i := range g.Instances {
   552  			if i.HealthStatus == nil {
   553  				continue
   554  			}
   555  			if strings.EqualFold(*i.HealthStatus, "Healthy") {
   556  				healthy++
   557  			}
   558  		}
   559  		if healthy < exp {
   560  			return fmt.Errorf("Expected at least %d healthy, got %d.", exp, healthy)
   561  		}
   562  		return nil
   563  	}
   564  }
   565  
   566  func testAccCheckAWSAutoScalingGroupAttributesVPCZoneIdentifer(group *autoscaling.Group) resource.TestCheckFunc {
   567  	return func(s *terraform.State) error {
   568  		// Grab Subnet Ids
   569  		var subnets []string
   570  		for _, rs := range s.RootModule().Resources {
   571  			if rs.Type != "aws_subnet" {
   572  				continue
   573  			}
   574  			subnets = append(subnets, rs.Primary.Attributes["id"])
   575  		}
   576  
   577  		if group.VPCZoneIdentifier == nil {
   578  			return fmt.Errorf("Bad VPC Zone Identifier\nexpected: %s\ngot nil", subnets)
   579  		}
   580  
   581  		zones := strings.Split(*group.VPCZoneIdentifier, ",")
   582  
   583  		remaining := len(zones)
   584  		for _, z := range zones {
   585  			for _, s := range subnets {
   586  				if z == s {
   587  					remaining--
   588  				}
   589  			}
   590  		}
   591  
   592  		if remaining != 0 {
   593  			return fmt.Errorf("Bad VPC Zone Identifier match\nexpected: %s\ngot:%s", zones, subnets)
   594  		}
   595  
   596  		return nil
   597  	}
   598  }
   599  
   600  const testAccAWSAutoScalingGroupConfig_autoGeneratedName = `
   601  resource "aws_launch_configuration" "foobar" {
   602    image_id = "ami-21f78e11"
   603    instance_type = "t1.micro"
   604  }
   605  
   606  resource "aws_autoscaling_group" "bar" {
   607    availability_zones = ["us-west-2a"]
   608    desired_capacity = 0
   609    max_size = 0
   610    min_size = 0
   611    launch_configuration = "${aws_launch_configuration.foobar.name}"
   612  }
   613  `
   614  
   615  const testAccAWSAutoScalingGroupConfig_terminationPoliciesEmpty = `
   616  resource "aws_launch_configuration" "foobar" {
   617    image_id = "ami-21f78e11"
   618    instance_type = "t1.micro"
   619  }
   620  
   621  resource "aws_autoscaling_group" "bar" {
   622    availability_zones = ["us-west-2a"]
   623    max_size = 0
   624    min_size = 0
   625    desired_capacity = 0
   626  
   627    launch_configuration = "${aws_launch_configuration.foobar.name}"
   628  }
   629  `
   630  
   631  const testAccAWSAutoScalingGroupConfig_terminationPoliciesExplicitDefault = `
   632  resource "aws_launch_configuration" "foobar" {
   633    image_id = "ami-21f78e11"
   634    instance_type = "t1.micro"
   635  }
   636  
   637  resource "aws_autoscaling_group" "bar" {
   638    availability_zones = ["us-west-2a"]
   639    max_size = 0
   640    min_size = 0
   641    desired_capacity = 0
   642    termination_policies = ["Default"]
   643  
   644    launch_configuration = "${aws_launch_configuration.foobar.name}"
   645  }
   646  `
   647  
   648  const testAccAWSAutoScalingGroupConfig_terminationPoliciesUpdate = `
   649  resource "aws_launch_configuration" "foobar" {
   650    image_id = "ami-21f78e11"
   651    instance_type = "t1.micro"
   652  }
   653  
   654  resource "aws_autoscaling_group" "bar" {
   655    availability_zones = ["us-west-2a"]
   656    max_size = 0
   657    min_size = 0
   658    desired_capacity = 0
   659    termination_policies = ["OldestInstance"]
   660  
   661    launch_configuration = "${aws_launch_configuration.foobar.name}"
   662  }
   663  `
   664  
   665  func testAccAWSAutoScalingGroupConfig(name string) string {
   666  	return fmt.Sprintf(`
   667  resource "aws_launch_configuration" "foobar" {
   668    image_id = "ami-21f78e11"
   669    instance_type = "t1.micro"
   670  }
   671  
   672  resource "aws_placement_group" "test" {
   673    name = "asg_pg_%s"
   674    strategy = "cluster"
   675  }
   676  
   677  resource "aws_autoscaling_group" "bar" {
   678    availability_zones = ["us-west-2a"]
   679    name = "%s"
   680    max_size = 5
   681    min_size = 2
   682    health_check_type = "ELB"
   683    desired_capacity = 4
   684    force_delete = true
   685    termination_policies = ["OldestInstance","ClosestToNextInstanceHour"]
   686  
   687    launch_configuration = "${aws_launch_configuration.foobar.name}"
   688  
   689    tag {
   690      key = "Foo"
   691      value = "foo-bar"
   692      propagate_at_launch = true
   693    }
   694  }
   695  `, name, name)
   696  }
   697  
   698  func testAccAWSAutoScalingGroupConfigUpdate(name string) string {
   699  	return fmt.Sprintf(`
   700  resource "aws_launch_configuration" "foobar" {
   701    image_id = "ami-21f78e11"
   702    instance_type = "t1.micro"
   703  }
   704  
   705  resource "aws_launch_configuration" "new" {
   706    image_id = "ami-21f78e11"
   707    instance_type = "t1.micro"
   708  }
   709  
   710  resource "aws_autoscaling_group" "bar" {
   711    availability_zones = ["us-west-2a"]
   712    name = "%s"
   713    max_size = 5
   714    min_size = 2
   715    health_check_grace_period = 300
   716    health_check_type = "ELB"
   717    desired_capacity = 5
   718    force_delete = true
   719    termination_policies = ["ClosestToNextInstanceHour"]
   720    protect_from_scale_in = true
   721  
   722    launch_configuration = "${aws_launch_configuration.new.name}"
   723  
   724    tag {
   725      key = "Bar"
   726      value = "bar-foo"
   727      propagate_at_launch = true
   728    }
   729  }
   730  `, name)
   731  }
   732  
   733  const testAccAWSAutoScalingGroupConfigWithLoadBalancer = `
   734  resource "aws_vpc" "foo" {
   735    cidr_block = "10.1.0.0/16"
   736  	tags { Name = "tf-asg-test" }
   737  }
   738  
   739  resource "aws_internet_gateway" "gw" {
   740    vpc_id = "${aws_vpc.foo.id}"
   741  }
   742  
   743  resource "aws_subnet" "foo" {
   744  	cidr_block = "10.1.1.0/24"
   745  	vpc_id = "${aws_vpc.foo.id}"
   746  }
   747  
   748  resource "aws_security_group" "foo" {
   749    vpc_id="${aws_vpc.foo.id}"
   750  
   751    ingress {
   752      protocol = "-1"
   753      from_port = 0
   754      to_port = 0
   755      cidr_blocks = ["0.0.0.0/0"]
   756    }
   757  
   758    egress {
   759      protocol = "-1"
   760      from_port = 0
   761      to_port = 0
   762      cidr_blocks = ["0.0.0.0/0"]
   763    }
   764  }
   765  
   766  resource "aws_elb" "bar" {
   767    subnets = ["${aws_subnet.foo.id}"]
   768  	security_groups = ["${aws_security_group.foo.id}"]
   769  
   770    listener {
   771      instance_port = 80
   772      instance_protocol = "http"
   773      lb_port = 80
   774      lb_protocol = "http"
   775    }
   776  
   777    health_check {
   778      healthy_threshold = 2
   779      unhealthy_threshold = 2
   780      target = "HTTP:80/"
   781      interval = 5
   782      timeout = 2
   783    }
   784  
   785  	depends_on = ["aws_internet_gateway.gw"]
   786  }
   787  
   788  resource "aws_launch_configuration" "foobar" {
   789    // need an AMI that listens on :80 at boot, this is:
   790    // bitnami-nginxstack-1.6.1-0-linux-ubuntu-14.04.1-x86_64-hvm-ebs-ami-99f5b1a9-3
   791    image_id = "ami-b5b3fc85"
   792    instance_type = "t2.micro"
   793  	security_groups = ["${aws_security_group.foo.id}"]
   794  }
   795  
   796  resource "aws_autoscaling_group" "bar" {
   797    availability_zones = ["${aws_subnet.foo.availability_zone}"]
   798  	vpc_zone_identifier = ["${aws_subnet.foo.id}"]
   799    max_size = 2
   800    min_size = 2
   801    health_check_grace_period = 300
   802    health_check_type = "ELB"
   803    wait_for_elb_capacity = 2
   804    force_delete = true
   805  
   806    launch_configuration = "${aws_launch_configuration.foobar.name}"
   807    load_balancers = ["${aws_elb.bar.name}"]
   808  }
   809  `
   810  
   811  const testAccAWSAutoScalingGroupConfigWithAZ = `
   812  resource "aws_vpc" "default" {
   813    cidr_block = "10.0.0.0/16"
   814    tags {
   815       Name = "terraform-test"
   816    }
   817  }
   818  
   819  resource "aws_subnet" "main" {
   820    vpc_id = "${aws_vpc.default.id}"
   821    cidr_block = "10.0.1.0/24"
   822    availability_zone = "us-west-2a"
   823    tags {
   824       Name = "terraform-test"
   825    }
   826  }
   827  
   828  resource "aws_launch_configuration" "foobar" {
   829    image_id = "ami-b5b3fc85"
   830    instance_type = "t2.micro"
   831  }
   832  
   833  resource "aws_autoscaling_group" "bar" {
   834    availability_zones = [
   835  	  "us-west-2a"
   836    ]
   837    desired_capacity = 0
   838    max_size = 0
   839    min_size = 0
   840    launch_configuration = "${aws_launch_configuration.foobar.name}"
   841  }
   842  `
   843  
   844  const testAccAWSAutoScalingGroupConfigWithVPCIdent = `
   845  resource "aws_vpc" "default" {
   846    cidr_block = "10.0.0.0/16"
   847    tags {
   848       Name = "terraform-test"
   849    }
   850  }
   851  
   852  resource "aws_subnet" "main" {
   853    vpc_id = "${aws_vpc.default.id}"
   854    cidr_block = "10.0.1.0/24"
   855    availability_zone = "us-west-2a"
   856    tags {
   857       Name = "terraform-test"
   858    }
   859  }
   860  
   861  resource "aws_launch_configuration" "foobar" {
   862    image_id = "ami-b5b3fc85"
   863    instance_type = "t2.micro"
   864  }
   865  
   866  resource "aws_autoscaling_group" "bar" {
   867    vpc_zone_identifier = [
   868      "${aws_subnet.main.id}",
   869    ]
   870    desired_capacity = 0
   871    max_size = 0
   872    min_size = 0
   873    launch_configuration = "${aws_launch_configuration.foobar.name}"
   874  }
   875  `
   876  
   877  func testAccAWSAutoScalingGroupConfig_withPlacementGroup(name string) string {
   878  	return fmt.Sprintf(`
   879  resource "aws_launch_configuration" "foobar" {
   880    image_id = "ami-21f78e11"
   881    instance_type = "c3.large"
   882  }
   883  
   884  resource "aws_placement_group" "test" {
   885    name = "%s"
   886    strategy = "cluster"
   887  }
   888  
   889  resource "aws_autoscaling_group" "bar" {
   890    availability_zones = ["us-west-2a"]
   891    name = "%s"
   892    max_size = 1
   893    min_size = 1
   894    health_check_grace_period = 300
   895    health_check_type = "ELB"
   896    desired_capacity = 1
   897    force_delete = true
   898    termination_policies = ["OldestInstance","ClosestToNextInstanceHour"]
   899    placement_group = "${aws_placement_group.test.name}"
   900  
   901    launch_configuration = "${aws_launch_configuration.foobar.name}"
   902  
   903    tag {
   904      key = "Foo"
   905      value = "foo-bar"
   906      propagate_at_launch = true
   907    }
   908  }
   909  `, name, name)
   910  }
   911  
   912  const testAccAWSAutoscalingMetricsCollectionConfig_allMetricsCollected = `
   913  resource "aws_launch_configuration" "foobar" {
   914    image_id = "ami-21f78e11"
   915    instance_type = "t1.micro"
   916  }
   917  
   918  resource "aws_autoscaling_group" "bar" {
   919    availability_zones = ["us-west-2a"]
   920    max_size = 1
   921    min_size = 0
   922    health_check_grace_period = 300
   923    health_check_type = "EC2"
   924    desired_capacity = 0
   925    force_delete = true
   926    termination_policies = ["OldestInstance","ClosestToNextInstanceHour"]
   927    launch_configuration = "${aws_launch_configuration.foobar.name}"
   928    enabled_metrics = ["GroupTotalInstances",
   929    	     "GroupPendingInstances",
   930    	     "GroupTerminatingInstances",
   931    	     "GroupDesiredCapacity",
   932    	     "GroupInServiceInstances",
   933    	     "GroupMinSize",
   934    	     "GroupMaxSize"
   935    ]
   936    metrics_granularity = "1Minute"
   937  }
   938  `
   939  
   940  const testAccAWSAutoscalingMetricsCollectionConfig_updatingMetricsCollected = `
   941  resource "aws_launch_configuration" "foobar" {
   942    image_id = "ami-21f78e11"
   943    instance_type = "t1.micro"
   944  }
   945  
   946  resource "aws_autoscaling_group" "bar" {
   947    availability_zones = ["us-west-2a"]
   948    max_size = 1
   949    min_size = 0
   950    health_check_grace_period = 300
   951    health_check_type = "EC2"
   952    desired_capacity = 0
   953    force_delete = true
   954    termination_policies = ["OldestInstance","ClosestToNextInstanceHour"]
   955    launch_configuration = "${aws_launch_configuration.foobar.name}"
   956    enabled_metrics = ["GroupTotalInstances",
   957    	     "GroupPendingInstances",
   958    	     "GroupTerminatingInstances",
   959    	     "GroupDesiredCapacity",
   960    	     "GroupMaxSize"
   961    ]
   962    metrics_granularity = "1Minute"
   963  }
   964  `
   965  
   966  const testAccAWSAutoScalingGroupConfig_ALB_TargetGroup_pre = `
   967  provider "aws" {
   968    region = "us-west-2"
   969  }
   970  
   971  resource "aws_vpc" "default" {
   972    cidr_block = "10.0.0.0/16"
   973  
   974    tags {
   975      Name = "testAccAWSAutoScalingGroupConfig_ALB_TargetGroup"
   976    }
   977  }
   978  
   979  resource "aws_alb_target_group" "test" {
   980    name     = "tf-example-alb-tg"
   981    port     = 80
   982    protocol = "HTTP"
   983    vpc_id   = "${aws_vpc.default.id}"
   984  }
   985  
   986  resource "aws_subnet" "main" {
   987    vpc_id            = "${aws_vpc.default.id}"
   988    cidr_block        = "10.0.1.0/24"
   989    availability_zone = "us-west-2a"
   990  
   991    tags {
   992      Name = "testAccAWSAutoScalingGroupConfig_ALB_TargetGroup"
   993    }
   994  }
   995  
   996  resource "aws_subnet" "alt" {
   997    vpc_id            = "${aws_vpc.default.id}"
   998    cidr_block        = "10.0.2.0/24"
   999    availability_zone = "us-west-2b"
  1000  
  1001    tags {
  1002      Name = "testAccAWSAutoScalingGroupConfig_ALB_TargetGroup"
  1003    }
  1004  }
  1005  
  1006  resource "aws_launch_configuration" "foobar" {
  1007    # Golang-base from cts-hashi aws account, shared with tf testing account
  1008    image_id          = "ami-1817d178"
  1009    instance_type     = "t2.micro"
  1010    enable_monitoring = false
  1011  }
  1012  
  1013  resource "aws_autoscaling_group" "bar" {
  1014    vpc_zone_identifier = [
  1015      "${aws_subnet.main.id}",
  1016      "${aws_subnet.alt.id}",
  1017    ]
  1018  
  1019    max_size                  = 2
  1020    min_size                  = 0
  1021    health_check_grace_period = 300
  1022    health_check_type         = "ELB"
  1023    desired_capacity          = 0
  1024    force_delete              = true
  1025    termination_policies      = ["OldestInstance"]
  1026    launch_configuration      = "${aws_launch_configuration.foobar.name}"
  1027  
  1028  }
  1029  
  1030  resource "aws_security_group" "tf_test_self" {
  1031    name        = "tf_test_alb_asg"
  1032    description = "tf_test_alb_asg"
  1033    vpc_id      = "${aws_vpc.default.id}"
  1034  
  1035    ingress {
  1036      from_port   = 80
  1037      to_port     = 80
  1038      protocol    = "tcp"
  1039      cidr_blocks = ["0.0.0.0/0"]
  1040    }
  1041  
  1042    tags {
  1043      Name = "testAccAWSAutoScalingGroupConfig_ALB_TargetGroup"
  1044    }
  1045  }
  1046  `
  1047  
  1048  const testAccAWSAutoScalingGroupConfig_ALB_TargetGroup_post = `
  1049  provider "aws" {
  1050    region = "us-west-2"
  1051  }
  1052  
  1053  resource "aws_vpc" "default" {
  1054    cidr_block = "10.0.0.0/16"
  1055  
  1056    tags {
  1057      Name = "testAccAWSAutoScalingGroupConfig_ALB_TargetGroup"
  1058    }
  1059  }
  1060  
  1061  resource "aws_alb_target_group" "test" {
  1062    name     = "tf-example-alb-tg"
  1063    port     = 80
  1064    protocol = "HTTP"
  1065    vpc_id   = "${aws_vpc.default.id}"
  1066  }
  1067  
  1068  resource "aws_subnet" "main" {
  1069    vpc_id            = "${aws_vpc.default.id}"
  1070    cidr_block        = "10.0.1.0/24"
  1071    availability_zone = "us-west-2a"
  1072  
  1073    tags {
  1074      Name = "testAccAWSAutoScalingGroupConfig_ALB_TargetGroup"
  1075    }
  1076  }
  1077  
  1078  resource "aws_subnet" "alt" {
  1079    vpc_id            = "${aws_vpc.default.id}"
  1080    cidr_block        = "10.0.2.0/24"
  1081    availability_zone = "us-west-2b"
  1082  
  1083    tags {
  1084      Name = "testAccAWSAutoScalingGroupConfig_ALB_TargetGroup"
  1085    }
  1086  }
  1087  
  1088  resource "aws_launch_configuration" "foobar" {
  1089    # Golang-base from cts-hashi aws account, shared with tf testing account
  1090    image_id          = "ami-1817d178"
  1091    instance_type     = "t2.micro"
  1092    enable_monitoring = false
  1093  }
  1094  
  1095  resource "aws_autoscaling_group" "bar" {
  1096    vpc_zone_identifier = [
  1097      "${aws_subnet.main.id}",
  1098      "${aws_subnet.alt.id}",
  1099    ]
  1100  
  1101  	target_group_arns = ["${aws_alb_target_group.test.arn}"]
  1102  
  1103    max_size                  = 2
  1104    min_size                  = 0
  1105    health_check_grace_period = 300
  1106    health_check_type         = "ELB"
  1107    desired_capacity          = 0
  1108    force_delete              = true
  1109    termination_policies      = ["OldestInstance"]
  1110    launch_configuration      = "${aws_launch_configuration.foobar.name}"
  1111  
  1112  }
  1113  
  1114  resource "aws_security_group" "tf_test_self" {
  1115    name        = "tf_test_alb_asg"
  1116    description = "tf_test_alb_asg"
  1117    vpc_id      = "${aws_vpc.default.id}"
  1118  
  1119    ingress {
  1120      from_port   = 80
  1121      to_port     = 80
  1122      protocol    = "tcp"
  1123      cidr_blocks = ["0.0.0.0/0"]
  1124    }
  1125  
  1126    tags {
  1127      Name = "testAccAWSAutoScalingGroupConfig_ALB_TargetGroup"
  1128    }
  1129  }
  1130  `
  1131  
  1132  const testAccAWSAutoScalingGroupConfig_ALB_TargetGroup_post_duo = `
  1133  provider "aws" {
  1134    region = "us-west-2"
  1135  }
  1136  
  1137  resource "aws_vpc" "default" {
  1138    cidr_block = "10.0.0.0/16"
  1139  
  1140    tags {
  1141      Name = "testAccAWSAutoScalingGroupConfig_ALB_TargetGroup"
  1142    }
  1143  }
  1144  
  1145  resource "aws_alb_target_group" "test" {
  1146    name     = "tf-example-alb-tg"
  1147    port     = 80
  1148    protocol = "HTTP"
  1149    vpc_id   = "${aws_vpc.default.id}"
  1150  }
  1151  
  1152  resource "aws_alb_target_group" "test_more" {
  1153    name     = "tf-example-alb-tg-more"
  1154    port     = 80
  1155    protocol = "HTTP"
  1156    vpc_id   = "${aws_vpc.default.id}"
  1157  }
  1158  
  1159  resource "aws_subnet" "main" {
  1160    vpc_id            = "${aws_vpc.default.id}"
  1161    cidr_block        = "10.0.1.0/24"
  1162    availability_zone = "us-west-2a"
  1163  
  1164    tags {
  1165      Name = "testAccAWSAutoScalingGroupConfig_ALB_TargetGroup"
  1166    }
  1167  }
  1168  
  1169  resource "aws_subnet" "alt" {
  1170    vpc_id            = "${aws_vpc.default.id}"
  1171    cidr_block        = "10.0.2.0/24"
  1172    availability_zone = "us-west-2b"
  1173  
  1174    tags {
  1175      Name = "testAccAWSAutoScalingGroupConfig_ALB_TargetGroup"
  1176    }
  1177  }
  1178  
  1179  resource "aws_launch_configuration" "foobar" {
  1180    # Golang-base from cts-hashi aws account, shared with tf testing account
  1181    image_id          = "ami-1817d178"
  1182    instance_type     = "t2.micro"
  1183    enable_monitoring = false
  1184  }
  1185  
  1186  resource "aws_autoscaling_group" "bar" {
  1187    vpc_zone_identifier = [
  1188      "${aws_subnet.main.id}",
  1189      "${aws_subnet.alt.id}",
  1190    ]
  1191  
  1192  	target_group_arns = [
  1193  		"${aws_alb_target_group.test.arn}",
  1194  		"${aws_alb_target_group.test_more.arn}",
  1195  	]
  1196  
  1197    max_size                  = 2
  1198    min_size                  = 0
  1199    health_check_grace_period = 300
  1200    health_check_type         = "ELB"
  1201    desired_capacity          = 0
  1202    force_delete              = true
  1203    termination_policies      = ["OldestInstance"]
  1204    launch_configuration      = "${aws_launch_configuration.foobar.name}"
  1205  
  1206  }
  1207  
  1208  resource "aws_security_group" "tf_test_self" {
  1209    name        = "tf_test_alb_asg"
  1210    description = "tf_test_alb_asg"
  1211    vpc_id      = "${aws_vpc.default.id}"
  1212  
  1213    ingress {
  1214      from_port   = 80
  1215      to_port     = 80
  1216      protocol    = "tcp"
  1217      cidr_blocks = ["0.0.0.0/0"]
  1218    }
  1219  
  1220    tags {
  1221      Name = "testAccAWSAutoScalingGroupConfig_ALB_TargetGroup"
  1222    }
  1223  }
  1224  `