github.com/tomaszheflik/terraform@v0.7.3-0.20160827060421-32f990b41594/builtin/providers/aws/resource_aws_autoscaling_group.go (about) 1 package aws 2 3 import ( 4 "fmt" 5 "log" 6 "strings" 7 "time" 8 9 "github.com/hashicorp/terraform/helper/resource" 10 "github.com/hashicorp/terraform/helper/schema" 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/elb" 16 ) 17 18 func resourceAwsAutoscalingGroup() *schema.Resource { 19 return &schema.Resource{ 20 Create: resourceAwsAutoscalingGroupCreate, 21 Read: resourceAwsAutoscalingGroupRead, 22 Update: resourceAwsAutoscalingGroupUpdate, 23 Delete: resourceAwsAutoscalingGroupDelete, 24 Importer: &schema.ResourceImporter{ 25 State: schema.ImportStatePassthrough, 26 }, 27 28 Schema: map[string]*schema.Schema{ 29 "name": &schema.Schema{ 30 Type: schema.TypeString, 31 Optional: true, 32 Computed: true, 33 ForceNew: true, 34 ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { 35 // https://github.com/boto/botocore/blob/9f322b1/botocore/data/autoscaling/2011-01-01/service-2.json#L1862-L1873 36 value := v.(string) 37 if len(value) > 255 { 38 errors = append(errors, fmt.Errorf( 39 "%q cannot be longer than 255 characters", k)) 40 } 41 return 42 }, 43 }, 44 45 "launch_configuration": &schema.Schema{ 46 Type: schema.TypeString, 47 Required: true, 48 }, 49 50 "desired_capacity": &schema.Schema{ 51 Type: schema.TypeInt, 52 Optional: true, 53 Computed: true, 54 }, 55 56 "min_elb_capacity": &schema.Schema{ 57 Type: schema.TypeInt, 58 Optional: true, 59 }, 60 61 "min_size": &schema.Schema{ 62 Type: schema.TypeInt, 63 Required: true, 64 }, 65 66 "max_size": &schema.Schema{ 67 Type: schema.TypeInt, 68 Required: true, 69 }, 70 71 "default_cooldown": &schema.Schema{ 72 Type: schema.TypeInt, 73 Optional: true, 74 Computed: true, 75 }, 76 77 "force_delete": &schema.Schema{ 78 Type: schema.TypeBool, 79 Optional: true, 80 Default: false, 81 }, 82 83 "health_check_grace_period": &schema.Schema{ 84 Type: schema.TypeInt, 85 Optional: true, 86 Default: 300, 87 }, 88 89 "health_check_type": &schema.Schema{ 90 Type: schema.TypeString, 91 Optional: true, 92 Computed: true, 93 }, 94 95 "availability_zones": &schema.Schema{ 96 Type: schema.TypeSet, 97 Optional: true, 98 Computed: true, 99 Elem: &schema.Schema{Type: schema.TypeString}, 100 Set: schema.HashString, 101 }, 102 103 "placement_group": &schema.Schema{ 104 Type: schema.TypeString, 105 Optional: true, 106 }, 107 108 "load_balancers": &schema.Schema{ 109 Type: schema.TypeSet, 110 Optional: true, 111 Elem: &schema.Schema{Type: schema.TypeString}, 112 Set: schema.HashString, 113 }, 114 115 "vpc_zone_identifier": &schema.Schema{ 116 Type: schema.TypeSet, 117 Optional: true, 118 Computed: true, 119 Elem: &schema.Schema{Type: schema.TypeString}, 120 Set: schema.HashString, 121 }, 122 123 "termination_policies": &schema.Schema{ 124 Type: schema.TypeList, 125 Optional: true, 126 Elem: &schema.Schema{Type: schema.TypeString}, 127 }, 128 129 "wait_for_capacity_timeout": &schema.Schema{ 130 Type: schema.TypeString, 131 Optional: true, 132 Default: "10m", 133 ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { 134 value := v.(string) 135 duration, err := time.ParseDuration(value) 136 if err != nil { 137 errors = append(errors, fmt.Errorf( 138 "%q cannot be parsed as a duration: %s", k, err)) 139 } 140 if duration < 0 { 141 errors = append(errors, fmt.Errorf( 142 "%q must be greater than zero", k)) 143 } 144 return 145 }, 146 }, 147 148 "wait_for_elb_capacity": &schema.Schema{ 149 Type: schema.TypeInt, 150 Optional: true, 151 }, 152 153 "enabled_metrics": &schema.Schema{ 154 Type: schema.TypeSet, 155 Optional: true, 156 Elem: &schema.Schema{Type: schema.TypeString}, 157 Set: schema.HashString, 158 }, 159 160 "metrics_granularity": &schema.Schema{ 161 Type: schema.TypeString, 162 Optional: true, 163 Default: "1Minute", 164 }, 165 166 "protect_from_scale_in": &schema.Schema{ 167 Type: schema.TypeBool, 168 Optional: true, 169 Default: false, 170 }, 171 172 "target_group_arns": &schema.Schema{ 173 Type: schema.TypeSet, 174 Optional: true, 175 Elem: &schema.Schema{Type: schema.TypeString}, 176 Set: schema.HashString, 177 }, 178 179 "tag": autoscalingTagsSchema(), 180 }, 181 } 182 } 183 184 func resourceAwsAutoscalingGroupCreate(d *schema.ResourceData, meta interface{}) error { 185 conn := meta.(*AWSClient).autoscalingconn 186 187 var autoScalingGroupOpts autoscaling.CreateAutoScalingGroupInput 188 189 var asgName string 190 if v, ok := d.GetOk("name"); ok { 191 asgName = v.(string) 192 } else { 193 asgName = resource.PrefixedUniqueId("tf-asg-") 194 d.Set("name", asgName) 195 } 196 197 autoScalingGroupOpts.AutoScalingGroupName = aws.String(asgName) 198 autoScalingGroupOpts.LaunchConfigurationName = aws.String(d.Get("launch_configuration").(string)) 199 autoScalingGroupOpts.MinSize = aws.Int64(int64(d.Get("min_size").(int))) 200 autoScalingGroupOpts.MaxSize = aws.Int64(int64(d.Get("max_size").(int))) 201 autoScalingGroupOpts.NewInstancesProtectedFromScaleIn = aws.Bool(d.Get("protect_from_scale_in").(bool)) 202 203 // Availability Zones are optional if VPC Zone Identifer(s) are specified 204 if v, ok := d.GetOk("availability_zones"); ok && v.(*schema.Set).Len() > 0 { 205 autoScalingGroupOpts.AvailabilityZones = expandStringList(v.(*schema.Set).List()) 206 } 207 208 if v, ok := d.GetOk("tag"); ok { 209 autoScalingGroupOpts.Tags = autoscalingTagsFromMap( 210 setToMapByKey(v.(*schema.Set), "key"), d.Get("name").(string)) 211 } 212 213 if v, ok := d.GetOk("default_cooldown"); ok { 214 autoScalingGroupOpts.DefaultCooldown = aws.Int64(int64(v.(int))) 215 } 216 217 if v, ok := d.GetOk("health_check_type"); ok && v.(string) != "" { 218 autoScalingGroupOpts.HealthCheckType = aws.String(v.(string)) 219 } 220 221 if v, ok := d.GetOk("desired_capacity"); ok { 222 autoScalingGroupOpts.DesiredCapacity = aws.Int64(int64(v.(int))) 223 } 224 225 if v, ok := d.GetOk("health_check_grace_period"); ok { 226 autoScalingGroupOpts.HealthCheckGracePeriod = aws.Int64(int64(v.(int))) 227 } 228 229 if v, ok := d.GetOk("placement_group"); ok { 230 autoScalingGroupOpts.PlacementGroup = aws.String(v.(string)) 231 } 232 233 if v, ok := d.GetOk("load_balancers"); ok && v.(*schema.Set).Len() > 0 { 234 autoScalingGroupOpts.LoadBalancerNames = expandStringList( 235 v.(*schema.Set).List()) 236 } 237 238 if v, ok := d.GetOk("vpc_zone_identifier"); ok && v.(*schema.Set).Len() > 0 { 239 autoScalingGroupOpts.VPCZoneIdentifier = expandVpcZoneIdentifiers(v.(*schema.Set).List()) 240 } 241 242 if v, ok := d.GetOk("termination_policies"); ok && len(v.([]interface{})) > 0 { 243 autoScalingGroupOpts.TerminationPolicies = expandStringList(v.([]interface{})) 244 } 245 246 if v, ok := d.GetOk("target_group_arns"); ok && len(v.(*schema.Set).List()) > 0 { 247 autoScalingGroupOpts.TargetGroupARNs = expandStringList(v.(*schema.Set).List()) 248 } 249 250 log.Printf("[DEBUG] AutoScaling Group create configuration: %#v", autoScalingGroupOpts) 251 _, err := conn.CreateAutoScalingGroup(&autoScalingGroupOpts) 252 if err != nil { 253 return fmt.Errorf("Error creating Autoscaling Group: %s", err) 254 } 255 256 d.SetId(d.Get("name").(string)) 257 log.Printf("[INFO] AutoScaling Group ID: %s", d.Id()) 258 259 if err := waitForASGCapacity(d, meta, capacitySatifiedCreate); err != nil { 260 return err 261 } 262 263 if _, ok := d.GetOk("enabled_metrics"); ok { 264 metricsErr := enableASGMetricsCollection(d, conn) 265 if metricsErr != nil { 266 return metricsErr 267 } 268 } 269 270 return resourceAwsAutoscalingGroupRead(d, meta) 271 } 272 273 func resourceAwsAutoscalingGroupRead(d *schema.ResourceData, meta interface{}) error { 274 conn := meta.(*AWSClient).autoscalingconn 275 276 g, err := getAwsAutoscalingGroup(d.Id(), conn) 277 if err != nil { 278 return err 279 } 280 if g == nil { 281 log.Printf("[INFO] Autoscaling Group %q not found", d.Id()) 282 d.SetId("") 283 return nil 284 } 285 286 d.Set("availability_zones", flattenStringList(g.AvailabilityZones)) 287 d.Set("default_cooldown", g.DefaultCooldown) 288 d.Set("desired_capacity", g.DesiredCapacity) 289 d.Set("health_check_grace_period", g.HealthCheckGracePeriod) 290 d.Set("health_check_type", g.HealthCheckType) 291 d.Set("launch_configuration", g.LaunchConfigurationName) 292 d.Set("load_balancers", flattenStringList(g.LoadBalancerNames)) 293 if err := d.Set("target_group_arns", flattenStringList(g.TargetGroupARNs)); err != nil { 294 log.Printf("[ERR] Error setting target groups: %s", err) 295 } 296 d.Set("min_size", g.MinSize) 297 d.Set("max_size", g.MaxSize) 298 d.Set("placement_group", g.PlacementGroup) 299 d.Set("name", g.AutoScalingGroupName) 300 d.Set("tag", autoscalingTagDescriptionsToSlice(g.Tags)) 301 d.Set("vpc_zone_identifier", strings.Split(*g.VPCZoneIdentifier, ",")) 302 d.Set("protect_from_scale_in", g.NewInstancesProtectedFromScaleIn) 303 304 // If no termination polices are explicitly configured and the upstream state 305 // is only using the "Default" policy, clear the state to make it consistent 306 // with the default AWS create API behavior. 307 _, ok := d.GetOk("termination_policies") 308 if !ok && len(g.TerminationPolicies) == 1 && *g.TerminationPolicies[0] == "Default" { 309 d.Set("termination_policies", []interface{}{}) 310 } else { 311 d.Set("termination_policies", flattenStringList(g.TerminationPolicies)) 312 } 313 314 if g.EnabledMetrics != nil { 315 if err := d.Set("enabled_metrics", flattenAsgEnabledMetrics(g.EnabledMetrics)); err != nil { 316 log.Printf("[WARN] Error setting metrics for (%s): %s", d.Id(), err) 317 } 318 d.Set("metrics_granularity", g.EnabledMetrics[0].Granularity) 319 } 320 321 return nil 322 } 323 324 func resourceAwsAutoscalingGroupUpdate(d *schema.ResourceData, meta interface{}) error { 325 conn := meta.(*AWSClient).autoscalingconn 326 shouldWaitForCapacity := false 327 328 opts := autoscaling.UpdateAutoScalingGroupInput{ 329 AutoScalingGroupName: aws.String(d.Id()), 330 } 331 332 opts.NewInstancesProtectedFromScaleIn = aws.Bool(d.Get("protect_from_scale_in").(bool)) 333 334 if d.HasChange("default_cooldown") { 335 opts.DefaultCooldown = aws.Int64(int64(d.Get("default_cooldown").(int))) 336 } 337 338 if d.HasChange("desired_capacity") { 339 opts.DesiredCapacity = aws.Int64(int64(d.Get("desired_capacity").(int))) 340 shouldWaitForCapacity = true 341 } 342 343 if d.HasChange("launch_configuration") { 344 opts.LaunchConfigurationName = aws.String(d.Get("launch_configuration").(string)) 345 } 346 347 if d.HasChange("min_size") { 348 opts.MinSize = aws.Int64(int64(d.Get("min_size").(int))) 349 shouldWaitForCapacity = true 350 } 351 352 if d.HasChange("max_size") { 353 opts.MaxSize = aws.Int64(int64(d.Get("max_size").(int))) 354 } 355 356 if d.HasChange("health_check_grace_period") { 357 opts.HealthCheckGracePeriod = aws.Int64(int64(d.Get("health_check_grace_period").(int))) 358 } 359 360 if d.HasChange("health_check_type") { 361 opts.HealthCheckGracePeriod = aws.Int64(int64(d.Get("health_check_grace_period").(int))) 362 opts.HealthCheckType = aws.String(d.Get("health_check_type").(string)) 363 } 364 365 if d.HasChange("vpc_zone_identifier") { 366 opts.VPCZoneIdentifier = expandVpcZoneIdentifiers(d.Get("vpc_zone_identifier").(*schema.Set).List()) 367 } 368 369 if d.HasChange("availability_zones") { 370 if v, ok := d.GetOk("availability_zones"); ok && v.(*schema.Set).Len() > 0 { 371 opts.AvailabilityZones = expandStringList(v.(*schema.Set).List()) 372 } 373 } 374 375 if d.HasChange("placement_group") { 376 opts.PlacementGroup = aws.String(d.Get("placement_group").(string)) 377 } 378 379 if d.HasChange("termination_policies") { 380 // If the termination policy is set to null, we need to explicitly set 381 // it back to "Default", or the API won't reset it for us. 382 if v, ok := d.GetOk("termination_policies"); ok && len(v.([]interface{})) > 0 { 383 opts.TerminationPolicies = expandStringList(v.([]interface{})) 384 } else { 385 log.Printf("[DEBUG] Explictly setting null termination policy to 'Default'") 386 opts.TerminationPolicies = aws.StringSlice([]string{"Default"}) 387 } 388 } 389 390 if err := setAutoscalingTags(conn, d); err != nil { 391 return err 392 } else { 393 d.SetPartial("tag") 394 } 395 396 log.Printf("[DEBUG] AutoScaling Group update configuration: %#v", opts) 397 _, err := conn.UpdateAutoScalingGroup(&opts) 398 if err != nil { 399 d.Partial(true) 400 return fmt.Errorf("Error updating Autoscaling group: %s", err) 401 } 402 403 if d.HasChange("load_balancers") { 404 405 o, n := d.GetChange("load_balancers") 406 if o == nil { 407 o = new(schema.Set) 408 } 409 if n == nil { 410 n = new(schema.Set) 411 } 412 413 os := o.(*schema.Set) 414 ns := n.(*schema.Set) 415 remove := expandStringList(os.Difference(ns).List()) 416 add := expandStringList(ns.Difference(os).List()) 417 418 if len(remove) > 0 { 419 _, err := conn.DetachLoadBalancers(&autoscaling.DetachLoadBalancersInput{ 420 AutoScalingGroupName: aws.String(d.Id()), 421 LoadBalancerNames: remove, 422 }) 423 if err != nil { 424 return fmt.Errorf("[WARN] Error updating Load Balancers for AutoScaling Group (%s), error: %s", d.Id(), err) 425 } 426 } 427 428 if len(add) > 0 { 429 _, err := conn.AttachLoadBalancers(&autoscaling.AttachLoadBalancersInput{ 430 AutoScalingGroupName: aws.String(d.Id()), 431 LoadBalancerNames: add, 432 }) 433 if err != nil { 434 return fmt.Errorf("[WARN] Error updating Load Balancers for AutoScaling Group (%s), error: %s", d.Id(), err) 435 } 436 } 437 } 438 439 if d.HasChange("target_group_arns") { 440 441 o, n := d.GetChange("target_group_arns") 442 if o == nil { 443 o = new(schema.Set) 444 } 445 if n == nil { 446 n = new(schema.Set) 447 } 448 449 os := o.(*schema.Set) 450 ns := n.(*schema.Set) 451 remove := expandStringList(os.Difference(ns).List()) 452 add := expandStringList(ns.Difference(os).List()) 453 454 if len(remove) > 0 { 455 _, err := conn.DetachLoadBalancerTargetGroups(&autoscaling.DetachLoadBalancerTargetGroupsInput{ 456 AutoScalingGroupName: aws.String(d.Id()), 457 TargetGroupARNs: remove, 458 }) 459 if err != nil { 460 return fmt.Errorf("[WARN] Error updating Load Balancers Target Groups for AutoScaling Group (%s), error: %s", d.Id(), err) 461 } 462 } 463 464 if len(add) > 0 { 465 _, err := conn.AttachLoadBalancerTargetGroups(&autoscaling.AttachLoadBalancerTargetGroupsInput{ 466 AutoScalingGroupName: aws.String(d.Id()), 467 TargetGroupARNs: add, 468 }) 469 if err != nil { 470 return fmt.Errorf("[WARN] Error updating Load Balancers Target Groups for AutoScaling Group (%s), error: %s", d.Id(), err) 471 } 472 } 473 } 474 475 if shouldWaitForCapacity { 476 waitForASGCapacity(d, meta, capacitySatifiedUpdate) 477 } 478 479 if d.HasChange("enabled_metrics") { 480 updateASGMetricsCollection(d, conn) 481 } 482 483 return resourceAwsAutoscalingGroupRead(d, meta) 484 } 485 486 func resourceAwsAutoscalingGroupDelete(d *schema.ResourceData, meta interface{}) error { 487 conn := meta.(*AWSClient).autoscalingconn 488 489 // Read the autoscaling group first. If it doesn't exist, we're done. 490 // We need the group in order to check if there are instances attached. 491 // If so, we need to remove those first. 492 g, err := getAwsAutoscalingGroup(d.Id(), conn) 493 if err != nil { 494 return err 495 } 496 if g == nil { 497 log.Printf("[INFO] Autoscaling Group %q not found", d.Id()) 498 d.SetId("") 499 return nil 500 } 501 if len(g.Instances) > 0 || *g.DesiredCapacity > 0 { 502 if err := resourceAwsAutoscalingGroupDrain(d, meta); err != nil { 503 return err 504 } 505 } 506 507 log.Printf("[DEBUG] AutoScaling Group destroy: %v", d.Id()) 508 deleteopts := autoscaling.DeleteAutoScalingGroupInput{ 509 AutoScalingGroupName: aws.String(d.Id()), 510 ForceDelete: aws.Bool(d.Get("force_delete").(bool)), 511 } 512 513 // We retry the delete operation to handle InUse/InProgress errors coming 514 // from scaling operations. We should be able to sneak in a delete in between 515 // scaling operations within 5m. 516 err = resource.Retry(5*time.Minute, func() *resource.RetryError { 517 if _, err := conn.DeleteAutoScalingGroup(&deleteopts); err != nil { 518 if awserr, ok := err.(awserr.Error); ok { 519 switch awserr.Code() { 520 case "InvalidGroup.NotFound": 521 // Already gone? Sure! 522 return nil 523 case "ResourceInUse", "ScalingActivityInProgress": 524 // These are retryable 525 return resource.RetryableError(awserr) 526 } 527 } 528 // Didn't recognize the error, so shouldn't retry. 529 return resource.NonRetryableError(err) 530 } 531 // Successful delete 532 return nil 533 }) 534 if err != nil { 535 return err 536 } 537 538 return resource.Retry(5*time.Minute, func() *resource.RetryError { 539 if g, _ = getAwsAutoscalingGroup(d.Id(), conn); g != nil { 540 return resource.RetryableError( 541 fmt.Errorf("Auto Scaling Group still exists")) 542 } 543 return nil 544 }) 545 } 546 547 func getAwsAutoscalingGroup( 548 asgName string, 549 conn *autoscaling.AutoScaling) (*autoscaling.Group, error) { 550 551 describeOpts := autoscaling.DescribeAutoScalingGroupsInput{ 552 AutoScalingGroupNames: []*string{aws.String(asgName)}, 553 } 554 555 log.Printf("[DEBUG] AutoScaling Group describe configuration: %#v", describeOpts) 556 describeGroups, err := conn.DescribeAutoScalingGroups(&describeOpts) 557 if err != nil { 558 autoscalingerr, ok := err.(awserr.Error) 559 if ok && autoscalingerr.Code() == "InvalidGroup.NotFound" { 560 return nil, nil 561 } 562 563 return nil, fmt.Errorf("Error retrieving AutoScaling groups: %s", err) 564 } 565 566 // Search for the autoscaling group 567 for idx, asc := range describeGroups.AutoScalingGroups { 568 if *asc.AutoScalingGroupName == asgName { 569 return describeGroups.AutoScalingGroups[idx], nil 570 } 571 } 572 573 return nil, nil 574 } 575 576 func resourceAwsAutoscalingGroupDrain(d *schema.ResourceData, meta interface{}) error { 577 conn := meta.(*AWSClient).autoscalingconn 578 579 if d.Get("force_delete").(bool) { 580 log.Printf("[DEBUG] Skipping ASG drain, force_delete was set.") 581 return nil 582 } 583 584 // First, set the capacity to zero so the group will drain 585 log.Printf("[DEBUG] Reducing autoscaling group capacity to zero") 586 opts := autoscaling.UpdateAutoScalingGroupInput{ 587 AutoScalingGroupName: aws.String(d.Id()), 588 DesiredCapacity: aws.Int64(0), 589 MinSize: aws.Int64(0), 590 MaxSize: aws.Int64(0), 591 } 592 if _, err := conn.UpdateAutoScalingGroup(&opts); err != nil { 593 return fmt.Errorf("Error setting capacity to zero to drain: %s", err) 594 } 595 596 // Next, wait for the autoscale group to drain 597 log.Printf("[DEBUG] Waiting for group to have zero instances") 598 return resource.Retry(10*time.Minute, func() *resource.RetryError { 599 g, err := getAwsAutoscalingGroup(d.Id(), conn) 600 if err != nil { 601 return resource.NonRetryableError(err) 602 } 603 if g == nil { 604 log.Printf("[INFO] Autoscaling Group %q not found", d.Id()) 605 d.SetId("") 606 return nil 607 } 608 609 if len(g.Instances) == 0 { 610 return nil 611 } 612 613 return resource.RetryableError( 614 fmt.Errorf("group still has %d instances", len(g.Instances))) 615 }) 616 } 617 618 func enableASGMetricsCollection(d *schema.ResourceData, conn *autoscaling.AutoScaling) error { 619 props := &autoscaling.EnableMetricsCollectionInput{ 620 AutoScalingGroupName: aws.String(d.Id()), 621 Granularity: aws.String(d.Get("metrics_granularity").(string)), 622 Metrics: expandStringList(d.Get("enabled_metrics").(*schema.Set).List()), 623 } 624 625 log.Printf("[INFO] Enabling metrics collection for the ASG: %s", d.Id()) 626 _, metricsErr := conn.EnableMetricsCollection(props) 627 if metricsErr != nil { 628 return metricsErr 629 } 630 631 return nil 632 } 633 634 func updateASGMetricsCollection(d *schema.ResourceData, conn *autoscaling.AutoScaling) error { 635 636 o, n := d.GetChange("enabled_metrics") 637 if o == nil { 638 o = new(schema.Set) 639 } 640 if n == nil { 641 n = new(schema.Set) 642 } 643 644 os := o.(*schema.Set) 645 ns := n.(*schema.Set) 646 647 disableMetrics := os.Difference(ns) 648 if disableMetrics.Len() != 0 { 649 props := &autoscaling.DisableMetricsCollectionInput{ 650 AutoScalingGroupName: aws.String(d.Id()), 651 Metrics: expandStringList(disableMetrics.List()), 652 } 653 654 _, err := conn.DisableMetricsCollection(props) 655 if err != nil { 656 return fmt.Errorf("Failure to Disable metrics collection types for ASG %s: %s", d.Id(), err) 657 } 658 } 659 660 enabledMetrics := ns.Difference(os) 661 if enabledMetrics.Len() != 0 { 662 props := &autoscaling.EnableMetricsCollectionInput{ 663 AutoScalingGroupName: aws.String(d.Id()), 664 Metrics: expandStringList(enabledMetrics.List()), 665 Granularity: aws.String(d.Get("metrics_granularity").(string)), 666 } 667 668 _, err := conn.EnableMetricsCollection(props) 669 if err != nil { 670 return fmt.Errorf("Failure to Enable metrics collection types for ASG %s: %s", d.Id(), err) 671 } 672 } 673 674 return nil 675 } 676 677 // Returns a mapping of the instance states of all the ELBs attached to the 678 // provided ASG. 679 // 680 // Nested like: lbName -> instanceId -> instanceState 681 func getLBInstanceStates(g *autoscaling.Group, meta interface{}) (map[string]map[string]string, error) { 682 lbInstanceStates := make(map[string]map[string]string) 683 elbconn := meta.(*AWSClient).elbconn 684 685 for _, lbName := range g.LoadBalancerNames { 686 lbInstanceStates[*lbName] = make(map[string]string) 687 opts := &elb.DescribeInstanceHealthInput{LoadBalancerName: lbName} 688 r, err := elbconn.DescribeInstanceHealth(opts) 689 if err != nil { 690 return nil, err 691 } 692 for _, is := range r.InstanceStates { 693 if is.InstanceId == nil || is.State == nil { 694 continue 695 } 696 lbInstanceStates[*lbName][*is.InstanceId] = *is.State 697 } 698 } 699 700 return lbInstanceStates, nil 701 } 702 703 func expandVpcZoneIdentifiers(list []interface{}) *string { 704 strs := make([]string, len(list)) 705 for _, s := range list { 706 strs = append(strs, s.(string)) 707 } 708 return aws.String(strings.Join(strs, ",")) 709 }