github.com/peterbale/terraform@v0.9.0-beta2.0.20170315142748-5723acd55547/builtin/providers/aws/resource_aws_autoscaling_group_test.go (about)

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