github.com/koding/terraform@v0.6.4-0.20170608090606-5d7e0339779d/builtin/providers/aws/resource_aws_autoscaling_group_test.go (about)

     1  package aws
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"log"
     7  	"reflect"
     8  	"regexp"
     9  	"sort"
    10  	"strings"
    11  	"testing"
    12  	"time"
    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/autoscaling"
    17  	"github.com/aws/aws-sdk-go/service/elbv2"
    18  	"github.com/hashicorp/terraform/helper/acctest"
    19  	"github.com/hashicorp/terraform/helper/resource"
    20  	"github.com/hashicorp/terraform/terraform"
    21  )
    22  
    23  func init() {
    24  	resource.AddTestSweepers("aws_autoscaling_group", &resource.Sweeper{
    25  		Name: "aws_autoscaling_group",
    26  		F:    testSweepAutoscalingGroups,
    27  	})
    28  }
    29  
    30  func testSweepAutoscalingGroups(region string) error {
    31  	client, err := sharedClientForRegion(region)
    32  	if err != nil {
    33  		return fmt.Errorf("error getting client: %s", err)
    34  	}
    35  	conn := client.(*AWSClient).autoscalingconn
    36  
    37  	resp, err := conn.DescribeAutoScalingGroups(&autoscaling.DescribeAutoScalingGroupsInput{})
    38  	if err != nil {
    39  		return fmt.Errorf("Error retrieving launch configuration: %s", err)
    40  	}
    41  
    42  	if len(resp.AutoScalingGroups) == 0 {
    43  		log.Print("[DEBUG] No aws autoscaling groups to sweep")
    44  		return nil
    45  	}
    46  
    47  	for _, asg := range resp.AutoScalingGroups {
    48  		var testOptGroup bool
    49  		for _, testName := range []string{"foobar", "terraform-"} {
    50  			if strings.HasPrefix(*asg.AutoScalingGroupName, testName) {
    51  				testOptGroup = true
    52  			}
    53  		}
    54  
    55  		if !testOptGroup {
    56  			continue
    57  		}
    58  
    59  		deleteopts := autoscaling.DeleteAutoScalingGroupInput{
    60  			AutoScalingGroupName: asg.AutoScalingGroupName,
    61  			ForceDelete:          aws.Bool(true),
    62  		}
    63  
    64  		err = resource.Retry(5*time.Minute, func() *resource.RetryError {
    65  			if _, err := conn.DeleteAutoScalingGroup(&deleteopts); err != nil {
    66  				if awserr, ok := err.(awserr.Error); ok {
    67  					switch awserr.Code() {
    68  					case "InvalidGroup.NotFound":
    69  						return nil
    70  					case "ResourceInUse", "ScalingActivityInProgress":
    71  						return resource.RetryableError(awserr)
    72  					}
    73  				}
    74  
    75  				// Didn't recognize the error, so shouldn't retry.
    76  				return resource.NonRetryableError(err)
    77  			}
    78  			// Successful delete
    79  			return nil
    80  		})
    81  		if err != nil {
    82  			return err
    83  		}
    84  	}
    85  
    86  	return nil
    87  }
    88  
    89  func TestAccAWSAutoScalingGroup_basic(t *testing.T) {
    90  	var group autoscaling.Group
    91  	var lc autoscaling.LaunchConfiguration
    92  
    93  	randName := fmt.Sprintf("terraform-test-%s", acctest.RandString(10))
    94  
    95  	resource.Test(t, resource.TestCase{
    96  		PreCheck:        func() { testAccPreCheck(t) },
    97  		IDRefreshName:   "aws_autoscaling_group.bar",
    98  		IDRefreshIgnore: []string{"force_delete", "metrics_granularity", "wait_for_capacity_timeout"},
    99  		Providers:       testAccProviders,
   100  		CheckDestroy:    testAccCheckAWSAutoScalingGroupDestroy,
   101  		Steps: []resource.TestStep{
   102  			resource.TestStep{
   103  				Config: testAccAWSAutoScalingGroupConfig(randName),
   104  				Check: resource.ComposeTestCheckFunc(
   105  					testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
   106  					testAccCheckAWSAutoScalingGroupHealthyCapacity(&group, 2),
   107  					testAccCheckAWSAutoScalingGroupAttributes(&group, randName),
   108  					resource.TestCheckResourceAttr(
   109  						"aws_autoscaling_group.bar", "availability_zones.2487133097", "us-west-2a"),
   110  					resource.TestCheckResourceAttr(
   111  						"aws_autoscaling_group.bar", "name", randName),
   112  					resource.TestCheckResourceAttr(
   113  						"aws_autoscaling_group.bar", "max_size", "5"),
   114  					resource.TestCheckResourceAttr(
   115  						"aws_autoscaling_group.bar", "min_size", "2"),
   116  					resource.TestCheckResourceAttr(
   117  						"aws_autoscaling_group.bar", "health_check_grace_period", "300"),
   118  					resource.TestCheckResourceAttr(
   119  						"aws_autoscaling_group.bar", "health_check_type", "ELB"),
   120  					resource.TestCheckResourceAttr(
   121  						"aws_autoscaling_group.bar", "desired_capacity", "4"),
   122  					resource.TestCheckResourceAttr(
   123  						"aws_autoscaling_group.bar", "force_delete", "true"),
   124  					resource.TestCheckResourceAttr(
   125  						"aws_autoscaling_group.bar", "termination_policies.0", "OldestInstance"),
   126  					resource.TestCheckResourceAttr(
   127  						"aws_autoscaling_group.bar", "termination_policies.1", "ClosestToNextInstanceHour"),
   128  					resource.TestCheckResourceAttr(
   129  						"aws_autoscaling_group.bar", "protect_from_scale_in", "false"),
   130  				),
   131  			},
   132  
   133  			resource.TestStep{
   134  				Config: testAccAWSAutoScalingGroupConfigUpdate(randName),
   135  				Check: resource.ComposeTestCheckFunc(
   136  					testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
   137  					testAccCheckAWSLaunchConfigurationExists("aws_launch_configuration.new", &lc),
   138  					resource.TestCheckResourceAttr(
   139  						"aws_autoscaling_group.bar", "desired_capacity", "5"),
   140  					resource.TestCheckResourceAttr(
   141  						"aws_autoscaling_group.bar", "termination_policies.0", "ClosestToNextInstanceHour"),
   142  					resource.TestCheckResourceAttr(
   143  						"aws_autoscaling_group.bar", "protect_from_scale_in", "true"),
   144  					testLaunchConfigurationName("aws_autoscaling_group.bar", &lc),
   145  					testAccCheckAutoscalingTags(&group.Tags, "FromTags1Changed", map[string]interface{}{
   146  						"value":               "value1changed",
   147  						"propagate_at_launch": true,
   148  					}),
   149  					testAccCheckAutoscalingTags(&group.Tags, "FromTags2", map[string]interface{}{
   150  						"value":               "value2changed",
   151  						"propagate_at_launch": true,
   152  					}),
   153  					testAccCheckAutoscalingTags(&group.Tags, "FromTags3", map[string]interface{}{
   154  						"value":               "value3",
   155  						"propagate_at_launch": true,
   156  					}),
   157  				),
   158  			},
   159  		},
   160  	})
   161  }
   162  
   163  func TestAccAWSAutoScalingGroup_namePrefix(t *testing.T) {
   164  	nameRegexp := regexp.MustCompile("^test-")
   165  
   166  	resource.Test(t, resource.TestCase{
   167  		PreCheck:     func() { testAccPreCheck(t) },
   168  		Providers:    testAccProviders,
   169  		CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
   170  		Steps: []resource.TestStep{
   171  			resource.TestStep{
   172  				Config: testAccAWSAutoScalingGroupConfig_namePrefix,
   173  				Check: resource.ComposeTestCheckFunc(
   174  					resource.TestMatchResourceAttr(
   175  						"aws_autoscaling_group.test", "name", nameRegexp),
   176  					resource.TestCheckResourceAttrSet(
   177  						"aws_autoscaling_group.test", "arn"),
   178  				),
   179  			},
   180  		},
   181  	})
   182  }
   183  
   184  func TestAccAWSAutoScalingGroup_autoGeneratedName(t *testing.T) {
   185  	asgNameRegexp := regexp.MustCompile("^tf-asg-")
   186  
   187  	resource.Test(t, resource.TestCase{
   188  		PreCheck:     func() { testAccPreCheck(t) },
   189  		Providers:    testAccProviders,
   190  		CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
   191  		Steps: []resource.TestStep{
   192  			resource.TestStep{
   193  				Config: testAccAWSAutoScalingGroupConfig_autoGeneratedName,
   194  				Check: resource.ComposeTestCheckFunc(
   195  					resource.TestMatchResourceAttr(
   196  						"aws_autoscaling_group.bar", "name", asgNameRegexp),
   197  					resource.TestCheckResourceAttrSet(
   198  						"aws_autoscaling_group.bar", "arn"),
   199  				),
   200  			},
   201  		},
   202  	})
   203  }
   204  
   205  func TestAccAWSAutoScalingGroup_terminationPolicies(t *testing.T) {
   206  	resource.Test(t, resource.TestCase{
   207  		PreCheck:     func() { testAccPreCheck(t) },
   208  		Providers:    testAccProviders,
   209  		CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
   210  		Steps: []resource.TestStep{
   211  			resource.TestStep{
   212  				Config: testAccAWSAutoScalingGroupConfig_terminationPoliciesEmpty,
   213  				Check: resource.ComposeTestCheckFunc(
   214  					resource.TestCheckResourceAttr(
   215  						"aws_autoscaling_group.bar", "termination_policies.#", "0"),
   216  				),
   217  			},
   218  
   219  			resource.TestStep{
   220  				Config: testAccAWSAutoScalingGroupConfig_terminationPoliciesUpdate,
   221  				Check: resource.ComposeTestCheckFunc(
   222  					resource.TestCheckResourceAttr(
   223  						"aws_autoscaling_group.bar", "termination_policies.#", "1"),
   224  					resource.TestCheckResourceAttr(
   225  						"aws_autoscaling_group.bar", "termination_policies.0", "OldestInstance"),
   226  				),
   227  			},
   228  
   229  			resource.TestStep{
   230  				Config: testAccAWSAutoScalingGroupConfig_terminationPoliciesExplicitDefault,
   231  				Check: resource.ComposeTestCheckFunc(
   232  					resource.TestCheckResourceAttr(
   233  						"aws_autoscaling_group.bar", "termination_policies.#", "1"),
   234  					resource.TestCheckResourceAttr(
   235  						"aws_autoscaling_group.bar", "termination_policies.0", "Default"),
   236  				),
   237  			},
   238  
   239  			resource.TestStep{
   240  				Config: testAccAWSAutoScalingGroupConfig_terminationPoliciesEmpty,
   241  				Check: resource.ComposeTestCheckFunc(
   242  					resource.TestCheckResourceAttr(
   243  						"aws_autoscaling_group.bar", "termination_policies.#", "0"),
   244  				),
   245  			},
   246  		},
   247  	})
   248  }
   249  
   250  func TestAccAWSAutoScalingGroup_tags(t *testing.T) {
   251  	var group autoscaling.Group
   252  
   253  	randName := fmt.Sprintf("tfautotags-%s", acctest.RandString(5))
   254  
   255  	resource.Test(t, resource.TestCase{
   256  		PreCheck:     func() { testAccPreCheck(t) },
   257  		Providers:    testAccProviders,
   258  		CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
   259  		Steps: []resource.TestStep{
   260  			resource.TestStep{
   261  				Config: testAccAWSAutoScalingGroupConfig(randName),
   262  				Check: resource.ComposeTestCheckFunc(
   263  					testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
   264  					testAccCheckAutoscalingTags(&group.Tags, "FromTags1", map[string]interface{}{
   265  						"value":               "value1",
   266  						"propagate_at_launch": true,
   267  					}),
   268  					testAccCheckAutoscalingTags(&group.Tags, "FromTags2", map[string]interface{}{
   269  						"value":               "value2",
   270  						"propagate_at_launch": true,
   271  					}),
   272  					testAccCheckAutoscalingTags(&group.Tags, "FromTags3", map[string]interface{}{
   273  						"value":               "value3",
   274  						"propagate_at_launch": true,
   275  					}),
   276  				),
   277  			},
   278  
   279  			resource.TestStep{
   280  				Config: testAccAWSAutoScalingGroupConfigUpdate(randName),
   281  				Check: resource.ComposeTestCheckFunc(
   282  					testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
   283  					testAccCheckAutoscalingTagNotExists(&group.Tags, "Foo"),
   284  					testAccCheckAutoscalingTags(&group.Tags, "FromTags1Changed", map[string]interface{}{
   285  						"value":               "value1changed",
   286  						"propagate_at_launch": true,
   287  					}),
   288  					testAccCheckAutoscalingTags(&group.Tags, "FromTags2", map[string]interface{}{
   289  						"value":               "value2changed",
   290  						"propagate_at_launch": true,
   291  					}),
   292  					testAccCheckAutoscalingTags(&group.Tags, "FromTags3", map[string]interface{}{
   293  						"value":               "value3",
   294  						"propagate_at_launch": true,
   295  					}),
   296  				),
   297  			},
   298  		},
   299  	})
   300  }
   301  
   302  func TestAccAWSAutoScalingGroup_VpcUpdates(t *testing.T) {
   303  	var group autoscaling.Group
   304  
   305  	resource.Test(t, resource.TestCase{
   306  		PreCheck:     func() { testAccPreCheck(t) },
   307  		Providers:    testAccProviders,
   308  		CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
   309  		Steps: []resource.TestStep{
   310  			resource.TestStep{
   311  				Config: testAccAWSAutoScalingGroupConfigWithAZ,
   312  				Check: resource.ComposeTestCheckFunc(
   313  					testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
   314  					resource.TestCheckResourceAttr(
   315  						"aws_autoscaling_group.bar", "availability_zones.#", "1"),
   316  					resource.TestCheckResourceAttr(
   317  						"aws_autoscaling_group.bar", "availability_zones.2487133097", "us-west-2a"),
   318  					resource.TestCheckResourceAttr(
   319  						"aws_autoscaling_group.bar", "vpc_zone_identifier.#", "1"),
   320  				),
   321  			},
   322  
   323  			resource.TestStep{
   324  				Config: testAccAWSAutoScalingGroupConfigWithVPCIdent,
   325  				Check: resource.ComposeTestCheckFunc(
   326  					testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
   327  					testAccCheckAWSAutoScalingGroupAttributesVPCZoneIdentifer(&group),
   328  					resource.TestCheckResourceAttr(
   329  						"aws_autoscaling_group.bar", "availability_zones.#", "1"),
   330  					resource.TestCheckResourceAttr(
   331  						"aws_autoscaling_group.bar", "availability_zones.2487133097", "us-west-2a"),
   332  					resource.TestCheckResourceAttr(
   333  						"aws_autoscaling_group.bar", "vpc_zone_identifier.#", "1"),
   334  				),
   335  			},
   336  		},
   337  	})
   338  }
   339  
   340  func TestAccAWSAutoScalingGroup_WithLoadBalancer(t *testing.T) {
   341  	var group autoscaling.Group
   342  
   343  	resource.Test(t, resource.TestCase{
   344  		PreCheck:     func() { testAccPreCheck(t) },
   345  		Providers:    testAccProviders,
   346  		CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
   347  		Steps: []resource.TestStep{
   348  			resource.TestStep{
   349  				Config: testAccAWSAutoScalingGroupConfigWithLoadBalancer,
   350  				Check: resource.ComposeTestCheckFunc(
   351  					testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
   352  					testAccCheckAWSAutoScalingGroupAttributesLoadBalancer(&group),
   353  				),
   354  			},
   355  		},
   356  	})
   357  }
   358  
   359  func TestAccAWSAutoScalingGroup_withPlacementGroup(t *testing.T) {
   360  	var group autoscaling.Group
   361  
   362  	randName := fmt.Sprintf("tf_placement_test-%s", acctest.RandString(5))
   363  	resource.Test(t, resource.TestCase{
   364  		PreCheck:     func() { testAccPreCheck(t) },
   365  		Providers:    testAccProviders,
   366  		CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
   367  		Steps: []resource.TestStep{
   368  			resource.TestStep{
   369  				Config: testAccAWSAutoScalingGroupConfig_withPlacementGroup(randName),
   370  				Check: resource.ComposeTestCheckFunc(
   371  					testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
   372  					resource.TestCheckResourceAttr(
   373  						"aws_autoscaling_group.bar", "placement_group", randName),
   374  				),
   375  			},
   376  		},
   377  	})
   378  }
   379  
   380  func TestAccAWSAutoScalingGroup_enablingMetrics(t *testing.T) {
   381  	var group autoscaling.Group
   382  	randName := fmt.Sprintf("terraform-test-%s", acctest.RandString(10))
   383  
   384  	resource.Test(t, resource.TestCase{
   385  		PreCheck:     func() { testAccPreCheck(t) },
   386  		Providers:    testAccProviders,
   387  		CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
   388  		Steps: []resource.TestStep{
   389  			resource.TestStep{
   390  				Config: testAccAWSAutoScalingGroupConfig(randName),
   391  				Check: resource.ComposeTestCheckFunc(
   392  					testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
   393  					resource.TestCheckNoResourceAttr(
   394  						"aws_autoscaling_group.bar", "enabled_metrics"),
   395  				),
   396  			},
   397  
   398  			resource.TestStep{
   399  				Config: testAccAWSAutoscalingMetricsCollectionConfig_updatingMetricsCollected,
   400  				Check: resource.ComposeTestCheckFunc(
   401  					testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
   402  					resource.TestCheckResourceAttr(
   403  						"aws_autoscaling_group.bar", "enabled_metrics.#", "5"),
   404  				),
   405  			},
   406  		},
   407  	})
   408  }
   409  
   410  func TestAccAWSAutoScalingGroup_suspendingProcesses(t *testing.T) {
   411  	var group autoscaling.Group
   412  	randName := fmt.Sprintf("terraform-test-%s", acctest.RandString(10))
   413  
   414  	resource.Test(t, resource.TestCase{
   415  		PreCheck:     func() { testAccPreCheck(t) },
   416  		Providers:    testAccProviders,
   417  		CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
   418  		Steps: []resource.TestStep{
   419  			{
   420  				Config: testAccAWSAutoScalingGroupConfig(randName),
   421  				Check: resource.ComposeTestCheckFunc(
   422  					testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
   423  					resource.TestCheckResourceAttr(
   424  						"aws_autoscaling_group.bar", "suspended_processes.#", "0"),
   425  				),
   426  			},
   427  			{
   428  				Config: testAccAWSAutoScalingGroupConfigWithSuspendedProcesses(randName),
   429  				Check: resource.ComposeTestCheckFunc(
   430  					testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
   431  					resource.TestCheckResourceAttr(
   432  						"aws_autoscaling_group.bar", "suspended_processes.#", "2"),
   433  				),
   434  			},
   435  			{
   436  				Config: testAccAWSAutoScalingGroupConfigWithSuspendedProcessesUpdated(randName),
   437  				Check: resource.ComposeTestCheckFunc(
   438  					testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
   439  					resource.TestCheckResourceAttr(
   440  						"aws_autoscaling_group.bar", "suspended_processes.#", "2"),
   441  				),
   442  			},
   443  		},
   444  	})
   445  }
   446  
   447  func TestAccAWSAutoScalingGroup_withMetrics(t *testing.T) {
   448  	var group autoscaling.Group
   449  
   450  	resource.Test(t, resource.TestCase{
   451  		PreCheck:     func() { testAccPreCheck(t) },
   452  		Providers:    testAccProviders,
   453  		CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
   454  		Steps: []resource.TestStep{
   455  			resource.TestStep{
   456  				Config: testAccAWSAutoscalingMetricsCollectionConfig_allMetricsCollected,
   457  				Check: resource.ComposeTestCheckFunc(
   458  					testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
   459  					resource.TestCheckResourceAttr(
   460  						"aws_autoscaling_group.bar", "enabled_metrics.#", "7"),
   461  				),
   462  			},
   463  
   464  			resource.TestStep{
   465  				Config: testAccAWSAutoscalingMetricsCollectionConfig_updatingMetricsCollected,
   466  				Check: resource.ComposeTestCheckFunc(
   467  					testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
   468  					resource.TestCheckResourceAttr(
   469  						"aws_autoscaling_group.bar", "enabled_metrics.#", "5"),
   470  				),
   471  			},
   472  		},
   473  	})
   474  }
   475  
   476  func TestAccAWSAutoScalingGroup_ALB_TargetGroups(t *testing.T) {
   477  	var group autoscaling.Group
   478  	var tg elbv2.TargetGroup
   479  	var tg2 elbv2.TargetGroup
   480  
   481  	testCheck := func(targets []*elbv2.TargetGroup) resource.TestCheckFunc {
   482  		return func(*terraform.State) error {
   483  			var ts []string
   484  			var gs []string
   485  			for _, t := range targets {
   486  				ts = append(ts, *t.TargetGroupArn)
   487  			}
   488  
   489  			for _, s := range group.TargetGroupARNs {
   490  				gs = append(gs, *s)
   491  			}
   492  
   493  			sort.Strings(ts)
   494  			sort.Strings(gs)
   495  
   496  			if !reflect.DeepEqual(ts, gs) {
   497  				return fmt.Errorf("Error: target group match not found!\nASG Target groups: %#v\nTarget Group: %#v", ts, gs)
   498  			}
   499  			return nil
   500  		}
   501  	}
   502  
   503  	resource.Test(t, resource.TestCase{
   504  		PreCheck:     func() { testAccPreCheck(t) },
   505  		Providers:    testAccProviders,
   506  		CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
   507  		Steps: []resource.TestStep{
   508  			resource.TestStep{
   509  				Config: testAccAWSAutoScalingGroupConfig_ALB_TargetGroup_pre,
   510  				Check: resource.ComposeAggregateTestCheckFunc(
   511  					testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
   512  					testAccCheckAWSALBTargetGroupExists("aws_alb_target_group.test", &tg),
   513  					resource.TestCheckResourceAttr(
   514  						"aws_autoscaling_group.bar", "target_group_arns.#", "0"),
   515  				),
   516  			},
   517  
   518  			resource.TestStep{
   519  				Config: testAccAWSAutoScalingGroupConfig_ALB_TargetGroup_post_duo,
   520  				Check: resource.ComposeAggregateTestCheckFunc(
   521  					testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
   522  					testAccCheckAWSALBTargetGroupExists("aws_alb_target_group.test", &tg),
   523  					testAccCheckAWSALBTargetGroupExists("aws_alb_target_group.test_more", &tg2),
   524  					testCheck([]*elbv2.TargetGroup{&tg, &tg2}),
   525  					resource.TestCheckResourceAttr(
   526  						"aws_autoscaling_group.bar", "target_group_arns.#", "2"),
   527  				),
   528  			},
   529  
   530  			resource.TestStep{
   531  				Config: testAccAWSAutoScalingGroupConfig_ALB_TargetGroup_post,
   532  				Check: resource.ComposeAggregateTestCheckFunc(
   533  					testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
   534  					testAccCheckAWSALBTargetGroupExists("aws_alb_target_group.test", &tg),
   535  					testCheck([]*elbv2.TargetGroup{&tg}),
   536  					resource.TestCheckResourceAttr(
   537  						"aws_autoscaling_group.bar", "target_group_arns.#", "1"),
   538  				),
   539  			},
   540  		},
   541  	})
   542  }
   543  
   544  func TestAccAWSAutoScalingGroup_initialLifecycleHook(t *testing.T) {
   545  	var group autoscaling.Group
   546  
   547  	randName := fmt.Sprintf("terraform-test-%s", acctest.RandString(10))
   548  
   549  	resource.Test(t, resource.TestCase{
   550  		PreCheck:        func() { testAccPreCheck(t) },
   551  		IDRefreshName:   "aws_autoscaling_group.bar",
   552  		IDRefreshIgnore: []string{"force_delete", "metrics_granularity", "wait_for_capacity_timeout"},
   553  		Providers:       testAccProviders,
   554  		CheckDestroy:    testAccCheckAWSAutoScalingGroupDestroy,
   555  		Steps: []resource.TestStep{
   556  			resource.TestStep{
   557  				Config: testAccAWSAutoScalingGroupWithHookConfig(randName),
   558  				Check: resource.ComposeTestCheckFunc(
   559  					testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
   560  					testAccCheckAWSAutoScalingGroupHealthyCapacity(&group, 2),
   561  					resource.TestCheckResourceAttr(
   562  						"aws_autoscaling_group.bar", "initial_lifecycle_hook.#", "1"),
   563  					resource.TestCheckResourceAttr(
   564  						"aws_autoscaling_group.bar", "initial_lifecycle_hook.391359060.default_result", "CONTINUE"),
   565  					resource.TestCheckResourceAttr(
   566  						"aws_autoscaling_group.bar", "initial_lifecycle_hook.391359060.name", "launching"),
   567  					testAccCheckAWSAutoScalingGroupInitialLifecycleHookExists(
   568  						"aws_autoscaling_group.bar", "initial_lifecycle_hook.391359060.name"),
   569  				),
   570  			},
   571  		},
   572  	})
   573  }
   574  
   575  func TestAccAWSAutoScalingGroup_ALB_TargetGroups_ELBCapacity(t *testing.T) {
   576  	var group autoscaling.Group
   577  	var tg elbv2.TargetGroup
   578  
   579  	rInt := acctest.RandInt()
   580  
   581  	resource.Test(t, resource.TestCase{
   582  		PreCheck:     func() { testAccPreCheck(t) },
   583  		Providers:    testAccProviders,
   584  		CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
   585  		Steps: []resource.TestStep{
   586  			resource.TestStep{
   587  				Config: testAccAWSAutoScalingGroupConfig_ALB_TargetGroup_ELBCapacity(rInt),
   588  				Check: resource.ComposeAggregateTestCheckFunc(
   589  					testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
   590  					testAccCheckAWSALBTargetGroupExists("aws_alb_target_group.test", &tg),
   591  					testAccCheckAWSALBTargetGroupHealthy(&tg),
   592  				),
   593  			},
   594  		},
   595  	})
   596  }
   597  
   598  func testAccCheckAWSAutoScalingGroupDestroy(s *terraform.State) error {
   599  	conn := testAccProvider.Meta().(*AWSClient).autoscalingconn
   600  
   601  	for _, rs := range s.RootModule().Resources {
   602  		if rs.Type != "aws_autoscaling_group" {
   603  			continue
   604  		}
   605  
   606  		// Try to find the Group
   607  		describeGroups, err := conn.DescribeAutoScalingGroups(
   608  			&autoscaling.DescribeAutoScalingGroupsInput{
   609  				AutoScalingGroupNames: []*string{aws.String(rs.Primary.ID)},
   610  			})
   611  
   612  		if err == nil {
   613  			if len(describeGroups.AutoScalingGroups) != 0 &&
   614  				*describeGroups.AutoScalingGroups[0].AutoScalingGroupName == rs.Primary.ID {
   615  				return fmt.Errorf("AutoScaling Group still exists")
   616  			}
   617  		}
   618  
   619  		// Verify the error
   620  		ec2err, ok := err.(awserr.Error)
   621  		if !ok {
   622  			return err
   623  		}
   624  		if ec2err.Code() != "InvalidGroup.NotFound" {
   625  			return err
   626  		}
   627  	}
   628  
   629  	return nil
   630  }
   631  
   632  func testAccCheckAWSAutoScalingGroupAttributes(group *autoscaling.Group, name string) resource.TestCheckFunc {
   633  	return func(s *terraform.State) error {
   634  		if *group.AvailabilityZones[0] != "us-west-2a" {
   635  			return fmt.Errorf("Bad availability_zones: %#v", group.AvailabilityZones[0])
   636  		}
   637  
   638  		if *group.AutoScalingGroupName != name {
   639  			return fmt.Errorf("Bad Autoscaling Group name, expected (%s), got (%s)", name, *group.AutoScalingGroupName)
   640  		}
   641  
   642  		if *group.MaxSize != 5 {
   643  			return fmt.Errorf("Bad max_size: %d", *group.MaxSize)
   644  		}
   645  
   646  		if *group.MinSize != 2 {
   647  			return fmt.Errorf("Bad max_size: %d", *group.MinSize)
   648  		}
   649  
   650  		if *group.HealthCheckType != "ELB" {
   651  			return fmt.Errorf("Bad health_check_type,\nexpected: %s\ngot: %s", "ELB", *group.HealthCheckType)
   652  		}
   653  
   654  		if *group.HealthCheckGracePeriod != 300 {
   655  			return fmt.Errorf("Bad health_check_grace_period: %d", *group.HealthCheckGracePeriod)
   656  		}
   657  
   658  		if *group.DesiredCapacity != 4 {
   659  			return fmt.Errorf("Bad desired_capacity: %d", *group.DesiredCapacity)
   660  		}
   661  
   662  		if *group.LaunchConfigurationName == "" {
   663  			return fmt.Errorf("Bad launch configuration name: %s", *group.LaunchConfigurationName)
   664  		}
   665  
   666  		t := &autoscaling.TagDescription{
   667  			Key:               aws.String("FromTags1"),
   668  			Value:             aws.String("value1"),
   669  			PropagateAtLaunch: aws.Bool(true),
   670  			ResourceType:      aws.String("auto-scaling-group"),
   671  			ResourceId:        group.AutoScalingGroupName,
   672  		}
   673  
   674  		if !reflect.DeepEqual(group.Tags[0], t) {
   675  			return fmt.Errorf(
   676  				"Got:\n\n%#v\n\nExpected:\n\n%#v\n",
   677  				group.Tags[0],
   678  				t)
   679  		}
   680  
   681  		return nil
   682  	}
   683  }
   684  
   685  func testAccCheckAWSAutoScalingGroupAttributesLoadBalancer(group *autoscaling.Group) resource.TestCheckFunc {
   686  	return func(s *terraform.State) error {
   687  		if len(group.LoadBalancerNames) != 1 {
   688  			return fmt.Errorf("Bad load_balancers: %v", group.LoadBalancerNames)
   689  		}
   690  
   691  		return nil
   692  	}
   693  }
   694  
   695  func testAccCheckAWSAutoScalingGroupExists(n string, group *autoscaling.Group) resource.TestCheckFunc {
   696  	return func(s *terraform.State) error {
   697  		rs, ok := s.RootModule().Resources[n]
   698  		if !ok {
   699  			return fmt.Errorf("Not found: %s", n)
   700  		}
   701  
   702  		if rs.Primary.ID == "" {
   703  			return fmt.Errorf("No AutoScaling Group ID is set")
   704  		}
   705  
   706  		conn := testAccProvider.Meta().(*AWSClient).autoscalingconn
   707  
   708  		describeGroups, err := conn.DescribeAutoScalingGroups(
   709  			&autoscaling.DescribeAutoScalingGroupsInput{
   710  				AutoScalingGroupNames: []*string{aws.String(rs.Primary.ID)},
   711  			})
   712  
   713  		if err != nil {
   714  			return err
   715  		}
   716  
   717  		if len(describeGroups.AutoScalingGroups) != 1 ||
   718  			*describeGroups.AutoScalingGroups[0].AutoScalingGroupName != rs.Primary.ID {
   719  			return fmt.Errorf("AutoScaling Group not found")
   720  		}
   721  
   722  		*group = *describeGroups.AutoScalingGroups[0]
   723  
   724  		return nil
   725  	}
   726  }
   727  
   728  func testAccCheckAWSAutoScalingGroupInitialLifecycleHookExists(asg, hookAttr string) resource.TestCheckFunc {
   729  	return func(s *terraform.State) error {
   730  		asgResource, ok := s.RootModule().Resources[asg]
   731  		if !ok {
   732  			return fmt.Errorf("Not found: %s", asg)
   733  		}
   734  
   735  		if asgResource.Primary.ID == "" {
   736  			return fmt.Errorf("No AutoScaling Group ID is set")
   737  		}
   738  
   739  		hookName := asgResource.Primary.Attributes[hookAttr]
   740  		if hookName == "" {
   741  			return fmt.Errorf("ASG %s has no hook name %s", asg, hookAttr)
   742  		}
   743  
   744  		return checkLifecycleHookExistsByName(asgResource.Primary.ID, hookName)
   745  	}
   746  }
   747  
   748  func testLaunchConfigurationName(n string, lc *autoscaling.LaunchConfiguration) resource.TestCheckFunc {
   749  	return func(s *terraform.State) error {
   750  		rs, ok := s.RootModule().Resources[n]
   751  		if !ok {
   752  			return fmt.Errorf("Not found: %s", n)
   753  		}
   754  
   755  		if *lc.LaunchConfigurationName != rs.Primary.Attributes["launch_configuration"] {
   756  			return fmt.Errorf("Launch configuration names do not match")
   757  		}
   758  
   759  		return nil
   760  	}
   761  }
   762  
   763  func testAccCheckAWSAutoScalingGroupHealthyCapacity(
   764  	g *autoscaling.Group, exp int) resource.TestCheckFunc {
   765  	return func(s *terraform.State) error {
   766  		healthy := 0
   767  		for _, i := range g.Instances {
   768  			if i.HealthStatus == nil {
   769  				continue
   770  			}
   771  			if strings.EqualFold(*i.HealthStatus, "Healthy") {
   772  				healthy++
   773  			}
   774  		}
   775  		if healthy < exp {
   776  			return fmt.Errorf("Expected at least %d healthy, got %d.", exp, healthy)
   777  		}
   778  		return nil
   779  	}
   780  }
   781  
   782  func testAccCheckAWSAutoScalingGroupAttributesVPCZoneIdentifer(group *autoscaling.Group) resource.TestCheckFunc {
   783  	return func(s *terraform.State) error {
   784  		// Grab Subnet Ids
   785  		var subnets []string
   786  		for _, rs := range s.RootModule().Resources {
   787  			if rs.Type != "aws_subnet" {
   788  				continue
   789  			}
   790  			subnets = append(subnets, rs.Primary.Attributes["id"])
   791  		}
   792  
   793  		if group.VPCZoneIdentifier == nil {
   794  			return fmt.Errorf("Bad VPC Zone Identifier\nexpected: %s\ngot nil", subnets)
   795  		}
   796  
   797  		zones := strings.Split(*group.VPCZoneIdentifier, ",")
   798  
   799  		remaining := len(zones)
   800  		for _, z := range zones {
   801  			for _, s := range subnets {
   802  				if z == s {
   803  					remaining--
   804  				}
   805  			}
   806  		}
   807  
   808  		if remaining != 0 {
   809  			return fmt.Errorf("Bad VPC Zone Identifier match\nexpected: %s\ngot:%s", zones, subnets)
   810  		}
   811  
   812  		return nil
   813  	}
   814  }
   815  
   816  // testAccCheckAWSALBTargetGroupHealthy checks an *elbv2.TargetGroup to make
   817  // sure that all instances in it are healthy.
   818  func testAccCheckAWSALBTargetGroupHealthy(res *elbv2.TargetGroup) resource.TestCheckFunc {
   819  	return func(s *terraform.State) error {
   820  		conn := testAccProvider.Meta().(*AWSClient).elbv2conn
   821  
   822  		resp, err := conn.DescribeTargetHealth(&elbv2.DescribeTargetHealthInput{
   823  			TargetGroupArn: res.TargetGroupArn,
   824  		})
   825  
   826  		if err != nil {
   827  			return err
   828  		}
   829  
   830  		for _, target := range resp.TargetHealthDescriptions {
   831  			if target.TargetHealth == nil || target.TargetHealth.State == nil || *target.TargetHealth.State != "healthy" {
   832  				return errors.New("Not all instances in target group are healthy yet, but should be")
   833  			}
   834  		}
   835  
   836  		return nil
   837  	}
   838  }
   839  
   840  const testAccAWSAutoScalingGroupConfig_autoGeneratedName = `
   841  resource "aws_launch_configuration" "foobar" {
   842    image_id = "ami-21f78e11"
   843    instance_type = "t1.micro"
   844  }
   845  
   846  resource "aws_autoscaling_group" "bar" {
   847    availability_zones = ["us-west-2a"]
   848    desired_capacity = 0
   849    max_size = 0
   850    min_size = 0
   851    launch_configuration = "${aws_launch_configuration.foobar.name}"
   852  }
   853  `
   854  
   855  const testAccAWSAutoScalingGroupConfig_namePrefix = `
   856  resource "aws_launch_configuration" "test" {
   857    image_id = "ami-21f78e11"
   858    instance_type = "t1.micro"
   859  }
   860  
   861  resource "aws_autoscaling_group" "test" {
   862    availability_zones = ["us-west-2a"]
   863    desired_capacity = 0
   864    max_size = 0
   865    min_size = 0
   866    name_prefix = "test-"
   867    launch_configuration = "${aws_launch_configuration.test.name}"
   868  }
   869  `
   870  
   871  const testAccAWSAutoScalingGroupConfig_terminationPoliciesEmpty = `
   872  resource "aws_launch_configuration" "foobar" {
   873    image_id = "ami-21f78e11"
   874    instance_type = "t1.micro"
   875  }
   876  
   877  resource "aws_autoscaling_group" "bar" {
   878    availability_zones = ["us-west-2a"]
   879    max_size = 0
   880    min_size = 0
   881    desired_capacity = 0
   882  
   883    launch_configuration = "${aws_launch_configuration.foobar.name}"
   884  }
   885  `
   886  
   887  const testAccAWSAutoScalingGroupConfig_terminationPoliciesExplicitDefault = `
   888  resource "aws_launch_configuration" "foobar" {
   889    image_id = "ami-21f78e11"
   890    instance_type = "t1.micro"
   891  }
   892  
   893  resource "aws_autoscaling_group" "bar" {
   894    availability_zones = ["us-west-2a"]
   895    max_size = 0
   896    min_size = 0
   897    desired_capacity = 0
   898    termination_policies = ["Default"]
   899  
   900    launch_configuration = "${aws_launch_configuration.foobar.name}"
   901  }
   902  `
   903  
   904  const testAccAWSAutoScalingGroupConfig_terminationPoliciesUpdate = `
   905  resource "aws_launch_configuration" "foobar" {
   906    image_id = "ami-21f78e11"
   907    instance_type = "t1.micro"
   908  }
   909  
   910  resource "aws_autoscaling_group" "bar" {
   911    availability_zones = ["us-west-2a"]
   912    max_size = 0
   913    min_size = 0
   914    desired_capacity = 0
   915    termination_policies = ["OldestInstance"]
   916  
   917    launch_configuration = "${aws_launch_configuration.foobar.name}"
   918  }
   919  `
   920  
   921  func testAccAWSAutoScalingGroupConfig(name string) string {
   922  	return fmt.Sprintf(`
   923  resource "aws_launch_configuration" "foobar" {
   924    image_id = "ami-21f78e11"
   925    instance_type = "t1.micro"
   926  }
   927  
   928  resource "aws_placement_group" "test" {
   929    name = "asg_pg_%s"
   930    strategy = "cluster"
   931  }
   932  
   933  resource "aws_autoscaling_group" "bar" {
   934    availability_zones = ["us-west-2a"]
   935    name = "%s"
   936    max_size = 5
   937    min_size = 2
   938    health_check_type = "ELB"
   939    desired_capacity = 4
   940    force_delete = true
   941    termination_policies = ["OldestInstance","ClosestToNextInstanceHour"]
   942  
   943    launch_configuration = "${aws_launch_configuration.foobar.name}"
   944  
   945    tags = [
   946      {
   947        key = "FromTags1"
   948        value = "value1"
   949        propagate_at_launch = true
   950      },
   951      {
   952        key = "FromTags2"
   953        value = "value2"
   954        propagate_at_launch = true
   955      },
   956      {
   957        key = "FromTags3"
   958        value = "value3"
   959        propagate_at_launch = true
   960      },
   961    ]
   962  }
   963  `, name, name)
   964  }
   965  
   966  func testAccAWSAutoScalingGroupConfigUpdate(name string) string {
   967  	return fmt.Sprintf(`
   968  resource "aws_launch_configuration" "foobar" {
   969    image_id = "ami-21f78e11"
   970    instance_type = "t1.micro"
   971  }
   972  
   973  resource "aws_launch_configuration" "new" {
   974    image_id = "ami-21f78e11"
   975    instance_type = "t1.micro"
   976  }
   977  
   978  resource "aws_autoscaling_group" "bar" {
   979    availability_zones = ["us-west-2a"]
   980    name = "%s"
   981    max_size = 5
   982    min_size = 2
   983    health_check_grace_period = 300
   984    health_check_type = "ELB"
   985    desired_capacity = 5
   986    force_delete = true
   987    termination_policies = ["ClosestToNextInstanceHour"]
   988    protect_from_scale_in = true
   989  
   990    launch_configuration = "${aws_launch_configuration.new.name}"
   991  
   992    tags = [
   993      {
   994        key = "FromTags1Changed"
   995        value = "value1changed"
   996        propagate_at_launch = true
   997      },
   998      {
   999        key = "FromTags2"
  1000        value = "value2changed"
  1001        propagate_at_launch = true
  1002      },
  1003      {
  1004        key = "FromTags3"
  1005        value = "value3"
  1006        propagate_at_launch = true
  1007      },
  1008    ]
  1009  }
  1010  `, name)
  1011  }
  1012  
  1013  func testAccAWSAutoScalingGroupImport(name string) string {
  1014  	return fmt.Sprintf(`
  1015  resource "aws_launch_configuration" "foobar" {
  1016    image_id = "ami-21f78e11"
  1017    instance_type = "t1.micro"
  1018  }
  1019  
  1020  resource "aws_placement_group" "test" {
  1021    name = "asg_pg_%s"
  1022    strategy = "cluster"
  1023  }
  1024  
  1025  resource "aws_autoscaling_group" "bar" {
  1026    availability_zones = ["us-west-2a"]
  1027    name = "%s"
  1028    max_size = 5
  1029    min_size = 2
  1030    health_check_type = "ELB"
  1031    desired_capacity = 4
  1032    force_delete = true
  1033    termination_policies = ["OldestInstance","ClosestToNextInstanceHour"]
  1034  
  1035    launch_configuration = "${aws_launch_configuration.foobar.name}"
  1036  
  1037    tag {
  1038      key = "FromTags1"
  1039      value = "value1"
  1040      propagate_at_launch = true
  1041    }
  1042  
  1043    tag {
  1044      key = "FromTags2"
  1045      value = "value2"
  1046      propagate_at_launch = true
  1047    }
  1048  
  1049    tag {
  1050      key = "FromTags3"
  1051      value = "value3"
  1052      propagate_at_launch = true
  1053    }
  1054  }
  1055  `, name, name)
  1056  }
  1057  
  1058  const testAccAWSAutoScalingGroupConfigWithLoadBalancer = `
  1059  resource "aws_vpc" "foo" {
  1060    cidr_block = "10.1.0.0/16"
  1061  	tags { Name = "tf-asg-test" }
  1062  }
  1063  
  1064  resource "aws_internet_gateway" "gw" {
  1065    vpc_id = "${aws_vpc.foo.id}"
  1066  }
  1067  
  1068  resource "aws_subnet" "foo" {
  1069  	cidr_block = "10.1.1.0/24"
  1070  	vpc_id = "${aws_vpc.foo.id}"
  1071  }
  1072  
  1073  resource "aws_security_group" "foo" {
  1074    vpc_id="${aws_vpc.foo.id}"
  1075  
  1076    ingress {
  1077      protocol = "-1"
  1078      from_port = 0
  1079      to_port = 0
  1080      cidr_blocks = ["0.0.0.0/0"]
  1081    }
  1082  
  1083    egress {
  1084      protocol = "-1"
  1085      from_port = 0
  1086      to_port = 0
  1087      cidr_blocks = ["0.0.0.0/0"]
  1088    }
  1089  }
  1090  
  1091  resource "aws_elb" "bar" {
  1092    subnets = ["${aws_subnet.foo.id}"]
  1093  	security_groups = ["${aws_security_group.foo.id}"]
  1094  
  1095    listener {
  1096      instance_port = 80
  1097      instance_protocol = "http"
  1098      lb_port = 80
  1099      lb_protocol = "http"
  1100    }
  1101  
  1102    health_check {
  1103      healthy_threshold = 2
  1104      unhealthy_threshold = 2
  1105      target = "HTTP:80/"
  1106      interval = 5
  1107      timeout = 2
  1108    }
  1109  
  1110  	depends_on = ["aws_internet_gateway.gw"]
  1111  }
  1112  
  1113  resource "aws_launch_configuration" "foobar" {
  1114    // need an AMI that listens on :80 at boot, this is:
  1115    // bitnami-nginxstack-1.6.1-0-linux-ubuntu-14.04.1-x86_64-hvm-ebs-ami-99f5b1a9-3
  1116    image_id = "ami-b5b3fc85"
  1117    instance_type = "t2.micro"
  1118  	security_groups = ["${aws_security_group.foo.id}"]
  1119  }
  1120  
  1121  resource "aws_autoscaling_group" "bar" {
  1122    availability_zones = ["${aws_subnet.foo.availability_zone}"]
  1123  	vpc_zone_identifier = ["${aws_subnet.foo.id}"]
  1124    max_size = 2
  1125    min_size = 2
  1126    health_check_grace_period = 300
  1127    health_check_type = "ELB"
  1128    wait_for_elb_capacity = 2
  1129    force_delete = true
  1130  
  1131    launch_configuration = "${aws_launch_configuration.foobar.name}"
  1132    load_balancers = ["${aws_elb.bar.name}"]
  1133  }
  1134  `
  1135  
  1136  const testAccAWSAutoScalingGroupConfigWithAZ = `
  1137  resource "aws_vpc" "default" {
  1138    cidr_block = "10.0.0.0/16"
  1139    tags {
  1140       Name = "terraform-test"
  1141    }
  1142  }
  1143  
  1144  resource "aws_subnet" "main" {
  1145    vpc_id = "${aws_vpc.default.id}"
  1146    cidr_block = "10.0.1.0/24"
  1147    availability_zone = "us-west-2a"
  1148    tags {
  1149       Name = "terraform-test"
  1150    }
  1151  }
  1152  
  1153  resource "aws_launch_configuration" "foobar" {
  1154    image_id = "ami-b5b3fc85"
  1155    instance_type = "t2.micro"
  1156  }
  1157  
  1158  resource "aws_autoscaling_group" "bar" {
  1159    availability_zones = [
  1160  	  "us-west-2a"
  1161    ]
  1162    desired_capacity = 0
  1163    max_size = 0
  1164    min_size = 0
  1165    launch_configuration = "${aws_launch_configuration.foobar.name}"
  1166  }
  1167  `
  1168  
  1169  const testAccAWSAutoScalingGroupConfigWithVPCIdent = `
  1170  resource "aws_vpc" "default" {
  1171    cidr_block = "10.0.0.0/16"
  1172    tags {
  1173       Name = "terraform-test"
  1174    }
  1175  }
  1176  
  1177  resource "aws_subnet" "main" {
  1178    vpc_id = "${aws_vpc.default.id}"
  1179    cidr_block = "10.0.1.0/24"
  1180    availability_zone = "us-west-2a"
  1181    tags {
  1182       Name = "terraform-test"
  1183    }
  1184  }
  1185  
  1186  resource "aws_launch_configuration" "foobar" {
  1187    image_id = "ami-b5b3fc85"
  1188    instance_type = "t2.micro"
  1189  }
  1190  
  1191  resource "aws_autoscaling_group" "bar" {
  1192    vpc_zone_identifier = [
  1193      "${aws_subnet.main.id}",
  1194    ]
  1195    desired_capacity = 0
  1196    max_size = 0
  1197    min_size = 0
  1198    launch_configuration = "${aws_launch_configuration.foobar.name}"
  1199  }
  1200  `
  1201  
  1202  func testAccAWSAutoScalingGroupConfig_withPlacementGroup(name string) string {
  1203  	return fmt.Sprintf(`
  1204  resource "aws_launch_configuration" "foobar" {
  1205    image_id = "ami-21f78e11"
  1206    instance_type = "c3.large"
  1207  }
  1208  
  1209  resource "aws_placement_group" "test" {
  1210    name = "%s"
  1211    strategy = "cluster"
  1212  }
  1213  
  1214  resource "aws_autoscaling_group" "bar" {
  1215    availability_zones = ["us-west-2a"]
  1216    name = "%s"
  1217    max_size = 1
  1218    min_size = 1
  1219    health_check_grace_period = 300
  1220    health_check_type = "ELB"
  1221    desired_capacity = 1
  1222    force_delete = true
  1223    termination_policies = ["OldestInstance","ClosestToNextInstanceHour"]
  1224    placement_group = "${aws_placement_group.test.name}"
  1225  
  1226    launch_configuration = "${aws_launch_configuration.foobar.name}"
  1227  
  1228    tag {
  1229      key = "Foo"
  1230      value = "foo-bar"
  1231      propagate_at_launch = true
  1232    }
  1233  }
  1234  `, name, name)
  1235  }
  1236  
  1237  const testAccAWSAutoscalingMetricsCollectionConfig_allMetricsCollected = `
  1238  resource "aws_launch_configuration" "foobar" {
  1239    image_id = "ami-21f78e11"
  1240    instance_type = "t1.micro"
  1241  }
  1242  
  1243  resource "aws_autoscaling_group" "bar" {
  1244    availability_zones = ["us-west-2a"]
  1245    max_size = 1
  1246    min_size = 0
  1247    health_check_grace_period = 300
  1248    health_check_type = "EC2"
  1249    desired_capacity = 0
  1250    force_delete = true
  1251    termination_policies = ["OldestInstance","ClosestToNextInstanceHour"]
  1252    launch_configuration = "${aws_launch_configuration.foobar.name}"
  1253    enabled_metrics = ["GroupTotalInstances",
  1254    	     "GroupPendingInstances",
  1255    	     "GroupTerminatingInstances",
  1256    	     "GroupDesiredCapacity",
  1257    	     "GroupInServiceInstances",
  1258    	     "GroupMinSize",
  1259    	     "GroupMaxSize"
  1260    ]
  1261    metrics_granularity = "1Minute"
  1262  }
  1263  `
  1264  
  1265  const testAccAWSAutoscalingMetricsCollectionConfig_updatingMetricsCollected = `
  1266  resource "aws_launch_configuration" "foobar" {
  1267    image_id = "ami-21f78e11"
  1268    instance_type = "t1.micro"
  1269  }
  1270  
  1271  resource "aws_autoscaling_group" "bar" {
  1272    availability_zones = ["us-west-2a"]
  1273    max_size = 1
  1274    min_size = 0
  1275    health_check_grace_period = 300
  1276    health_check_type = "EC2"
  1277    desired_capacity = 0
  1278    force_delete = true
  1279    termination_policies = ["OldestInstance","ClosestToNextInstanceHour"]
  1280    launch_configuration = "${aws_launch_configuration.foobar.name}"
  1281    enabled_metrics = ["GroupTotalInstances",
  1282    	     "GroupPendingInstances",
  1283    	     "GroupTerminatingInstances",
  1284    	     "GroupDesiredCapacity",
  1285    	     "GroupMaxSize"
  1286    ]
  1287    metrics_granularity = "1Minute"
  1288  }
  1289  `
  1290  
  1291  const testAccAWSAutoScalingGroupConfig_ALB_TargetGroup_pre = `
  1292  provider "aws" {
  1293    region = "us-west-2"
  1294  }
  1295  
  1296  resource "aws_vpc" "default" {
  1297    cidr_block = "10.0.0.0/16"
  1298  
  1299    tags {
  1300      Name = "testAccAWSAutoScalingGroupConfig_ALB_TargetGroup"
  1301    }
  1302  }
  1303  
  1304  resource "aws_alb_target_group" "test" {
  1305    name     = "tf-example-alb-tg"
  1306    port     = 80
  1307    protocol = "HTTP"
  1308    vpc_id   = "${aws_vpc.default.id}"
  1309  }
  1310  
  1311  resource "aws_subnet" "main" {
  1312    vpc_id            = "${aws_vpc.default.id}"
  1313    cidr_block        = "10.0.1.0/24"
  1314    availability_zone = "us-west-2a"
  1315  
  1316    tags {
  1317      Name = "testAccAWSAutoScalingGroupConfig_ALB_TargetGroup"
  1318    }
  1319  }
  1320  
  1321  resource "aws_subnet" "alt" {
  1322    vpc_id            = "${aws_vpc.default.id}"
  1323    cidr_block        = "10.0.2.0/24"
  1324    availability_zone = "us-west-2b"
  1325  
  1326    tags {
  1327      Name = "testAccAWSAutoScalingGroupConfig_ALB_TargetGroup"
  1328    }
  1329  }
  1330  
  1331  resource "aws_launch_configuration" "foobar" {
  1332    # Golang-base from cts-hashi aws account, shared with tf testing account
  1333    image_id          = "ami-1817d178"
  1334    instance_type     = "t2.micro"
  1335    enable_monitoring = false
  1336  }
  1337  
  1338  resource "aws_autoscaling_group" "bar" {
  1339    vpc_zone_identifier = [
  1340      "${aws_subnet.main.id}",
  1341      "${aws_subnet.alt.id}",
  1342    ]
  1343  
  1344    max_size                  = 2
  1345    min_size                  = 0
  1346    health_check_grace_period = 300
  1347    health_check_type         = "ELB"
  1348    desired_capacity          = 0
  1349    force_delete              = true
  1350    termination_policies      = ["OldestInstance"]
  1351    launch_configuration      = "${aws_launch_configuration.foobar.name}"
  1352  
  1353  }
  1354  
  1355  resource "aws_security_group" "tf_test_self" {
  1356    name        = "tf_test_alb_asg"
  1357    description = "tf_test_alb_asg"
  1358    vpc_id      = "${aws_vpc.default.id}"
  1359  
  1360    ingress {
  1361      from_port   = 80
  1362      to_port     = 80
  1363      protocol    = "tcp"
  1364      cidr_blocks = ["0.0.0.0/0"]
  1365    }
  1366  
  1367    tags {
  1368      Name = "testAccAWSAutoScalingGroupConfig_ALB_TargetGroup"
  1369    }
  1370  }
  1371  `
  1372  
  1373  const testAccAWSAutoScalingGroupConfig_ALB_TargetGroup_post = `
  1374  provider "aws" {
  1375    region = "us-west-2"
  1376  }
  1377  
  1378  resource "aws_vpc" "default" {
  1379    cidr_block = "10.0.0.0/16"
  1380  
  1381    tags {
  1382      Name = "testAccAWSAutoScalingGroupConfig_ALB_TargetGroup"
  1383    }
  1384  }
  1385  
  1386  resource "aws_alb_target_group" "test" {
  1387    name     = "tf-example-alb-tg"
  1388    port     = 80
  1389    protocol = "HTTP"
  1390    vpc_id   = "${aws_vpc.default.id}"
  1391  }
  1392  
  1393  resource "aws_subnet" "main" {
  1394    vpc_id            = "${aws_vpc.default.id}"
  1395    cidr_block        = "10.0.1.0/24"
  1396    availability_zone = "us-west-2a"
  1397  
  1398    tags {
  1399      Name = "testAccAWSAutoScalingGroupConfig_ALB_TargetGroup"
  1400    }
  1401  }
  1402  
  1403  resource "aws_subnet" "alt" {
  1404    vpc_id            = "${aws_vpc.default.id}"
  1405    cidr_block        = "10.0.2.0/24"
  1406    availability_zone = "us-west-2b"
  1407  
  1408    tags {
  1409      Name = "testAccAWSAutoScalingGroupConfig_ALB_TargetGroup"
  1410    }
  1411  }
  1412  
  1413  resource "aws_launch_configuration" "foobar" {
  1414    # Golang-base from cts-hashi aws account, shared with tf testing account
  1415    image_id          = "ami-1817d178"
  1416    instance_type     = "t2.micro"
  1417    enable_monitoring = false
  1418  }
  1419  
  1420  resource "aws_autoscaling_group" "bar" {
  1421    vpc_zone_identifier = [
  1422      "${aws_subnet.main.id}",
  1423      "${aws_subnet.alt.id}",
  1424    ]
  1425  
  1426  	target_group_arns = ["${aws_alb_target_group.test.arn}"]
  1427  
  1428    max_size                  = 2
  1429    min_size                  = 0
  1430    health_check_grace_period = 300
  1431    health_check_type         = "ELB"
  1432    desired_capacity          = 0
  1433    force_delete              = true
  1434    termination_policies      = ["OldestInstance"]
  1435    launch_configuration      = "${aws_launch_configuration.foobar.name}"
  1436  
  1437  }
  1438  
  1439  resource "aws_security_group" "tf_test_self" {
  1440    name        = "tf_test_alb_asg"
  1441    description = "tf_test_alb_asg"
  1442    vpc_id      = "${aws_vpc.default.id}"
  1443  
  1444    ingress {
  1445      from_port   = 80
  1446      to_port     = 80
  1447      protocol    = "tcp"
  1448      cidr_blocks = ["0.0.0.0/0"]
  1449    }
  1450  
  1451    tags {
  1452      Name = "testAccAWSAutoScalingGroupConfig_ALB_TargetGroup"
  1453    }
  1454  }
  1455  `
  1456  
  1457  const testAccAWSAutoScalingGroupConfig_ALB_TargetGroup_post_duo = `
  1458  provider "aws" {
  1459    region = "us-west-2"
  1460  }
  1461  
  1462  resource "aws_vpc" "default" {
  1463    cidr_block = "10.0.0.0/16"
  1464  
  1465    tags {
  1466      Name = "testAccAWSAutoScalingGroupConfig_ALB_TargetGroup"
  1467    }
  1468  }
  1469  
  1470  resource "aws_alb_target_group" "test" {
  1471    name     = "tf-example-alb-tg"
  1472    port     = 80
  1473    protocol = "HTTP"
  1474    vpc_id   = "${aws_vpc.default.id}"
  1475  }
  1476  
  1477  resource "aws_alb_target_group" "test_more" {
  1478    name     = "tf-example-alb-tg-more"
  1479    port     = 80
  1480    protocol = "HTTP"
  1481    vpc_id   = "${aws_vpc.default.id}"
  1482  }
  1483  
  1484  resource "aws_subnet" "main" {
  1485    vpc_id            = "${aws_vpc.default.id}"
  1486    cidr_block        = "10.0.1.0/24"
  1487    availability_zone = "us-west-2a"
  1488  
  1489    tags {
  1490      Name = "testAccAWSAutoScalingGroupConfig_ALB_TargetGroup"
  1491    }
  1492  }
  1493  
  1494  resource "aws_subnet" "alt" {
  1495    vpc_id            = "${aws_vpc.default.id}"
  1496    cidr_block        = "10.0.2.0/24"
  1497    availability_zone = "us-west-2b"
  1498  
  1499    tags {
  1500      Name = "testAccAWSAutoScalingGroupConfig_ALB_TargetGroup"
  1501    }
  1502  }
  1503  
  1504  resource "aws_launch_configuration" "foobar" {
  1505    # Golang-base from cts-hashi aws account, shared with tf testing account
  1506    image_id          = "ami-1817d178"
  1507    instance_type     = "t2.micro"
  1508    enable_monitoring = false
  1509  }
  1510  
  1511  resource "aws_autoscaling_group" "bar" {
  1512    vpc_zone_identifier = [
  1513      "${aws_subnet.main.id}",
  1514      "${aws_subnet.alt.id}",
  1515    ]
  1516  
  1517  	target_group_arns = [
  1518  		"${aws_alb_target_group.test.arn}",
  1519  		"${aws_alb_target_group.test_more.arn}",
  1520  	]
  1521  
  1522    max_size                  = 2
  1523    min_size                  = 0
  1524    health_check_grace_period = 300
  1525    health_check_type         = "ELB"
  1526    desired_capacity          = 0
  1527    force_delete              = true
  1528    termination_policies      = ["OldestInstance"]
  1529    launch_configuration      = "${aws_launch_configuration.foobar.name}"
  1530  
  1531  }
  1532  
  1533  resource "aws_security_group" "tf_test_self" {
  1534    name        = "tf_test_alb_asg"
  1535    description = "tf_test_alb_asg"
  1536    vpc_id      = "${aws_vpc.default.id}"
  1537  
  1538    ingress {
  1539      from_port   = 80
  1540      to_port     = 80
  1541      protocol    = "tcp"
  1542      cidr_blocks = ["0.0.0.0/0"]
  1543    }
  1544  
  1545    tags {
  1546      Name = "testAccAWSAutoScalingGroupConfig_ALB_TargetGroup"
  1547    }
  1548  }
  1549  `
  1550  
  1551  func testAccAWSAutoScalingGroupWithHookConfig(name string) string {
  1552  	return fmt.Sprintf(`
  1553  resource "aws_launch_configuration" "foobar" {
  1554    image_id = "ami-21f78e11"
  1555    instance_type = "t1.micro"
  1556  }
  1557  
  1558  resource "aws_autoscaling_group" "bar" {
  1559    availability_zones = ["us-west-2a"]
  1560    name = "%s"
  1561    max_size = 5
  1562    min_size = 2
  1563    health_check_type = "ELB"
  1564    desired_capacity = 4
  1565    force_delete = true
  1566    termination_policies = ["OldestInstance","ClosestToNextInstanceHour"]
  1567  
  1568    launch_configuration = "${aws_launch_configuration.foobar.name}"
  1569  
  1570    initial_lifecycle_hook {
  1571      name = "launching"
  1572      default_result = "CONTINUE"
  1573      heartbeat_timeout = 30  # minimum value
  1574      lifecycle_transition = "autoscaling:EC2_INSTANCE_LAUNCHING"
  1575    }
  1576  }
  1577  `, name)
  1578  }
  1579  
  1580  func testAccAWSAutoScalingGroupConfig_ALB_TargetGroup_ELBCapacity(rInt int) string {
  1581  	return fmt.Sprintf(`
  1582  provider "aws" {
  1583    region = "us-west-2"
  1584  }
  1585  
  1586  resource "aws_vpc" "default" {
  1587    cidr_block           = "10.0.0.0/16"
  1588    enable_dns_hostnames = "true"
  1589    enable_dns_support   = "true"
  1590  
  1591    tags {
  1592      Name = "testAccAWSAutoScalingGroupConfig_ALB_TargetGroup_ELBCapacity"
  1593    }
  1594  }
  1595  
  1596  resource "aws_alb" "test_lb" {
  1597    subnets = ["${aws_subnet.main.id}", "${aws_subnet.alt.id}"]
  1598  
  1599    tags {
  1600      Name = "testAccAWSAutoScalingGroupConfig_ALB_TargetGroup_ELBCapacity"
  1601    }
  1602  }
  1603  
  1604  resource "aws_alb_listener" "test_listener" {
  1605    load_balancer_arn = "${aws_alb.test_lb.arn}"
  1606    port              = "80"
  1607  
  1608    default_action {
  1609      target_group_arn = "${aws_alb_target_group.test.arn}"
  1610      type             = "forward"
  1611    }
  1612  }
  1613  
  1614  resource "aws_alb_target_group" "test" {
  1615    name     = "tf-alb-test-%d"
  1616    port     = 80
  1617    protocol = "HTTP"
  1618    vpc_id   = "${aws_vpc.default.id}"
  1619  
  1620    health_check {
  1621      path              = "/"
  1622      healthy_threshold = "2"
  1623      timeout           = "2"
  1624      interval          = "5"
  1625    }
  1626  
  1627    tags {
  1628      Name = "testAccAWSAutoScalingGroupConfig_ALB_TargetGroup_ELBCapacity"
  1629    }
  1630  }
  1631  
  1632  resource "aws_subnet" "main" {
  1633    vpc_id            = "${aws_vpc.default.id}"
  1634    cidr_block        = "10.0.1.0/24"
  1635    availability_zone = "us-west-2a"
  1636  
  1637    tags {
  1638      Name = "testAccAWSAutoScalingGroupConfig_ALB_TargetGroup_ELBCapacity"
  1639    }
  1640  }
  1641  
  1642  resource "aws_subnet" "alt" {
  1643    vpc_id            = "${aws_vpc.default.id}"
  1644    cidr_block        = "10.0.2.0/24"
  1645    availability_zone = "us-west-2b"
  1646  
  1647    tags {
  1648      Name = "testAccAWSAutoScalingGroupConfig_ALB_TargetGroup_ELBCapacity"
  1649    }
  1650  }
  1651  
  1652  resource "aws_internet_gateway" "internet_gateway" {
  1653    vpc_id = "${aws_vpc.default.id}"
  1654  }
  1655  
  1656  resource "aws_route_table" "route_table" {
  1657    vpc_id = "${aws_vpc.default.id}"
  1658  }
  1659  
  1660  resource "aws_route_table_association" "route_table_association_main" {
  1661    subnet_id      = "${aws_subnet.main.id}"
  1662    route_table_id = "${aws_route_table.route_table.id}"
  1663  }
  1664  
  1665  resource "aws_route_table_association" "route_table_association_alt" {
  1666    subnet_id      = "${aws_subnet.alt.id}"
  1667    route_table_id = "${aws_route_table.route_table.id}"
  1668  }
  1669  
  1670  resource "aws_route" "public_default_route" {
  1671    route_table_id         = "${aws_route_table.route_table.id}"
  1672    destination_cidr_block = "0.0.0.0/0"
  1673    gateway_id             = "${aws_internet_gateway.internet_gateway.id}"
  1674  }
  1675  
  1676  data "aws_ami" "test_ami" {
  1677    most_recent = true
  1678  
  1679    filter {
  1680      name   = "owner-alias"
  1681      values = ["amazon"]
  1682    }
  1683  
  1684    filter {
  1685      name   = "name"
  1686      values = ["amzn-ami-hvm-*-x86_64-gp2"]
  1687    }
  1688  }
  1689  
  1690  resource "aws_launch_configuration" "foobar" {
  1691    image_id                    = "${data.aws_ami.test_ami.id}"
  1692    instance_type               = "t2.micro"
  1693    associate_public_ip_address = "true"
  1694  
  1695    user_data = <<EOS
  1696  #!/bin/bash
  1697  yum -y install httpd
  1698  echo "hello world" > /var/www/html/index.html
  1699  chkconfig httpd on
  1700  service httpd start
  1701  EOS
  1702  }
  1703  
  1704  resource "aws_autoscaling_group" "bar" {
  1705    vpc_zone_identifier = [
  1706      "${aws_subnet.main.id}",
  1707      "${aws_subnet.alt.id}",
  1708    ]
  1709  
  1710    target_group_arns = ["${aws_alb_target_group.test.arn}"]
  1711  
  1712    max_size                  = 2
  1713    min_size                  = 2
  1714    health_check_grace_period = 300
  1715    health_check_type         = "ELB"
  1716    desired_capacity          = 2
  1717    wait_for_elb_capacity     = 2
  1718    force_delete              = true
  1719    termination_policies      = ["OldestInstance"]
  1720    launch_configuration      = "${aws_launch_configuration.foobar.name}"
  1721  }`, rInt)
  1722  }
  1723  
  1724  func testAccAWSAutoScalingGroupConfigWithSuspendedProcesses(name string) string {
  1725  	return fmt.Sprintf(`
  1726  resource "aws_launch_configuration" "foobar" {
  1727    image_id = "ami-21f78e11"
  1728    instance_type = "t1.micro"
  1729  }
  1730  
  1731  resource "aws_placement_group" "test" {
  1732    name = "asg_pg_%s"
  1733    strategy = "cluster"
  1734  }
  1735  
  1736  resource "aws_autoscaling_group" "bar" {
  1737    availability_zones = ["us-west-2a"]
  1738    name = "%s"
  1739    max_size = 5
  1740    min_size = 2
  1741    health_check_type = "ELB"
  1742    desired_capacity = 4
  1743    force_delete = true
  1744    termination_policies = ["OldestInstance","ClosestToNextInstanceHour"]
  1745  
  1746    launch_configuration = "${aws_launch_configuration.foobar.name}"
  1747  
  1748    suspended_processes = ["AlarmNotification","ScheduledActions"]
  1749  
  1750    tag {
  1751      key = "Foo"
  1752      value = "foo-bar"
  1753      propagate_at_launch = true
  1754    }
  1755  }
  1756  `, name, name)
  1757  }
  1758  
  1759  func testAccAWSAutoScalingGroupConfigWithSuspendedProcessesUpdated(name string) string {
  1760  	return fmt.Sprintf(`
  1761  resource "aws_launch_configuration" "foobar" {
  1762    image_id = "ami-21f78e11"
  1763    instance_type = "t1.micro"
  1764  }
  1765  
  1766  resource "aws_placement_group" "test" {
  1767    name = "asg_pg_%s"
  1768    strategy = "cluster"
  1769  }
  1770  
  1771  resource "aws_autoscaling_group" "bar" {
  1772    availability_zones = ["us-west-2a"]
  1773    name = "%s"
  1774    max_size = 5
  1775    min_size = 2
  1776    health_check_type = "ELB"
  1777    desired_capacity = 4
  1778    force_delete = true
  1779    termination_policies = ["OldestInstance","ClosestToNextInstanceHour"]
  1780  
  1781    launch_configuration = "${aws_launch_configuration.foobar.name}"
  1782  
  1783    suspended_processes = ["AZRebalance","ScheduledActions"]
  1784  
  1785    tag {
  1786      key = "Foo"
  1787      value = "foo-bar"
  1788      propagate_at_launch = true
  1789    }
  1790  }
  1791  `, name, name)
  1792  }