github.com/jsoriano/terraform@v0.6.7-0.20151026070445-8b70867fdd95/builtin/providers/aws/resource_aws_autoscaling_group_test.go (about)

     1  package aws
     2  
     3  import (
     4  	"fmt"
     5  	"reflect"
     6  	"strings"
     7  	"testing"
     8  
     9  	"github.com/aws/aws-sdk-go/aws"
    10  	"github.com/aws/aws-sdk-go/aws/awserr"
    11  	"github.com/aws/aws-sdk-go/service/autoscaling"
    12  	"github.com/hashicorp/terraform/helper/resource"
    13  	"github.com/hashicorp/terraform/terraform"
    14  )
    15  
    16  func TestAccAWSAutoScalingGroup_basic(t *testing.T) {
    17  	var group autoscaling.Group
    18  	var lc autoscaling.LaunchConfiguration
    19  
    20  	resource.Test(t, resource.TestCase{
    21  		PreCheck:     func() { testAccPreCheck(t) },
    22  		Providers:    testAccProviders,
    23  		CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
    24  		Steps: []resource.TestStep{
    25  			resource.TestStep{
    26  				Config: testAccAWSAutoScalingGroupConfig,
    27  				Check: resource.ComposeTestCheckFunc(
    28  					testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
    29  					testAccCheckAWSAutoScalingGroupHealthyCapacity(&group, 2),
    30  					testAccCheckAWSAutoScalingGroupAttributes(&group),
    31  					resource.TestCheckResourceAttr(
    32  						"aws_autoscaling_group.bar", "availability_zones.2487133097", "us-west-2a"),
    33  					resource.TestCheckResourceAttr(
    34  						"aws_autoscaling_group.bar", "name", "foobar3-terraform-test"),
    35  					resource.TestCheckResourceAttr(
    36  						"aws_autoscaling_group.bar", "max_size", "5"),
    37  					resource.TestCheckResourceAttr(
    38  						"aws_autoscaling_group.bar", "min_size", "2"),
    39  					resource.TestCheckResourceAttr(
    40  						"aws_autoscaling_group.bar", "health_check_grace_period", "300"),
    41  					resource.TestCheckResourceAttr(
    42  						"aws_autoscaling_group.bar", "health_check_type", "ELB"),
    43  					resource.TestCheckResourceAttr(
    44  						"aws_autoscaling_group.bar", "desired_capacity", "4"),
    45  					resource.TestCheckResourceAttr(
    46  						"aws_autoscaling_group.bar", "force_delete", "true"),
    47  					resource.TestCheckResourceAttr(
    48  						"aws_autoscaling_group.bar", "termination_policies.912102603", "OldestInstance"),
    49  				),
    50  			},
    51  
    52  			resource.TestStep{
    53  				Config: testAccAWSAutoScalingGroupConfigUpdate,
    54  				Check: resource.ComposeTestCheckFunc(
    55  					testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
    56  					testAccCheckAWSLaunchConfigurationExists("aws_launch_configuration.new", &lc),
    57  					resource.TestCheckResourceAttr(
    58  						"aws_autoscaling_group.bar", "desired_capacity", "5"),
    59  					testLaunchConfigurationName("aws_autoscaling_group.bar", &lc),
    60  					testAccCheckAutoscalingTags(&group.Tags, "Bar", map[string]interface{}{
    61  						"value":               "bar-foo",
    62  						"propagate_at_launch": true,
    63  					}),
    64  				),
    65  			},
    66  		},
    67  	})
    68  }
    69  
    70  func TestAccAWSAutoScalingGroup_tags(t *testing.T) {
    71  	var group autoscaling.Group
    72  
    73  	resource.Test(t, resource.TestCase{
    74  		PreCheck:     func() { testAccPreCheck(t) },
    75  		Providers:    testAccProviders,
    76  		CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
    77  		Steps: []resource.TestStep{
    78  			resource.TestStep{
    79  				Config: testAccAWSAutoScalingGroupConfig,
    80  				Check: resource.ComposeTestCheckFunc(
    81  					testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
    82  					testAccCheckAutoscalingTags(&group.Tags, "Foo", map[string]interface{}{
    83  						"value":               "foo-bar",
    84  						"propagate_at_launch": true,
    85  					}),
    86  				),
    87  			},
    88  
    89  			resource.TestStep{
    90  				Config: testAccAWSAutoScalingGroupConfigUpdate,
    91  				Check: resource.ComposeTestCheckFunc(
    92  					testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
    93  					testAccCheckAutoscalingTagNotExists(&group.Tags, "Foo"),
    94  					testAccCheckAutoscalingTags(&group.Tags, "Bar", map[string]interface{}{
    95  						"value":               "bar-foo",
    96  						"propagate_at_launch": true,
    97  					}),
    98  				),
    99  			},
   100  		},
   101  	})
   102  }
   103  
   104  func TestAccAWSAutoScalingGroup_VpcUpdates(t *testing.T) {
   105  	var group autoscaling.Group
   106  
   107  	resource.Test(t, resource.TestCase{
   108  		PreCheck:     func() { testAccPreCheck(t) },
   109  		Providers:    testAccProviders,
   110  		CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
   111  		Steps: []resource.TestStep{
   112  			resource.TestStep{
   113  				Config: testAccAWSAutoScalingGroupConfigWithAZ,
   114  				Check: resource.ComposeTestCheckFunc(
   115  					testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
   116  				),
   117  			},
   118  
   119  			resource.TestStep{
   120  				Config: testAccAWSAutoScalingGroupConfigWithVPCIdent,
   121  				Check: resource.ComposeTestCheckFunc(
   122  					testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
   123  					testAccCheckAWSAutoScalingGroupAttributesVPCZoneIdentifer(&group),
   124  				),
   125  			},
   126  		},
   127  	})
   128  }
   129  
   130  func TestAccAWSAutoScalingGroup_WithLoadBalancer(t *testing.T) {
   131  	var group autoscaling.Group
   132  
   133  	resource.Test(t, resource.TestCase{
   134  		PreCheck:     func() { testAccPreCheck(t) },
   135  		Providers:    testAccProviders,
   136  		CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
   137  		Steps: []resource.TestStep{
   138  			resource.TestStep{
   139  				Config: testAccAWSAutoScalingGroupConfigWithLoadBalancer,
   140  				Check: resource.ComposeTestCheckFunc(
   141  					testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group),
   142  					testAccCheckAWSAutoScalingGroupAttributesLoadBalancer(&group),
   143  				),
   144  			},
   145  		},
   146  	})
   147  }
   148  
   149  func testAccCheckAWSAutoScalingGroupDestroy(s *terraform.State) error {
   150  	conn := testAccProvider.Meta().(*AWSClient).autoscalingconn
   151  
   152  	for _, rs := range s.RootModule().Resources {
   153  		if rs.Type != "aws_autoscaling_group" {
   154  			continue
   155  		}
   156  
   157  		// Try to find the Group
   158  		describeGroups, err := conn.DescribeAutoScalingGroups(
   159  			&autoscaling.DescribeAutoScalingGroupsInput{
   160  				AutoScalingGroupNames: []*string{aws.String(rs.Primary.ID)},
   161  			})
   162  
   163  		if err == nil {
   164  			if len(describeGroups.AutoScalingGroups) != 0 &&
   165  				*describeGroups.AutoScalingGroups[0].AutoScalingGroupName == rs.Primary.ID {
   166  				return fmt.Errorf("AutoScaling Group still exists")
   167  			}
   168  		}
   169  
   170  		// Verify the error
   171  		ec2err, ok := err.(awserr.Error)
   172  		if !ok {
   173  			return err
   174  		}
   175  		if ec2err.Code() != "InvalidGroup.NotFound" {
   176  			return err
   177  		}
   178  	}
   179  
   180  	return nil
   181  }
   182  
   183  func testAccCheckAWSAutoScalingGroupAttributes(group *autoscaling.Group) resource.TestCheckFunc {
   184  	return func(s *terraform.State) error {
   185  		if *group.AvailabilityZones[0] != "us-west-2a" {
   186  			return fmt.Errorf("Bad availability_zones: %#v", group.AvailabilityZones[0])
   187  		}
   188  
   189  		if *group.AutoScalingGroupName != "foobar3-terraform-test" {
   190  			return fmt.Errorf("Bad name: %s", *group.AutoScalingGroupName)
   191  		}
   192  
   193  		if *group.MaxSize != 5 {
   194  			return fmt.Errorf("Bad max_size: %d", *group.MaxSize)
   195  		}
   196  
   197  		if *group.MinSize != 2 {
   198  			return fmt.Errorf("Bad max_size: %d", *group.MinSize)
   199  		}
   200  
   201  		if *group.HealthCheckType != "ELB" {
   202  			return fmt.Errorf("Bad health_check_type,\nexpected: %s\ngot: %s", "ELB", *group.HealthCheckType)
   203  		}
   204  
   205  		if *group.HealthCheckGracePeriod != 300 {
   206  			return fmt.Errorf("Bad health_check_grace_period: %d", *group.HealthCheckGracePeriod)
   207  		}
   208  
   209  		if *group.DesiredCapacity != 4 {
   210  			return fmt.Errorf("Bad desired_capacity: %d", *group.DesiredCapacity)
   211  		}
   212  
   213  		if *group.LaunchConfigurationName == "" {
   214  			return fmt.Errorf("Bad launch configuration name: %s", *group.LaunchConfigurationName)
   215  		}
   216  
   217  		t := &autoscaling.TagDescription{
   218  			Key:               aws.String("Foo"),
   219  			Value:             aws.String("foo-bar"),
   220  			PropagateAtLaunch: aws.Bool(true),
   221  			ResourceType:      aws.String("auto-scaling-group"),
   222  			ResourceId:        group.AutoScalingGroupName,
   223  		}
   224  
   225  		if !reflect.DeepEqual(group.Tags[0], t) {
   226  			return fmt.Errorf(
   227  				"Got:\n\n%#v\n\nExpected:\n\n%#v\n",
   228  				group.Tags[0],
   229  				t)
   230  		}
   231  
   232  		return nil
   233  	}
   234  }
   235  
   236  func testAccCheckAWSAutoScalingGroupAttributesLoadBalancer(group *autoscaling.Group) resource.TestCheckFunc {
   237  	return func(s *terraform.State) error {
   238  		if *group.LoadBalancerNames[0] != "foobar-terraform-test" {
   239  			return fmt.Errorf("Bad load_balancers: %#v", group.LoadBalancerNames[0])
   240  		}
   241  
   242  		return nil
   243  	}
   244  }
   245  
   246  func testAccCheckAWSAutoScalingGroupExists(n string, group *autoscaling.Group) resource.TestCheckFunc {
   247  	return func(s *terraform.State) error {
   248  		rs, ok := s.RootModule().Resources[n]
   249  		if !ok {
   250  			return fmt.Errorf("Not found: %s", n)
   251  		}
   252  
   253  		if rs.Primary.ID == "" {
   254  			return fmt.Errorf("No AutoScaling Group ID is set")
   255  		}
   256  
   257  		conn := testAccProvider.Meta().(*AWSClient).autoscalingconn
   258  
   259  		describeGroups, err := conn.DescribeAutoScalingGroups(
   260  			&autoscaling.DescribeAutoScalingGroupsInput{
   261  				AutoScalingGroupNames: []*string{aws.String(rs.Primary.ID)},
   262  			})
   263  
   264  		if err != nil {
   265  			return err
   266  		}
   267  
   268  		if len(describeGroups.AutoScalingGroups) != 1 ||
   269  			*describeGroups.AutoScalingGroups[0].AutoScalingGroupName != rs.Primary.ID {
   270  			return fmt.Errorf("AutoScaling Group not found")
   271  		}
   272  
   273  		*group = *describeGroups.AutoScalingGroups[0]
   274  
   275  		return nil
   276  	}
   277  }
   278  
   279  func testLaunchConfigurationName(n string, lc *autoscaling.LaunchConfiguration) resource.TestCheckFunc {
   280  	return func(s *terraform.State) error {
   281  		rs, ok := s.RootModule().Resources[n]
   282  		if !ok {
   283  			return fmt.Errorf("Not found: %s", n)
   284  		}
   285  
   286  		if *lc.LaunchConfigurationName != rs.Primary.Attributes["launch_configuration"] {
   287  			return fmt.Errorf("Launch configuration names do not match")
   288  		}
   289  
   290  		return nil
   291  	}
   292  }
   293  
   294  func testAccCheckAWSAutoScalingGroupHealthyCapacity(
   295  	g *autoscaling.Group, exp int) resource.TestCheckFunc {
   296  	return func(s *terraform.State) error {
   297  		healthy := 0
   298  		for _, i := range g.Instances {
   299  			if i.HealthStatus == nil {
   300  				continue
   301  			}
   302  			if strings.EqualFold(*i.HealthStatus, "Healthy") {
   303  				healthy++
   304  			}
   305  		}
   306  		if healthy < exp {
   307  			return fmt.Errorf("Expected at least %d healthy, got %d.", exp, healthy)
   308  		}
   309  		return nil
   310  	}
   311  }
   312  
   313  func testAccCheckAWSAutoScalingGroupAttributesVPCZoneIdentifer(group *autoscaling.Group) resource.TestCheckFunc {
   314  	return func(s *terraform.State) error {
   315  		// Grab Subnet Ids
   316  		var subnets []string
   317  		for _, rs := range s.RootModule().Resources {
   318  			if rs.Type != "aws_subnet" {
   319  				continue
   320  			}
   321  			subnets = append(subnets, rs.Primary.Attributes["id"])
   322  		}
   323  
   324  		if group.VPCZoneIdentifier == nil {
   325  			return fmt.Errorf("Bad VPC Zone Identifier\nexpected: %s\ngot nil", subnets)
   326  		}
   327  
   328  		zones := strings.Split(*group.VPCZoneIdentifier, ",")
   329  
   330  		remaining := len(zones)
   331  		for _, z := range zones {
   332  			for _, s := range subnets {
   333  				if z == s {
   334  					remaining--
   335  				}
   336  			}
   337  		}
   338  
   339  		if remaining != 0 {
   340  			return fmt.Errorf("Bad VPC Zone Identifier match\nexpected: %s\ngot:%s", zones, subnets)
   341  		}
   342  
   343  		return nil
   344  	}
   345  }
   346  
   347  const testAccAWSAutoScalingGroupConfig = `
   348  resource "aws_launch_configuration" "foobar" {
   349    image_id = "ami-21f78e11"
   350    instance_type = "t1.micro"
   351  }
   352  
   353  resource "aws_autoscaling_group" "bar" {
   354    availability_zones = ["us-west-2a"]
   355    name = "foobar3-terraform-test"
   356    max_size = 5
   357    min_size = 2
   358    health_check_grace_period = 300
   359    health_check_type = "ELB"
   360    desired_capacity = 4
   361    force_delete = true
   362    termination_policies = ["OldestInstance"]
   363  
   364    launch_configuration = "${aws_launch_configuration.foobar.name}"
   365  
   366    tag {
   367      key = "Foo"
   368      value = "foo-bar"
   369      propagate_at_launch = true
   370    }
   371  }
   372  `
   373  
   374  const testAccAWSAutoScalingGroupConfigUpdate = `
   375  resource "aws_launch_configuration" "foobar" {
   376    image_id = "ami-21f78e11"
   377    instance_type = "t1.micro"
   378  }
   379  
   380  resource "aws_launch_configuration" "new" {
   381    image_id = "ami-21f78e11"
   382    instance_type = "t1.micro"
   383  }
   384  
   385  resource "aws_autoscaling_group" "bar" {
   386    availability_zones = ["us-west-2a"]
   387    name = "foobar3-terraform-test"
   388    max_size = 5
   389    min_size = 2
   390    health_check_grace_period = 300
   391    health_check_type = "ELB"
   392    desired_capacity = 5
   393    force_delete = true
   394  
   395    launch_configuration = "${aws_launch_configuration.new.name}"
   396  
   397    tag {
   398      key = "Bar"
   399      value = "bar-foo"
   400      propagate_at_launch = true
   401    }
   402  }
   403  `
   404  
   405  const testAccAWSAutoScalingGroupConfigWithLoadBalancer = `
   406  resource "aws_vpc" "foo" {
   407    cidr_block = "10.1.0.0/16"
   408  	tags { Name = "tf-asg-test" }
   409  }
   410  
   411  resource "aws_internet_gateway" "gw" {
   412    vpc_id = "${aws_vpc.foo.id}"
   413  }
   414  
   415  resource "aws_subnet" "foo" {
   416  	cidr_block = "10.1.1.0/24"
   417  	vpc_id = "${aws_vpc.foo.id}"
   418  }
   419  
   420  resource "aws_security_group" "foo" {
   421    vpc_id="${aws_vpc.foo.id}"
   422  
   423    ingress {
   424      protocol = "-1"
   425      from_port = 0
   426      to_port = 0
   427      cidr_blocks = ["0.0.0.0/0"]
   428    }
   429  
   430    egress {
   431      protocol = "-1"
   432      from_port = 0
   433      to_port = 0
   434      cidr_blocks = ["0.0.0.0/0"]
   435    }
   436  }
   437  
   438  resource "aws_elb" "bar" {
   439    name = "foobar-terraform-test"
   440    subnets = ["${aws_subnet.foo.id}"]
   441  	security_groups = ["${aws_security_group.foo.id}"]
   442  
   443    listener {
   444      instance_port = 80
   445      instance_protocol = "http"
   446      lb_port = 80
   447      lb_protocol = "http"
   448    }
   449  
   450    health_check {
   451      healthy_threshold = 2
   452      unhealthy_threshold = 2
   453      target = "HTTP:80/"
   454      interval = 5
   455      timeout = 2
   456    }
   457  
   458  	depends_on = ["aws_internet_gateway.gw"]
   459  }
   460  
   461  resource "aws_launch_configuration" "foobar" {
   462    // need an AMI that listens on :80 at boot, this is:
   463    // bitnami-nginxstack-1.6.1-0-linux-ubuntu-14.04.1-x86_64-hvm-ebs-ami-99f5b1a9-3
   464    image_id = "ami-b5b3fc85"
   465    instance_type = "t2.micro"
   466  	security_groups = ["${aws_security_group.foo.id}"]
   467  }
   468  
   469  resource "aws_autoscaling_group" "bar" {
   470    availability_zones = ["${aws_subnet.foo.availability_zone}"]
   471  	vpc_zone_identifier = ["${aws_subnet.foo.id}"]
   472    name = "foobar3-terraform-test"
   473    max_size = 2
   474    min_size = 2
   475    health_check_grace_period = 300
   476    health_check_type = "ELB"
   477    min_elb_capacity = 2
   478    force_delete = true
   479  
   480    launch_configuration = "${aws_launch_configuration.foobar.name}"
   481    load_balancers = ["${aws_elb.bar.name}"]
   482  }
   483  `
   484  
   485  const testAccAWSAutoScalingGroupConfigWithAZ = `
   486  resource "aws_vpc" "default" {
   487    cidr_block = "10.0.0.0/16"
   488    tags {
   489       Name = "terraform-test"
   490    }
   491  }
   492  
   493  resource "aws_subnet" "main" {
   494    vpc_id = "${aws_vpc.default.id}"
   495    cidr_block = "10.0.1.0/24"
   496    availability_zone = "us-west-2a"
   497    tags {
   498       Name = "terraform-test"
   499    }
   500  }
   501  
   502  resource "aws_subnet" "alt" {
   503    vpc_id = "${aws_vpc.default.id}"
   504    cidr_block = "10.0.2.0/24"
   505    availability_zone = "us-west-2b"
   506    tags {
   507       Name = "asg-vpc-thing"
   508    }
   509  }
   510  
   511  resource "aws_launch_configuration" "foobar" {
   512    name = "vpc-asg-test"
   513    image_id = "ami-b5b3fc85"
   514    instance_type = "t2.micro"
   515  }
   516  
   517  resource "aws_autoscaling_group" "bar" {
   518    availability_zones = ["us-west-2a"]
   519    name = "vpc-asg-test"
   520    max_size = 2
   521    min_size = 1
   522    health_check_grace_period = 300
   523    health_check_type = "ELB"
   524    desired_capacity = 1
   525    force_delete = true
   526    termination_policies = ["OldestInstance"]
   527    launch_configuration = "${aws_launch_configuration.foobar.name}"
   528  }
   529  `
   530  
   531  const testAccAWSAutoScalingGroupConfigWithVPCIdent = `
   532  resource "aws_vpc" "default" {
   533    cidr_block = "10.0.0.0/16"
   534    tags {
   535       Name = "terraform-test"
   536    }
   537  }
   538  
   539  resource "aws_subnet" "main" {
   540    vpc_id = "${aws_vpc.default.id}"
   541    cidr_block = "10.0.1.0/24"
   542    availability_zone = "us-west-2a"
   543    tags {
   544       Name = "terraform-test"
   545    }
   546  }
   547  
   548  resource "aws_subnet" "alt" {
   549    vpc_id = "${aws_vpc.default.id}"
   550    cidr_block = "10.0.2.0/24"
   551    availability_zone = "us-west-2b"
   552    tags {
   553       Name = "asg-vpc-thing"
   554    }
   555  }
   556  
   557  resource "aws_launch_configuration" "foobar" {
   558    name = "vpc-asg-test"
   559    image_id = "ami-b5b3fc85"
   560    instance_type = "t2.micro"
   561  }
   562  
   563  resource "aws_autoscaling_group" "bar" {
   564    vpc_zone_identifier = [
   565      "${aws_subnet.main.id}",
   566      "${aws_subnet.alt.id}",
   567    ]
   568    name = "vpc-asg-test"
   569    max_size = 2
   570    min_size = 1
   571    health_check_grace_period = 300
   572    health_check_type = "ELB"
   573    desired_capacity = 1
   574    force_delete = true
   575    termination_policies = ["OldestInstance"]
   576    launch_configuration = "${aws_launch_configuration.foobar.name}"
   577  }
   578  `