From 59dad712026db6e613feeb5739471ab2905a34ec Mon Sep 17 00:00:00 2001 From: Andreas Skarmutsos Lindh Date: Fri, 15 Jul 2016 13:54:36 +0200 Subject: [PATCH 1/5] AWS Application AutoScaling Initial work on two new resource types: * `aws_appautoscaling_target` * `aws_appautoscaling_policy` --- builtin/providers/aws/config.go | 3 + builtin/providers/aws/provider.go | 2 + .../aws/resource_aws_appautoscaling_policy.go | 331 ++++++++++++++++++ ...resource_aws_appautoscaling_policy_test.go | 121 +++++++ .../aws/resource_aws_appautoscaling_target.go | 202 +++++++++++ ...resource_aws_appautoscaling_target_test.go | 146 ++++++++ .../aws/r/appautoscaling_policy.html.markdown | 74 ++++ .../aws/r/appautoscaling_target.html.markdown | 40 +++ 8 files changed, 919 insertions(+) create mode 100644 builtin/providers/aws/resource_aws_appautoscaling_policy.go create mode 100644 builtin/providers/aws/resource_aws_appautoscaling_policy_test.go create mode 100644 builtin/providers/aws/resource_aws_appautoscaling_target.go create mode 100644 builtin/providers/aws/resource_aws_appautoscaling_target_test.go create mode 100644 website/source/docs/providers/aws/r/appautoscaling_policy.html.markdown create mode 100644 website/source/docs/providers/aws/r/appautoscaling_target.html.markdown diff --git a/builtin/providers/aws/config.go b/builtin/providers/aws/config.go index a9b49528c028..e5e69d46bb87 100644 --- a/builtin/providers/aws/config.go +++ b/builtin/providers/aws/config.go @@ -18,6 +18,7 @@ import ( "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/apigateway" + "github.com/aws/aws-sdk-go/service/applicationautoscaling" "github.com/aws/aws-sdk-go/service/autoscaling" "github.com/aws/aws-sdk-go/service/cloudformation" "github.com/aws/aws-sdk-go/service/cloudfront" @@ -94,6 +95,7 @@ type AWSClient struct { emrconn *emr.EMR esconn *elasticsearch.ElasticsearchService apigateway *apigateway.APIGateway + appautoscalingconn *applicationautoscaling.ApplicationAutoScaling autoscalingconn *autoscaling.AutoScaling s3conn *s3.S3 sesConn *ses.SES @@ -213,6 +215,7 @@ func (c *Config) Client() (interface{}, error) { } client.apigateway = apigateway.New(sess) + client.appautoscalingconn = applicationautoscaling.New(sess) client.autoscalingconn = autoscaling.New(sess) client.cfconn = cloudformation.New(sess) client.cloudfrontconn = cloudfront.New(sess) diff --git a/builtin/providers/aws/provider.go b/builtin/providers/aws/provider.go index edb2a744f6b8..215a8b07b274 100644 --- a/builtin/providers/aws/provider.go +++ b/builtin/providers/aws/provider.go @@ -134,6 +134,8 @@ func Provider() terraform.ResourceProvider { "aws_api_gateway_resource": resourceAwsApiGatewayResource(), "aws_api_gateway_rest_api": resourceAwsApiGatewayRestApi(), "aws_app_cookie_stickiness_policy": resourceAwsAppCookieStickinessPolicy(), + "aws_appautoscaling_target": resourceAwsAppautoscalingTarget(), + "aws_appautoscaling_policy": resourceAwsAppautoscalingPolicy(), "aws_autoscaling_group": resourceAwsAutoscalingGroup(), "aws_autoscaling_notification": resourceAwsAutoscalingNotification(), "aws_autoscaling_policy": resourceAwsAutoscalingPolicy(), diff --git a/builtin/providers/aws/resource_aws_appautoscaling_policy.go b/builtin/providers/aws/resource_aws_appautoscaling_policy.go new file mode 100644 index 000000000000..44461e3a74a5 --- /dev/null +++ b/builtin/providers/aws/resource_aws_appautoscaling_policy.go @@ -0,0 +1,331 @@ +package aws + +import ( + "bytes" + "fmt" + "log" + "strconv" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/applicationautoscaling" + "github.com/hashicorp/terraform/helper/hashcode" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceAwsAppautoscalingPolicy() *schema.Resource { + return &schema.Resource{ + Create: resourceAwsAppautoscalingPolicyCreate, + Read: resourceAwsAppautoscalingPolicyRead, + Update: resourceAwsAppautoscalingPolicyUpdate, + Delete: resourceAwsAppautoscalingPolicyDelete, + + Schema: map[string]*schema.Schema{ + "name": &schema.Schema{ + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { + // https://github.com/boto/botocore/blob/9f322b1/botocore/data/autoscaling/2011-01-01/service-2.json#L1862-L1873 + value := v.(string) + if len(value) > 255 { + errors = append(errors, fmt.Errorf("q cannot be longer than 255 characters", k)) + } + return + }, + }, + "arn": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + "policy_type": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Default: "StepScaling", + }, + "resource_id": &schema.Schema{ + Type: schema.TypeString, + Required: true, + }, + "scalable_dimension": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Default: "ecs:service:DesiredCount", + ForceNew: true, + }, + "service_namespace": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Default: "ecs", + ForceNew: true, + }, + "adjustment_type": &schema.Schema{ + Type: schema.TypeString, + Required: true, + }, + "cooldown": &schema.Schema{ + Type: schema.TypeInt, + Required: true, + }, + "metric_aggregation_type": &schema.Schema{ + Type: schema.TypeString, + Required: true, + }, + "min_adjustment_magnitude": &schema.Schema{ + Type: schema.TypeInt, + Optional: true, + }, + "alarms": &schema.Schema{ + Type: schema.TypeList, + Optional: true, + ForceNew: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "step_adjustment": &schema.Schema{ + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "metric_interval_lower_bound": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + }, + "metric_interval_upper_bound": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + }, + "scaling_adjustment": &schema.Schema{ + Type: schema.TypeInt, + Required: true, + }, + }, + }, + Set: resourceAwsAppautoscalingAdjustmentHash, + }, + }, + } +} + +func resourceAwsAppautoscalingPolicyCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).appautoscalingconn + + params, err := getAwsAppautoscalingPutScalingPolicyInput(d) + if err != nil { + return err + } + + log.Printf("[DEBUG] ApplicationAutoScaling PutScalingPolicy: %#v", params) + resp, err := conn.PutScalingPolicy(¶ms) + if err != nil { + return fmt.Errorf("Error putting scaling policy: %s", err) + } + + d.Set("arn", resp.PolicyARN) + d.SetId(d.Get("name").(string)) + log.Printf("[INFO] ApplicationAutoScaling scaling PolicyARN: %s", d.Get("arn").(string)) + + return resourceAwsAppautoscalingPolicyRead(d, meta) +} + +func resourceAwsAppautoscalingPolicyRead(d *schema.ResourceData, meta interface{}) error { + p, err := getAwsAppautoscalingPolicy(d, meta) + if err != nil { + return err + } + if p == nil { + d.SetId("") + return nil + } + + log.Printf("[DEBUG] Read ApplicationAutoScaling policy: %s, SP: %s, Obj: %s", d.Get("name"), d.Get("name"), p) + + d.Set("arn", p.PolicyARN) + d.Set("name", p.PolicyName) + d.Set("policy_type", p.PolicyType) + d.Set("resource_id", p.ResourceId) + d.Set("scalable_dimension", p.ScalableDimension) + d.Set("service_namespace", p.ServiceNamespace) + d.Set("alarms", p.Alarms) + d.Set("step_scaling_policy_configuration", p.StepScalingPolicyConfiguration) + + return nil +} + +func resourceAwsAppautoscalingPolicyUpdate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).appautoscalingconn + + params, inputErr := getAwsAppautoscalingPutScalingPolicyInput(d) + if inputErr != nil { + return inputErr + } + + log.Printf("[DEBUG] Application Autoscaling Update Scaling Policy: %#v", params) + _, err := conn.PutScalingPolicy(¶ms) + if err != nil { + return err + } + + return resourceAwsAppautoscalingPolicyRead(d, meta) +} + +func resourceAwsAppautoscalingPolicyDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).appautoscalingconn + p, err := getAwsAppautoscalingPolicy(d, meta) + if err != nil { + return fmt.Errorf("Error getting policy: %s", err) + } + if p == nil { + return nil + } + + params := applicationautoscaling.DeleteScalingPolicyInput{ + PolicyName: aws.String(d.Get("name").(string)), + ResourceId: aws.String(d.Get("resource_id").(string)), + ScalableDimension: aws.String(d.Get("scalable_dimension").(string)), + ServiceNamespace: aws.String(d.Get("service_namespace").(string)), + } + log.Printf("[DEBUG] Deleting Application AutoScaling Policy opts: %#v", params) + if _, err := conn.DeleteScalingPolicy(¶ms); err != nil { + return fmt.Errorf("Application AutoScaling Policy: %s", err) + } + + d.SetId("") + return nil +} + +// Takes the result of flatmap.Expand for an array of step adjustments and +// returns a []*applicationautoscaling.StepAdjustment. +func expandAppautoscalingStepAdjustments(configured []interface{}) ([]*applicationautoscaling.StepAdjustment, error) { + var adjustments []*applicationautoscaling.StepAdjustment + + // Loop over our configured step adjustments and create an array + // of aws-sdk-go compatible objects. We're forced to convert strings + // to floats here because there's no way to detect whether or not + // an uninitialized, optional schema element is "0.0" deliberately. + // With strings, we can test for "", which is definitely an empty + // struct value. + for _, raw := range configured { + data := raw.(map[string]interface{}) + a := &applicationautoscaling.StepAdjustment{ + ScalingAdjustment: aws.Int64(int64(data["scaling_adjustment"].(int))), + } + if data["metric_interval_lower_bound"] != "" { + bound := data["metric_interval_lower_bound"] + switch bound := bound.(type) { + case string: + f, err := strconv.ParseFloat(bound, 64) + if err != nil { + return nil, fmt.Errorf( + "metric_interval_lower_bound must be a float value represented as a string") + } + a.MetricIntervalLowerBound = aws.Float64(f) + default: + return nil, fmt.Errorf( + "metric_interval_lower_bound isn't a string. This is a bug. Please file an issue.") + } + } + if data["metric_interval_upper_bound"] != "" { + bound := data["metric_interval_upper_bound"] + switch bound := bound.(type) { + case string: + f, err := strconv.ParseFloat(bound, 64) + if err != nil { + return nil, fmt.Errorf( + "metric_interval_upper_bound must be a float value represented as a string") + } + a.MetricIntervalUpperBound = aws.Float64(f) + default: + return nil, fmt.Errorf( + "metric_interval_upper_bound isn't a string. This is a bug. Please file an issue.") + } + } + adjustments = append(adjustments, a) + } + + return adjustments, nil +} + +func getAwsAppautoscalingPutScalingPolicyInput(d *schema.ResourceData) (applicationautoscaling.PutScalingPolicyInput, error) { + var params = applicationautoscaling.PutScalingPolicyInput{ + PolicyName: aws.String(d.Get("name").(string)), + ResourceId: aws.String(d.Get("resource_id").(string)), + } + + if v, ok := d.GetOk("policy_type"); ok { + params.PolicyType = aws.String(v.(string)) + } + + if v, ok := d.GetOk("service_namespace"); ok { + params.ServiceNamespace = aws.String(v.(string)) + } + + if v, ok := d.GetOk("policy_type"); ok { + params.PolicyType = aws.String(v.(string)) + } + + if v, ok := d.GetOk("scalable_dimension"); ok { + params.ScalableDimension = aws.String(v.(string)) + } + + var adjustmentSteps []*applicationautoscaling.StepAdjustment + if v, ok := d.GetOk("step_adjustment"); ok { + steps, err := expandAppautoscalingStepAdjustments(v.(*schema.Set).List()) + if err != nil { + return params, fmt.Errorf("metric_interval_lower_bound and metric_interval_upper_bound must be strings!") + } + adjustmentSteps = steps + } + + // build StepScalingPolicyConfiguration + params.StepScalingPolicyConfiguration = &applicationautoscaling.StepScalingPolicyConfiguration{ + AdjustmentType: aws.String(d.Get("adjustment_type").(string)), + Cooldown: aws.Int64(int64(d.Get("cooldown").(int))), + MetricAggregationType: aws.String(d.Get("metric_aggregation_type").(string)), + StepAdjustments: adjustmentSteps, + } + + if v, ok := d.GetOk("min_adjustment_magnitude"); ok { + params.StepScalingPolicyConfiguration.MinAdjustmentMagnitude = aws.Int64(int64(v.(int))) + } + + return params, nil +} + +func getAwsAppautoscalingPolicy(d *schema.ResourceData, meta interface{}) (*applicationautoscaling.ScalingPolicy, error) { + conn := meta.(*AWSClient).appautoscalingconn + + params := applicationautoscaling.DescribeScalingPoliciesInput{ + PolicyNames: []*string{aws.String(d.Get("name").(string))}, + ServiceNamespace: aws.String(d.Get("service_namespace").(string)), + } + + log.Printf("[DEBUG] Application AutoScaling Policy Describe Params: %#v", params) + resp, err := conn.DescribeScalingPolicies(¶ms) + if err != nil { + return nil, fmt.Errorf("Error retrieving scaling policies: %s", err) + } + + // find scaling policy + name := d.Get("name") + for idx, sp := range resp.ScalingPolicies { + if *sp.PolicyName == name { + return resp.ScalingPolicies[idx], nil + } + } + + // policy not found + return nil, nil +} + +func resourceAwsAppautoscalingAdjustmentHash(v interface{}) int { + var buf bytes.Buffer + m := v.(map[string]interface{}) + if v, ok := m["metric_interval_lower_bound"]; ok { + buf.WriteString(fmt.Sprintf("%f-", v)) + } + if v, ok := m["metric_interval_upper_bound"]; ok { + buf.WriteString(fmt.Sprintf("%f-", v)) + } + buf.WriteString(fmt.Sprintf("%d-", m["scaling_adjustment"].(int))) + + return hashcode.String(buf.String()) +} diff --git a/builtin/providers/aws/resource_aws_appautoscaling_policy_test.go b/builtin/providers/aws/resource_aws_appautoscaling_policy_test.go new file mode 100644 index 000000000000..0bd8c9a762fd --- /dev/null +++ b/builtin/providers/aws/resource_aws_appautoscaling_policy_test.go @@ -0,0 +1,121 @@ +package aws + +import ( + "fmt" + "testing" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/applicationautoscaling" + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccAWSAppautoscalingPolicy_basic(t *testing.T) { + var policy applicationautoscaling.ScalingPolicy + + name := fmt.Sprintf("terraform-test-foobar-%s", acctest.RandString(5)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSAppautoscalingPolicyDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccAWSAppautoscalingPolicyConfig(name), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAppautoscalingPolicyExists("aws_appautoscaling_policy.foobar_simple", &policy), + resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_simple", "adjustment_type", "ChangeInCapacity"), + resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_simple", "policy_type", "StepScaling"), + resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_simple", "cooldown", "60"), + resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_simple", "name", "foobar_simple"), + resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_simple", "scaling_adjustment", "2"), + resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_simple", "resource_id", "service/default/foobar_simple"), + resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_simple", "service_namespace", "ecs"), + resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_simple", "scalable_dimension", "ecs:service:DesiredCount"), + ), + }, + }, + }) +} + +func testAccCheckAWSAppautoscalingPolicyExists(n string, policy *applicationautoscaling.ScalingPolicy) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + conn := testAccProvider.Meta().(*AWSClient).appautoscalingconn + params := &applicationautoscaling.DescribeScalingPoliciesInput{ + ServiceNamespace: aws.String(rs.Primary.Attributes["service_namespace"]), + PolicyNames: []*string{aws.String(rs.Primary.ID)}, + } + resp, err := conn.DescribeScalingPolicies(params) + if err != nil { + return err + } + if len(resp.ScalingPolicies) == 0 { + return fmt.Errorf("ScalingPolicy %s not found", rs.Primary.ID) + } + + return nil + } +} + +func testAccCheckAWSAppautoscalingPolicyDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*AWSClient).appautoscalingconn + + for _, rs := range s.RootModule().Resources { + params := applicationautoscaling.DescribeScalingPoliciesInput{ + ServiceNamespace: aws.String(rs.Primary.Attributes["service_namespace"]), + PolicyNames: []*string{aws.String(rs.Primary.ID)}, + } + + resp, err := conn.DescribeScalingPolicies(¶ms) + + if err == nil { + if len(resp.ScalingPolicies) != 0 && + *resp.ScalingPolicies[0].PolicyName == rs.Primary.ID { + return fmt.Errorf("Application autoscaling policy still exists: %s", rs.Primary.ID) + } + } + } + + return nil +} + +func testAccAWSAppautoscalingPolicyConfig(name string) string { + return fmt.Sprintf(` +resource "aws_appautoscaling_policy" "up" { + name = "%s" + service_namespace = "ecs" + resource_id = "service/default/foobar" + scalable_dimension = "ecs:service:DesiredCount" + + adjustment_type = "ExactCapacity" + cooldown = 60 + metric_aggregation_type = "Maximum" + min_adjustment_magnitude = 1 + + step_adjustment { + scaling_adjustment = 1 + } +} +resource "aws_appautoscaling_policy" "down" { + name = "%s" + service_namespace = "ecs" + resource_id = "service/default/foobar" + scalable_dimension = "ecs:service:DesiredCount" + + adjustment_type = "ExactCapacity" + cooldown = 60 + metric_aggregation_type = "Maximum" + min_adjustment_magnitude = 1 + + step_adjustment { + scaling_adjustment = -1 + } +} +`, name, name) +} diff --git a/builtin/providers/aws/resource_aws_appautoscaling_target.go b/builtin/providers/aws/resource_aws_appautoscaling_target.go new file mode 100644 index 000000000000..bbfade4dd53d --- /dev/null +++ b/builtin/providers/aws/resource_aws_appautoscaling_target.go @@ -0,0 +1,202 @@ +package aws + +import ( + "fmt" + "log" + "time" + + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/helper/schema" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/service/applicationautoscaling" +) + +func resourceAwsAppautoscalingTarget() *schema.Resource { + return &schema.Resource{ + Create: resourceAwsAppautoscalingTargetCreate, + Read: resourceAwsAppautoscalingTargetRead, + Delete: resourceAwsAppautoscalingTargetDelete, + + Schema: map[string]*schema.Schema{ + "name": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { + // https://github.com/boto/botocore/blob/9f322b1/botocore/data/autoscaling/2011-01-01/service-2.json#L1862-L1873 + value := v.(string) + if len(value) > 255 { + errors = append(errors, fmt.Errorf( + "%q cannot be longer than 255 characters", k)) + } + return + }, + }, + "arn": &schema.Schema{ + Type: schema.TypeString, + Computed: true, + }, + "max_capacity": &schema.Schema{ + Type: schema.TypeInt, + Required: true, + ForceNew: true, + }, + "min_capacity": &schema.Schema{ + Type: schema.TypeInt, + Required: true, + ForceNew: true, + }, + "resource_id": &schema.Schema{ + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "role_arn": &schema.Schema{ + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "scalable_dimension": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Default: "ecs:service:DesiredCount", + ForceNew: true, + }, + "service_namespace": &schema.Schema{ + Type: schema.TypeString, + Optional: true, + Default: "ecs", + ForceNew: true, + }, + }, + } +} + +func resourceAwsAppautoscalingTargetCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).appautoscalingconn + + var targetOpts applicationautoscaling.RegisterScalableTargetInput + + targetOpts.MaxCapacity = aws.Int64(int64(d.Get("max_capacity").(int))) + targetOpts.MinCapacity = aws.Int64(int64(d.Get("min_capacity").(int))) + targetOpts.ResourceId = aws.String(d.Get("resource_id").(string)) + targetOpts.RoleARN = aws.String(d.Get("role_arn").(string)) + targetOpts.ScalableDimension = aws.String(d.Get("scalable_dimension").(string)) + targetOpts.ServiceNamespace = aws.String(d.Get("service_namespace").(string)) + + log.Printf("[DEBUG] Application autoscaling target create configuration %#v", targetOpts) + _, err := conn.RegisterScalableTarget(&targetOpts) + if err != nil { + return fmt.Errorf("Error creating application autoscaling target: %s", err) + } + + d.SetId(d.Get("resource_id").(string)) + log.Printf("[INFO] Application AutoScaling Target ID: %s", d.Id()) + + return resourceAwsAppautoscalingTargetRead(d, meta) +} + +func resourceAwsAppautoscalingTargetRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).appautoscalingconn + + t, err := getAwsAppautoscalingTarget(d, conn) + if err != nil { + return err + } + if t == nil { + log.Printf("[INFO] Application AutoScaling Target %q not found", d.Id()) + d.SetId("") + return nil + } + + d.Set("max_capacity", t.MaxCapacity) + d.Set("min_capacity", t.MinCapacity) + d.Set("resource_id", t.ResourceId) + d.Set("role_arn", t.RoleARN) + d.Set("scalable_dimension", t.ScalableDimension) + d.Set("service_namespace", t.ServiceNamespace) + + return nil +} + +// Updating Target is not supported +// func getAwsAppautoscalingTargetUpdate(d *schema.ResourceData, meta interface{}) error { +// conn := meta.(*AWSClient).appautoscalingconn + +// } + +func resourceAwsAppautoscalingTargetDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).appautoscalingconn + + t, err := getAwsAppautoscalingTarget(d, conn) + if err != nil { + return err + } + if t == nil { + log.Printf("[INFO] Application AutoScaling Target %q not found", d.Id()) + d.SetId("") + return nil + } + + log.Printf("[DEBUG] Application AutoScaling Target destroy: %#v", d.Id()) + deleteOpts := applicationautoscaling.DeregisterScalableTargetInput{ + ResourceId: aws.String(d.Get("resource_id").(string)), + ServiceNamespace: aws.String(d.Get("service_namespace").(string)), + ScalableDimension: aws.String(d.Get("scalable_dimension").(string)), + } + + err = resource.Retry(5*time.Minute, func() *resource.RetryError { + if _, err := conn.DeregisterScalableTarget(&deleteOpts); err != nil { + if awserr, ok := err.(awserr.Error); ok { + // @TODO: We should do stuff here depending on the actual error returned + return resource.RetryableError(awserr) + } + // Non recognized error, no retry. + return resource.NonRetryableError(err) + } + // Successful delete + return nil + }) + if err != nil { + return err + } + + return resource.Retry(5*time.Minute, func() *resource.RetryError { + if t, _ = getAwsAppautoscalingTarget(d, conn); t != nil { + return resource.RetryableError( + fmt.Errorf("Application AutoScaling Target still exists")) + } + return nil + }) +} + +func getAwsAppautoscalingTarget( + d *schema.ResourceData, + conn *applicationautoscaling.ApplicationAutoScaling) (*applicationautoscaling.ScalableTarget, error) { + + tgtName := d.Id() + describeOpts := applicationautoscaling.DescribeScalableTargetsInput{ + ResourceIds: []*string{aws.String(tgtName)}, + ServiceNamespace: aws.String(d.Get("service_namespace").(string)), + } + + log.Printf("[DEBUG] Application AutoScaling Target describe configuration: %#v", describeOpts) + describeTargets, err := conn.DescribeScalableTargets(&describeOpts) + if err != nil { + // @TODO: We should probably send something else back if we're trying to access an unknown Resource ID + // targetserr, ok := err.(awserr.Error) + // if ok && targetserr.Code() == "" + return nil, fmt.Errorf("Error retrieving Application AutoScaling Target: %s", err) + } + + for idx, tgt := range describeTargets.ScalableTargets { + if *tgt.ResourceId == tgtName { + return describeTargets.ScalableTargets[idx], nil + } + } + + return nil, nil +} diff --git a/builtin/providers/aws/resource_aws_appautoscaling_target_test.go b/builtin/providers/aws/resource_aws_appautoscaling_target_test.go new file mode 100644 index 000000000000..575dc440b162 --- /dev/null +++ b/builtin/providers/aws/resource_aws_appautoscaling_target_test.go @@ -0,0 +1,146 @@ +package aws + +import ( + "fmt" + "testing" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/service/applicationautoscaling" + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccAWSAppautoScalingTarget_basic(t *testing.T) { + var target applicationautoscaling.ScalableTarget + + randResourceId := fmt.Sprintf("service/default/%s", acctest.RandString(10)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: "aws_appautoscaling_target.bar", + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSAppautoscalingTargetDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccAWSAppautoscalingTargetConfig(randResourceId), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAppautoscalingTargetExists("aws_appautoscaling_target.bar", &target), + testAccCheckAWSAppautoscalingTargetAttributes(&target, randResourceId), + resource.TestCheckResourceAttr("aws_appautoscaling_target.bar", "service_namespace", "ecs"), + resource.TestCheckResourceAttr("aws_appautoscaling_target.bar", "resource_id", randResourceId), + resource.TestCheckResourceAttr("aws_appautoscaling_target.bar", "scalable_dimension", "ecs:service:DesiredCount"), + resource.TestCheckResourceAttr("aws_appautoscaling_target.bar", "min_capacity", "1"), + resource.TestCheckResourceAttr("aws_appautoscaling_target.bar", "max_capacity", "3"), + ), + }, + + resource.TestStep{ + Config: testAccAWSAppautoscalingTargetConfigUpdate(randResourceId), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAppautoscalingTargetExists("aws_appautoscaling_target.bar", &target), + resource.TestCheckResourceAttr("aws_appautoscaling_target.bar", "min_capacity", "3"), + resource.TestCheckResourceAttr("aws_appautoscaling_target.bar", "max_capacity", "6"), + ), + }, + }, + }) +} + +func testAccCheckAWSAppautoscalingTargetDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*AWSClient).appautoscalingconn + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_appautoscaling_target" { + continue + } + + // Try to find the target + describeTargets, err := conn.DescribeScalableTargets( + &applicationautoscaling.DescribeScalableTargetsInput{ + ResourceIds: []*string{aws.String(rs.Primary.ID)}, + }, + ) + + if err == nil { + if len(describeTargets.ScalableTargets) != 0 && + *describeTargets.ScalableTargets[0].ResourceId == rs.Primary.ID { + return fmt.Errorf("Application AutoScaling Target still exists") + } + } + + // Verify error + e, ok := err.(awserr.Error) + if !ok { + return err + } + if e.Code() != "" { + return e + } + } + + return nil +} + +func testAccCheckAWSAppautoscalingTargetExists(n string, target *applicationautoscaling.ScalableTarget) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[n] + if !ok { + return fmt.Errorf("Not found: %s", n) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No Application AutoScaling Target ID is set") + } + + conn := testAccProvider.Meta().(*AWSClient).appautoscalingconn + + describeTargets, err := conn.DescribeScalableTargets( + &applicationautoscaling.DescribeScalableTargetsInput{ + ResourceIds: []*string{aws.String(rs.Primary.ID)}, + }, + ) + + if err != nil { + return err + } + + if len(describeTargets.ScalableTargets) != 1 || + *describeTargets.ScalableTargets[0].ResourceId != rs.Primary.ID { + return fmt.Errorf("Application AutoScaling ResourceId not found") + } + + *target = *describeTargets.ScalableTargets[0] + + return nil + } +} + +func testAccCheckAWSAppautoscalingTargetAttributes(target *applicationautoscaling.ScalableTarget, resourceId string) resource.TestCheckFunc { + return nil +} + +func testAccAWSAppautoscalingTargetConfig(r string) string { + return fmt.Sprintf(` +resource "aws_appautoscaling_target" "foobar" { + service_namespace = "ecs" + resource_id = "service/default/%s" + scalable_dimension = "ecs:service:DesiredCount" + min_capacity = 1 + max_capacity = 3 +} +`, r) +} + +func testAccAWSAppautoscalingTargetConfigUpdate(r string) string { + return fmt.Sprintf(` +resource "aws_appautoscaling_target" "foobar" { + service_namespace = "ecs" + resource_id = "service/default/%s" + scalable_dimension = "ecs:service:DesiredCount" + min_capacity = 2 + max_capacity = 6 +} +`, r) +} diff --git a/website/source/docs/providers/aws/r/appautoscaling_policy.html.markdown b/website/source/docs/providers/aws/r/appautoscaling_policy.html.markdown new file mode 100644 index 000000000000..f4cea7f59d24 --- /dev/null +++ b/website/source/docs/providers/aws/r/appautoscaling_policy.html.markdown @@ -0,0 +1,74 @@ +--- +layout: "aws" +page_title: "AWS: aws_appautoscaling_policy" +sidebar_current: "docs-aws-resource-appautoscaling-policy" +description: |- + Provides an Application AutoScaling Policy resource. +--- + +# aws\_appautoscaling\_policy + +Provides an Application AutoScaling Policy resource. + +## Example Usage +``` +resource "aws_appautoscaling_policy" "down" { + name = "scale-down" + service_namespace = "ecs" + resource_id = "service/ecsclustername/servicename" + scalable_dimension = "ecs:service:DesiredCount" + + adjustment_type = "ChangeInCapacity" + cooldown = 60 + metric_aggregation_type = "Maximum" + + step_adjustment { + metric_interval_lower_bound = 0 + scaling_adjustment = -1 + } + depends_on = ["aws_appautoscaling_target.target"] +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Required) The name of the policy. +* `policy_type` - (Optional) Defaults to "StepScaling" because it is the only option available. +* `resource_id` - (Required) The Resource ID on which you want the Application AutoScaling policy to apply to. For Amazon ECS services, this value is the resource type, followed by the cluster name and service name, such as `service/default/sample-webapp`. +* `scalable_dimension` - (Optional) The scalable dimension of the scalable target that this scaling policy applies to. The scalable dimension contains the service names- pace, resource type, and scaling property, such as `ecs:service:DesiredCount` for the desired task count of an Amazon ECS service. Defaults to `ecs:service:DesiredCount` since that is the only allowed value. +* `service_namespace` - (Optional) The AWS service namespace of the scalable target that this scaling policy applies to. Defaults to `ecs`, because that is currently the only supported option. +* `adjustment_type` - (Required) Specifies whether the adjustment is an absolute number or a percentage of the current capacity. Valid values are `ChangeInCapacity`, `ExactCapacity`, and `PercentChangeInCapacity`. +* `cooldown` - (Required) The amount of time, in seconds, after a scaling activity completes and before the next scaling activity can start. +* `metric_aggregation_type` - (Required) The aggregation type for the policy's metrics. Valid values are "Minimum", "Maximum", and "Average". Without a value, AWS will treat the aggregation type as "Average". +* `step_adjustments` - (Optional) A set of adjustments that manage scaling. These have the following structure: +``` +step_adjustment { + scaling_adjustment = -1 + metric_interval_lower_bound = 1.0 + metric_interval_upper_bound = 2.0 +} +step_adjustment { + scaling_adjustment = 1 + metric_interval_lower_bound = 2.0 + metric_interval_upper_bound = 3.0 +} +``` + +* `scaling_adjustment` - (Required) The number of members by which to +scale, when the adjustment bounds are breached. A positive value scales +up. A negative value scales down. +* `metric_interval_lower_bound` - (Optional) The lower bound for the +difference between the alarm threshold and the CloudWatch metric. +Without a value, AWS will treat this bound as infinity. +* `metric_interval_upper_bound` - (Optional) The upper bound for the +difference between the alarm threshold and the CloudWatch metric. +Without a value, AWS will treat this bound as infinity. The upper bound +must be greater than the lower bound. + +## Attribute Reference +* `arn` - The ARN assigned by AWS to the scaling policy. +* `name` - The scaling policy's name. +* `adjustment_type` - The scaling policy's adjustment type. +* `policy_type` - The scaling policy's type. \ No newline at end of file diff --git a/website/source/docs/providers/aws/r/appautoscaling_target.html.markdown b/website/source/docs/providers/aws/r/appautoscaling_target.html.markdown new file mode 100644 index 000000000000..d435ed47fafb --- /dev/null +++ b/website/source/docs/providers/aws/r/appautoscaling_target.html.markdown @@ -0,0 +1,40 @@ +--- +layout: "aws" +page_title: "AWS: aws_appautoscaling_target" +sidebar_current: "docs-aws-resource-appautoscaling-target" +description: |- + Provides an Application AutoScaling ScalableTarget resource. +--- + +# aws\_appautoscaling\_target + +Provides an Application AutoScaling ScalableTarget resource. + +## Example Usage +``` +resource "aws_appautoscaling_target" "tgt" { + service_namespace = "ecs" + resource_id = "service/clusterName/serviceName" + scalable_dimension = "ecs:service:DesiredCount" + role_arn = "${var.ecs_iam_role}" + min_capacity = 1 + max_capacity = 4 +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Required) The name of the policy. +* `resource_id` - (Required) The Resource ID on which you want the Application AutoScaling policy to apply to. For Amazon ECS services, this value is the resource type, followed by the cluster name and service name, such as `service/default/sample-webapp`. +* `scalable_dimension` - (Optional) The scalable dimension of the scalable target. The scalable dimension contains the service namespace, resource type, and scaling property, such as `ecs:service:DesiredCount` for the desired task count of an Amazon ECS service. Defaults to `ecs:service:DesiredCount` since that is the only allowed value. +* `service_namespace` - (Optional) The AWS service namespace of the scalable target. Defaults to `ecs`, because that is currently the only supported option. +* `max_capacity` - (Required) The max capacity of the scalable target. +* `min_capacity` - (Required) The min capacity of the scalable target. +* `role_arn` - (Required) The ARN of the IAM role that allows Application AutoScaling to modify your scalable target on your behalf. + + +## Attribute Reference +* `arn` - The ARN assigned by AWS to the scaling policy. +* `name` - The scaling policy's name. From 4abdd44741b0a3af95e110d3baef68fe2e5ddaa8 Mon Sep 17 00:00:00 2001 From: Andreas Skarmutsos Lindh Date: Sat, 16 Jul 2016 15:13:35 +0200 Subject: [PATCH 2/5] Fix acc tests --- ...resource_aws_appautoscaling_policy_test.go | 79 ++++++++++------ ...resource_aws_appautoscaling_target_test.go | 91 ++++++++++++++++--- 2 files changed, 130 insertions(+), 40 deletions(-) diff --git a/builtin/providers/aws/resource_aws_appautoscaling_policy_test.go b/builtin/providers/aws/resource_aws_appautoscaling_policy_test.go index 0bd8c9a762fd..cef3d7d74705 100644 --- a/builtin/providers/aws/resource_aws_appautoscaling_policy_test.go +++ b/builtin/providers/aws/resource_aws_appautoscaling_policy_test.go @@ -2,6 +2,7 @@ package aws import ( "fmt" + "os" "testing" "github.com/aws/aws-sdk-go/aws" @@ -13,8 +14,11 @@ import ( func TestAccAWSAppautoscalingPolicy_basic(t *testing.T) { var policy applicationautoscaling.ScalingPolicy + var awsAccountId = os.Getenv("AWS_ACCOUNT_ID") - name := fmt.Sprintf("terraform-test-foobar-%s", acctest.RandString(5)) + randClusterName := fmt.Sprintf("cluster-%s", acctest.RandString(10)) + // randResourceId := fmt.Sprintf("service/%s/%s", randClusterName, acctest.RandString(10)) + randPolicyName := fmt.Sprintf("terraform-test-foobar-%s", acctest.RandString(5)) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -22,15 +26,14 @@ func TestAccAWSAppautoscalingPolicy_basic(t *testing.T) { CheckDestroy: testAccCheckAWSAppautoscalingPolicyDestroy, Steps: []resource.TestStep{ resource.TestStep{ - Config: testAccAWSAppautoscalingPolicyConfig(name), + Config: testAccAWSAppautoscalingPolicyConfig(randClusterName, randPolicyName, awsAccountId), Check: resource.ComposeTestCheckFunc( testAccCheckAWSAppautoscalingPolicyExists("aws_appautoscaling_policy.foobar_simple", &policy), resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_simple", "adjustment_type", "ChangeInCapacity"), resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_simple", "policy_type", "StepScaling"), resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_simple", "cooldown", "60"), - resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_simple", "name", "foobar_simple"), - resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_simple", "scaling_adjustment", "2"), - resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_simple", "resource_id", "service/default/foobar_simple"), + resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_simple", "name", randPolicyName), + resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_simple", "resource_id", fmt.Sprintf("service/%s/foobar", randClusterName)), resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_simple", "service_namespace", "ecs"), resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_simple", "scalable_dimension", "ecs:service:DesiredCount"), ), @@ -85,37 +88,61 @@ func testAccCheckAWSAppautoscalingPolicyDestroy(s *terraform.State) error { return nil } -func testAccAWSAppautoscalingPolicyConfig(name string) string { +func testAccAWSAppautoscalingPolicyConfig( + randClusterName string, + randPolicyName string, + awsAccountId string) string { return fmt.Sprintf(` -resource "aws_appautoscaling_policy" "up" { +resource "aws_ecs_cluster" "foo" { name = "%s" - service_namespace = "ecs" - resource_id = "service/default/foobar" - scalable_dimension = "ecs:service:DesiredCount" - - adjustment_type = "ExactCapacity" - cooldown = 60 - metric_aggregation_type = "Maximum" - min_adjustment_magnitude = 1 +} - step_adjustment { - scaling_adjustment = 1 +resource "aws_ecs_task_definition" "task" { + family = "foobar" + container_definitions = < Date: Sat, 16 Jul 2016 15:21:45 +0200 Subject: [PATCH 3/5] added applicationautoscaling from aws-sdk-go using: `govendor add github.com/aws/aws-sdk-go/service/applicationautoscaling@v1.2.5` --- .../service/applicationautoscaling/api.go | 1450 +++++++++++++++++ .../service/applicationautoscaling/service.go | 112 ++ vendor/vendor.json | 6 + 3 files changed, 1568 insertions(+) create mode 100644 vendor/github.com/aws/aws-sdk-go/service/applicationautoscaling/api.go create mode 100644 vendor/github.com/aws/aws-sdk-go/service/applicationautoscaling/service.go diff --git a/vendor/github.com/aws/aws-sdk-go/service/applicationautoscaling/api.go b/vendor/github.com/aws/aws-sdk-go/service/applicationautoscaling/api.go new file mode 100644 index 000000000000..f2b3fe24540c --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/applicationautoscaling/api.go @@ -0,0 +1,1450 @@ +// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. + +// Package applicationautoscaling provides a client for Application Auto Scaling. +package applicationautoscaling + +import ( + "fmt" + "time" + + "github.com/aws/aws-sdk-go/aws/awsutil" + "github.com/aws/aws-sdk-go/aws/request" +) + +const opDeleteScalingPolicy = "DeleteScalingPolicy" + +// DeleteScalingPolicyRequest generates a "aws/request.Request" representing the +// client's request for the DeleteScalingPolicy operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the DeleteScalingPolicy method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the DeleteScalingPolicyRequest method. +// req, resp := client.DeleteScalingPolicyRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +func (c *ApplicationAutoScaling) DeleteScalingPolicyRequest(input *DeleteScalingPolicyInput) (req *request.Request, output *DeleteScalingPolicyOutput) { + op := &request.Operation{ + Name: opDeleteScalingPolicy, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DeleteScalingPolicyInput{} + } + + req = c.newRequest(op, input, output) + output = &DeleteScalingPolicyOutput{} + req.Data = output + return +} + +// Deletes an Application Auto Scaling scaling policy that was previously created. +// If you are no longer using a scaling policy, you can delete it with this +// operation. +// +// Deleting a policy deletes the underlying alarm action, but does not delete +// the CloudWatch alarm, even if it no longer has an associated action. +// +// To create a new scaling policy or update an existing one, see PutScalingPolicy. +func (c *ApplicationAutoScaling) DeleteScalingPolicy(input *DeleteScalingPolicyInput) (*DeleteScalingPolicyOutput, error) { + req, out := c.DeleteScalingPolicyRequest(input) + err := req.Send() + return out, err +} + +const opDeregisterScalableTarget = "DeregisterScalableTarget" + +// DeregisterScalableTargetRequest generates a "aws/request.Request" representing the +// client's request for the DeregisterScalableTarget operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the DeregisterScalableTarget method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the DeregisterScalableTargetRequest method. +// req, resp := client.DeregisterScalableTargetRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +func (c *ApplicationAutoScaling) DeregisterScalableTargetRequest(input *DeregisterScalableTargetInput) (req *request.Request, output *DeregisterScalableTargetOutput) { + op := &request.Operation{ + Name: opDeregisterScalableTarget, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DeregisterScalableTargetInput{} + } + + req = c.newRequest(op, input, output) + output = &DeregisterScalableTargetOutput{} + req.Data = output + return +} + +// Deregisters a scalable target that was previously registered. If you are +// no longer using a scalable target, you can delete it with this operation. +// When you deregister a scalable target, all of the scaling policies that are +// associated with that scalable target are deleted. +// +// To create a new scalable target or update an existing one, see RegisterScalableTarget. +func (c *ApplicationAutoScaling) DeregisterScalableTarget(input *DeregisterScalableTargetInput) (*DeregisterScalableTargetOutput, error) { + req, out := c.DeregisterScalableTargetRequest(input) + err := req.Send() + return out, err +} + +const opDescribeScalableTargets = "DescribeScalableTargets" + +// DescribeScalableTargetsRequest generates a "aws/request.Request" representing the +// client's request for the DescribeScalableTargets operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the DescribeScalableTargets method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the DescribeScalableTargetsRequest method. +// req, resp := client.DescribeScalableTargetsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +func (c *ApplicationAutoScaling) DescribeScalableTargetsRequest(input *DescribeScalableTargetsInput) (req *request.Request, output *DescribeScalableTargetsOutput) { + op := &request.Operation{ + Name: opDescribeScalableTargets, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &DescribeScalableTargetsInput{} + } + + req = c.newRequest(op, input, output) + output = &DescribeScalableTargetsOutput{} + req.Data = output + return +} + +// Provides descriptive information for scalable targets with a specified service +// namespace. +// +// You can filter the results in a service namespace with the ResourceIds and +// ScalableDimension parameters. +// +// To create a new scalable target or update an existing one, see RegisterScalableTarget. +// If you are no longer using a scalable target, you can deregister it with +// DeregisterScalableTarget. +func (c *ApplicationAutoScaling) DescribeScalableTargets(input *DescribeScalableTargetsInput) (*DescribeScalableTargetsOutput, error) { + req, out := c.DescribeScalableTargetsRequest(input) + err := req.Send() + return out, err +} + +// DescribeScalableTargetsPages iterates over the pages of a DescribeScalableTargets operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeScalableTargets method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeScalableTargets operation. +// pageNum := 0 +// err := client.DescribeScalableTargetsPages(params, +// func(page *DescribeScalableTargetsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *ApplicationAutoScaling) DescribeScalableTargetsPages(input *DescribeScalableTargetsInput, fn func(p *DescribeScalableTargetsOutput, lastPage bool) (shouldContinue bool)) error { + page, _ := c.DescribeScalableTargetsRequest(input) + page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) + return page.EachPage(func(p interface{}, lastPage bool) bool { + return fn(p.(*DescribeScalableTargetsOutput), lastPage) + }) +} + +const opDescribeScalingActivities = "DescribeScalingActivities" + +// DescribeScalingActivitiesRequest generates a "aws/request.Request" representing the +// client's request for the DescribeScalingActivities operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the DescribeScalingActivities method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the DescribeScalingActivitiesRequest method. +// req, resp := client.DescribeScalingActivitiesRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +func (c *ApplicationAutoScaling) DescribeScalingActivitiesRequest(input *DescribeScalingActivitiesInput) (req *request.Request, output *DescribeScalingActivitiesOutput) { + op := &request.Operation{ + Name: opDescribeScalingActivities, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &DescribeScalingActivitiesInput{} + } + + req = c.newRequest(op, input, output) + output = &DescribeScalingActivitiesOutput{} + req.Data = output + return +} + +// Provides descriptive information for scaling activities with a specified +// service namespace. +// +// You can filter the results in a service namespace with the ResourceId and +// ScalableDimension parameters. +// +// Scaling activities are triggered by CloudWatch alarms that are associated +// with scaling policies. To view the existing scaling policies for a service +// namespace, see DescribeScalingPolicies. To create a new scaling policy or +// update an existing one, see PutScalingPolicy. +func (c *ApplicationAutoScaling) DescribeScalingActivities(input *DescribeScalingActivitiesInput) (*DescribeScalingActivitiesOutput, error) { + req, out := c.DescribeScalingActivitiesRequest(input) + err := req.Send() + return out, err +} + +// DescribeScalingActivitiesPages iterates over the pages of a DescribeScalingActivities operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeScalingActivities method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeScalingActivities operation. +// pageNum := 0 +// err := client.DescribeScalingActivitiesPages(params, +// func(page *DescribeScalingActivitiesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *ApplicationAutoScaling) DescribeScalingActivitiesPages(input *DescribeScalingActivitiesInput, fn func(p *DescribeScalingActivitiesOutput, lastPage bool) (shouldContinue bool)) error { + page, _ := c.DescribeScalingActivitiesRequest(input) + page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) + return page.EachPage(func(p interface{}, lastPage bool) bool { + return fn(p.(*DescribeScalingActivitiesOutput), lastPage) + }) +} + +const opDescribeScalingPolicies = "DescribeScalingPolicies" + +// DescribeScalingPoliciesRequest generates a "aws/request.Request" representing the +// client's request for the DescribeScalingPolicies operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the DescribeScalingPolicies method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the DescribeScalingPoliciesRequest method. +// req, resp := client.DescribeScalingPoliciesRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +func (c *ApplicationAutoScaling) DescribeScalingPoliciesRequest(input *DescribeScalingPoliciesInput) (req *request.Request, output *DescribeScalingPoliciesOutput) { + op := &request.Operation{ + Name: opDescribeScalingPolicies, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &DescribeScalingPoliciesInput{} + } + + req = c.newRequest(op, input, output) + output = &DescribeScalingPoliciesOutput{} + req.Data = output + return +} + +// Provides descriptive information for scaling policies with a specified service +// namespace. +// +// You can filter the results in a service namespace with the ResourceId, ScalableDimension, +// and PolicyNames parameters. +// +// To create a new scaling policy or update an existing one, see PutScalingPolicy. +// If you are no longer using a scaling policy, you can delete it with DeleteScalingPolicy. +func (c *ApplicationAutoScaling) DescribeScalingPolicies(input *DescribeScalingPoliciesInput) (*DescribeScalingPoliciesOutput, error) { + req, out := c.DescribeScalingPoliciesRequest(input) + err := req.Send() + return out, err +} + +// DescribeScalingPoliciesPages iterates over the pages of a DescribeScalingPolicies operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeScalingPolicies method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeScalingPolicies operation. +// pageNum := 0 +// err := client.DescribeScalingPoliciesPages(params, +// func(page *DescribeScalingPoliciesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *ApplicationAutoScaling) DescribeScalingPoliciesPages(input *DescribeScalingPoliciesInput, fn func(p *DescribeScalingPoliciesOutput, lastPage bool) (shouldContinue bool)) error { + page, _ := c.DescribeScalingPoliciesRequest(input) + page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) + return page.EachPage(func(p interface{}, lastPage bool) bool { + return fn(p.(*DescribeScalingPoliciesOutput), lastPage) + }) +} + +const opPutScalingPolicy = "PutScalingPolicy" + +// PutScalingPolicyRequest generates a "aws/request.Request" representing the +// client's request for the PutScalingPolicy operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the PutScalingPolicy method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the PutScalingPolicyRequest method. +// req, resp := client.PutScalingPolicyRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +func (c *ApplicationAutoScaling) PutScalingPolicyRequest(input *PutScalingPolicyInput) (req *request.Request, output *PutScalingPolicyOutput) { + op := &request.Operation{ + Name: opPutScalingPolicy, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &PutScalingPolicyInput{} + } + + req = c.newRequest(op, input, output) + output = &PutScalingPolicyOutput{} + req.Data = output + return +} + +// Creates or updates a policy for an existing Application Auto Scaling scalable +// target. Each scalable target is identified by service namespace, a resource +// ID, and a scalable dimension, and a scaling policy applies to a scalable +// target that is identified by those three attributes. You cannot create a +// scaling policy without first registering a scalable target with RegisterScalableTarget. +// +// To update an existing policy, use the existing policy name and set the parameters +// you want to change. Any existing parameter not changed in an update to an +// existing policy is not changed in this update request. +// +// You can view the existing scaling policies for a service namespace with +// DescribeScalingPolicies. If you are no longer using a scaling policy, you +// can delete it with DeleteScalingPolicy. +func (c *ApplicationAutoScaling) PutScalingPolicy(input *PutScalingPolicyInput) (*PutScalingPolicyOutput, error) { + req, out := c.PutScalingPolicyRequest(input) + err := req.Send() + return out, err +} + +const opRegisterScalableTarget = "RegisterScalableTarget" + +// RegisterScalableTargetRequest generates a "aws/request.Request" representing the +// client's request for the RegisterScalableTarget operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the RegisterScalableTarget method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the RegisterScalableTargetRequest method. +// req, resp := client.RegisterScalableTargetRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +func (c *ApplicationAutoScaling) RegisterScalableTargetRequest(input *RegisterScalableTargetInput) (req *request.Request, output *RegisterScalableTargetOutput) { + op := &request.Operation{ + Name: opRegisterScalableTarget, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &RegisterScalableTargetInput{} + } + + req = c.newRequest(op, input, output) + output = &RegisterScalableTargetOutput{} + req.Data = output + return +} + +// Registers or updates a scalable target. A scalable target is a resource that +// can be scaled up or down with Application Auto Scaling. After you have registered +// a scalable target, you can use this command to update the minimum and maximum +// values for your scalable dimension. +// +// At this time, Application Auto Scaling only supports scaling Amazon ECS +// services. +// +// After you register a scalable target with Application Auto Scaling, you +// can create and apply scaling policies to it with PutScalingPolicy. You can +// view the existing scaling policies for a service namespace with DescribeScalableTargets. +// If you are no longer using a scalable target, you can deregister it with +// DeregisterScalableTarget. +func (c *ApplicationAutoScaling) RegisterScalableTarget(input *RegisterScalableTargetInput) (*RegisterScalableTargetOutput, error) { + req, out := c.RegisterScalableTargetRequest(input) + err := req.Send() + return out, err +} + +// An object representing a CloudWatch alarm associated with a scaling policy. +type Alarm struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the alarm. + AlarmARN *string `type:"string" required:"true"` + + // The name of the alarm. + AlarmName *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s Alarm) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Alarm) GoString() string { + return s.String() +} + +type DeleteScalingPolicyInput struct { + _ struct{} `type:"structure"` + + // The name of the scaling policy to delete. + PolicyName *string `min:"1" type:"string" required:"true"` + + // The unique identifier string for the resource associated with the scaling + // policy. For Amazon ECS services, this value is the resource type, followed + // by the cluster name and service name, such as service/default/sample-webapp. + ResourceId *string `min:"1" type:"string" required:"true"` + + // The scalable dimension associated with the scaling policy. The scalable dimension + // contains the service namespace, resource type, and scaling property, such + // as ecs:service:DesiredCount for the desired task count of an Amazon ECS service. + ScalableDimension *string `type:"string" required:"true" enum:"ScalableDimension"` + + // The namespace for the AWS service that the scaling policy is associated with. + // For more information, see AWS Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#genref-aws-service-namespaces) + // in the Amazon Web Services General Reference. + ServiceNamespace *string `type:"string" required:"true" enum:"ServiceNamespace"` +} + +// String returns the string representation +func (s DeleteScalingPolicyInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteScalingPolicyInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteScalingPolicyInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteScalingPolicyInput"} + if s.PolicyName == nil { + invalidParams.Add(request.NewErrParamRequired("PolicyName")) + } + if s.PolicyName != nil && len(*s.PolicyName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("PolicyName", 1)) + } + if s.ResourceId == nil { + invalidParams.Add(request.NewErrParamRequired("ResourceId")) + } + if s.ResourceId != nil && len(*s.ResourceId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ResourceId", 1)) + } + if s.ScalableDimension == nil { + invalidParams.Add(request.NewErrParamRequired("ScalableDimension")) + } + if s.ServiceNamespace == nil { + invalidParams.Add(request.NewErrParamRequired("ServiceNamespace")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +type DeleteScalingPolicyOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s DeleteScalingPolicyOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteScalingPolicyOutput) GoString() string { + return s.String() +} + +type DeregisterScalableTargetInput struct { + _ struct{} `type:"structure"` + + // The unique identifier string for the resource associated with the scalable + // target. For Amazon ECS services, this value is the resource type, followed + // by the cluster name and service name, such as service/default/sample-webapp. + ResourceId *string `min:"1" type:"string" required:"true"` + + // The scalable dimension associated with the scalable target. The scalable + // dimension contains the service namespace, resource type, and scaling property, + // such as ecs:service:DesiredCount for the desired task count of an Amazon + // ECS service. + ScalableDimension *string `type:"string" required:"true" enum:"ScalableDimension"` + + // The namespace for the AWS service that the scalable target is associated + // with. For more information, see AWS Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#genref-aws-service-namespaces) + // in the Amazon Web Services General Reference. + ServiceNamespace *string `type:"string" required:"true" enum:"ServiceNamespace"` +} + +// String returns the string representation +func (s DeregisterScalableTargetInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeregisterScalableTargetInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeregisterScalableTargetInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeregisterScalableTargetInput"} + if s.ResourceId == nil { + invalidParams.Add(request.NewErrParamRequired("ResourceId")) + } + if s.ResourceId != nil && len(*s.ResourceId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ResourceId", 1)) + } + if s.ScalableDimension == nil { + invalidParams.Add(request.NewErrParamRequired("ScalableDimension")) + } + if s.ServiceNamespace == nil { + invalidParams.Add(request.NewErrParamRequired("ServiceNamespace")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +type DeregisterScalableTargetOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s DeregisterScalableTargetOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeregisterScalableTargetOutput) GoString() string { + return s.String() +} + +type DescribeScalableTargetsInput struct { + _ struct{} `type:"structure"` + + // The maximum number of scalable target results returned by DescribeScalableTargets + // in paginated output. When this parameter is used, DescribeScalableTargets + // returns up to MaxResults results in a single page along with a NextToken + // response element. The remaining results of the initial request can be seen + // by sending another DescribeScalableTargets request with the returned NextToken + // value. This value can be between 1 and 50. If this parameter is not used, + // then DescribeScalableTargets returns up to 50 results and a NextToken value, + // if applicable. + MaxResults *int64 `type:"integer"` + + // The NextToken value returned from a previous paginated DescribeScalableTargets + // request. Pagination continues from the end of the previous results that returned + // the NextToken value. This value is null when there are no more results to + // return. + NextToken *string `type:"string"` + + // The unique identifier string for the resource associated with the scalable + // target. For Amazon ECS services, this value is the resource type, followed + // by the cluster name and service name, such as service/default/sample-webapp. + // If you specify a scalable dimension, you must also specify a resource ID. + ResourceIds []*string `type:"list"` + + // The scalable dimension associated with the scalable target. The scalable + // dimension contains the service namespace, resource type, and scaling property, + // such as ecs:service:DesiredCount for the desired task count of an Amazon + // ECS service. If you specify a scalable dimension, you must also specify a + // resource ID. + ScalableDimension *string `type:"string" enum:"ScalableDimension"` + + // The namespace for the AWS service that the scalable target is associated + // with. For more information, see AWS Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#genref-aws-service-namespaces) + // in the Amazon Web Services General Reference. + ServiceNamespace *string `type:"string" required:"true" enum:"ServiceNamespace"` +} + +// String returns the string representation +func (s DescribeScalableTargetsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeScalableTargetsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeScalableTargetsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeScalableTargetsInput"} + if s.ServiceNamespace == nil { + invalidParams.Add(request.NewErrParamRequired("ServiceNamespace")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +type DescribeScalableTargetsOutput struct { + _ struct{} `type:"structure"` + + // The NextToken value to include in a future DescribeScalableTargets request. + // When the results of a DescribeScalableTargets request exceed MaxResults, + // this value can be used to retrieve the next page of results. This value is + // null when there are no more results to return. + NextToken *string `type:"string"` + + // The list of scalable targets that matches the request parameters. + ScalableTargets []*ScalableTarget `type:"list"` +} + +// String returns the string representation +func (s DescribeScalableTargetsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeScalableTargetsOutput) GoString() string { + return s.String() +} + +type DescribeScalingActivitiesInput struct { + _ struct{} `type:"structure"` + + // The maximum number of scaling activity results returned by DescribeScalingActivities + // in paginated output. When this parameter is used, DescribeScalingActivities + // returns up to MaxResults results in a single page along with a NextToken + // response element. The remaining results of the initial request can be seen + // by sending another DescribeScalingActivities request with the returned NextToken + // value. This value can be between 1 and 50. If this parameter is not used, + // then DescribeScalingActivities returns up to 50 results and a NextToken value, + // if applicable. + MaxResults *int64 `type:"integer"` + + // The NextToken value returned from a previous paginated DescribeScalingActivities + // request. Pagination continues from the end of the previous results that returned + // the NextToken value. This value is null when there are no more results to + // return. + NextToken *string `type:"string"` + + // The unique identifier string for the resource associated with the scaling + // activity. For Amazon ECS services, this value is the resource type, followed + // by the cluster name and service name, such as service/default/sample-webapp. + // If you specify a scalable dimension, you must also specify a resource ID. + ResourceId *string `min:"1" type:"string"` + + // The scalable dimension associated with the scaling activity. The scalable + // dimension contains the service namespace, resource type, and scaling property, + // such as ecs:service:DesiredCount for the desired task count of an Amazon + // ECS service. If you specify a scalable dimension, you must also specify a + // resource ID. + ScalableDimension *string `type:"string" enum:"ScalableDimension"` + + // The namespace for the AWS service that the scaling activity is associated + // with. For more information, see AWS Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#genref-aws-service-namespaces) + // in the Amazon Web Services General Reference. + ServiceNamespace *string `type:"string" required:"true" enum:"ServiceNamespace"` +} + +// String returns the string representation +func (s DescribeScalingActivitiesInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeScalingActivitiesInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeScalingActivitiesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeScalingActivitiesInput"} + if s.ResourceId != nil && len(*s.ResourceId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ResourceId", 1)) + } + if s.ServiceNamespace == nil { + invalidParams.Add(request.NewErrParamRequired("ServiceNamespace")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +type DescribeScalingActivitiesOutput struct { + _ struct{} `type:"structure"` + + // The NextToken value to include in a future DescribeScalingActivities request. + // When the results of a DescribeScalingActivities request exceed MaxResults, + // this value can be used to retrieve the next page of results. This value is + // null when there are no more results to return. + NextToken *string `type:"string"` + + // A list of scaling activity objects. + ScalingActivities []*ScalingActivity `type:"list"` +} + +// String returns the string representation +func (s DescribeScalingActivitiesOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeScalingActivitiesOutput) GoString() string { + return s.String() +} + +type DescribeScalingPoliciesInput struct { + _ struct{} `type:"structure"` + + // The maximum number of scaling policy results returned by DescribeScalingPolicies + // in paginated output. When this parameter is used, DescribeScalingPolicies + // returns up to MaxResults results in a single page along with a NextToken + // response element. The remaining results of the initial request can be seen + // by sending another DescribeScalingPolicies request with the returned NextToken + // value. This value can be between 1 and 50. If this parameter is not used, + // then DescribeScalingPolicies returns up to 50 results and a NextToken value, + // if applicable. + MaxResults *int64 `type:"integer"` + + // The NextToken value returned from a previous paginated DescribeScalingPolicies + // request. Pagination continues from the end of the previous results that returned + // the NextToken value. This value is null when there are no more results to + // return. + NextToken *string `type:"string"` + + // The names of the scaling policies to describe. + PolicyNames []*string `type:"list"` + + // The unique resource identifier string of the scalable target that the scaling + // policy is associated with. For Amazon ECS services, this value is the resource + // type, followed by the cluster name and service name, such as service/default/sample-webapp. + // If you specify a scalable dimension, you must also specify a resource ID. + ResourceId *string `min:"1" type:"string"` + + // The scalable dimension of the scalable target that the scaling policy is + // associated with. The scalable dimension contains the service namespace, resource + // type, and scaling property, such as ecs:service:DesiredCount for the desired + // task count of an Amazon ECS service. If you specify a scalable dimension, + // you must also specify a resource ID. + ScalableDimension *string `type:"string" enum:"ScalableDimension"` + + // The AWS service namespace of the scalable target that the scaling policy + // is associated with. For more information, see AWS Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#genref-aws-service-namespaces) + // in the Amazon Web Services General Reference. + ServiceNamespace *string `type:"string" required:"true" enum:"ServiceNamespace"` +} + +// String returns the string representation +func (s DescribeScalingPoliciesInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeScalingPoliciesInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeScalingPoliciesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeScalingPoliciesInput"} + if s.ResourceId != nil && len(*s.ResourceId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ResourceId", 1)) + } + if s.ServiceNamespace == nil { + invalidParams.Add(request.NewErrParamRequired("ServiceNamespace")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +type DescribeScalingPoliciesOutput struct { + _ struct{} `type:"structure"` + + // The NextToken value to include in a future DescribeScalingPolicies request. + // When the results of a DescribeScalingPolicies request exceed MaxResults, + // this value can be used to retrieve the next page of results. This value is + // null when there are no more results to return. + NextToken *string `type:"string"` + + // A list of scaling policy objects. + ScalingPolicies []*ScalingPolicy `type:"list"` +} + +// String returns the string representation +func (s DescribeScalingPoliciesOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeScalingPoliciesOutput) GoString() string { + return s.String() +} + +type PutScalingPolicyInput struct { + _ struct{} `type:"structure"` + + // The name of the scaling policy. + PolicyName *string `min:"1" type:"string" required:"true"` + + // The policy type. This parameter is required if you are creating a new policy. + PolicyType *string `type:"string" enum:"PolicyType"` + + // The unique resource identifier string for the scalable target that this scaling + // policy applies to. For Amazon ECS services, this value is the resource type, + // followed by the cluster name and service name, such as service/default/sample-webapp. + ResourceId *string `min:"1" type:"string" required:"true"` + + // The scalable dimension of the scalable target that this scaling policy applies + // to. The scalable dimension contains the service namespace, resource type, + // and scaling property, such as ecs:service:DesiredCount for the desired task + // count of an Amazon ECS service. + ScalableDimension *string `type:"string" required:"true" enum:"ScalableDimension"` + + // The AWS service namespace of the scalable target that this scaling policy + // applies to. For more information, see AWS Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#genref-aws-service-namespaces) + // in the Amazon Web Services General Reference. + ServiceNamespace *string `type:"string" required:"true" enum:"ServiceNamespace"` + + // The configuration for the step scaling policy. This parameter is required + // if you are creating a new policy. For more information, see StepScalingPolicyConfiguration + // and StepAdjustment. + StepScalingPolicyConfiguration *StepScalingPolicyConfiguration `type:"structure"` +} + +// String returns the string representation +func (s PutScalingPolicyInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PutScalingPolicyInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *PutScalingPolicyInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PutScalingPolicyInput"} + if s.PolicyName == nil { + invalidParams.Add(request.NewErrParamRequired("PolicyName")) + } + if s.PolicyName != nil && len(*s.PolicyName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("PolicyName", 1)) + } + if s.ResourceId == nil { + invalidParams.Add(request.NewErrParamRequired("ResourceId")) + } + if s.ResourceId != nil && len(*s.ResourceId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ResourceId", 1)) + } + if s.ScalableDimension == nil { + invalidParams.Add(request.NewErrParamRequired("ScalableDimension")) + } + if s.ServiceNamespace == nil { + invalidParams.Add(request.NewErrParamRequired("ServiceNamespace")) + } + if s.StepScalingPolicyConfiguration != nil { + if err := s.StepScalingPolicyConfiguration.Validate(); err != nil { + invalidParams.AddNested("StepScalingPolicyConfiguration", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +type PutScalingPolicyOutput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the resulting scaling policy. + PolicyARN *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s PutScalingPolicyOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PutScalingPolicyOutput) GoString() string { + return s.String() +} + +type RegisterScalableTargetInput struct { + _ struct{} `type:"structure"` + + // The maximum value for this scalable target to scale out to in response to + // scaling activities. This parameter is required if you are registering a new + // scalable target, and it is optional if you are updating an existing one. + MaxCapacity *int64 `type:"integer"` + + // The minimum value for this scalable target to scale in to in response to + // scaling activities. This parameter is required if you are registering a new + // scalable target, and it is optional if you are updating an existing one. + MinCapacity *int64 `type:"integer"` + + // The unique identifier string for the resource to associate with the scalable + // target. For Amazon ECS services, this value is the resource type, followed + // by the cluster name and service name, such as service/default/sample-webapp. + ResourceId *string `min:"1" type:"string" required:"true"` + + // The ARN of the IAM role that allows Application Auto Scaling to modify your + // scalable target on your behalf. This parameter is required if you are registering + // a new scalable target, and it is optional if you are updating an existing + // one. + RoleARN *string `min:"1" type:"string"` + + // The scalable dimension associated with the scalable target. The scalable + // dimension contains the service namespace, resource type, and scaling property, + // such as ecs:service:DesiredCount for the desired task count of an Amazon + // ECS service. + ScalableDimension *string `type:"string" required:"true" enum:"ScalableDimension"` + + // The namespace for the AWS service that the scalable target is associated + // with. For Amazon ECS services, the namespace value is ecs. For more information, + // see AWS Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#genref-aws-service-namespaces) + // in the Amazon Web Services General Reference. + ServiceNamespace *string `type:"string" required:"true" enum:"ServiceNamespace"` +} + +// String returns the string representation +func (s RegisterScalableTargetInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s RegisterScalableTargetInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *RegisterScalableTargetInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "RegisterScalableTargetInput"} + if s.ResourceId == nil { + invalidParams.Add(request.NewErrParamRequired("ResourceId")) + } + if s.ResourceId != nil && len(*s.ResourceId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ResourceId", 1)) + } + if s.RoleARN != nil && len(*s.RoleARN) < 1 { + invalidParams.Add(request.NewErrParamMinLen("RoleARN", 1)) + } + if s.ScalableDimension == nil { + invalidParams.Add(request.NewErrParamRequired("ScalableDimension")) + } + if s.ServiceNamespace == nil { + invalidParams.Add(request.NewErrParamRequired("ServiceNamespace")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +type RegisterScalableTargetOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s RegisterScalableTargetOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s RegisterScalableTargetOutput) GoString() string { + return s.String() +} + +// An object representing a scalable target. +type ScalableTarget struct { + _ struct{} `type:"structure"` + + // The Unix timestamp for when the scalable target was created. + CreationTime *time.Time `type:"timestamp" timestampFormat:"unix" required:"true"` + + // The maximum value for this scalable target to scale out to in response to + // scaling activities. + MaxCapacity *int64 `type:"integer" required:"true"` + + // The minimum value for this scalable target to scale in to in response to + // scaling activities. + MinCapacity *int64 `type:"integer" required:"true"` + + // The unique identifier string for the resource associated with the scalable + // target. For Amazon ECS services, this value is the resource type, followed + // by the cluster name and service name, such as service/default/sample-webapp. + ResourceId *string `min:"1" type:"string" required:"true"` + + // The ARN of the IAM role that allows Application Auto Scaling to modify your + // scalable target on your behalf. + RoleARN *string `min:"1" type:"string" required:"true"` + + // The scalable dimension associated with the scalable target. The scalable + // dimension contains the service namespace, resource type, and scaling property, + // such as ecs:service:DesiredCount for the desired task count of an Amazon + // ECS service. + ScalableDimension *string `type:"string" required:"true" enum:"ScalableDimension"` + + // The namespace for the AWS service that the scalable target is associated + // with. For more information, see AWS Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#genref-aws-service-namespaces) + // in the Amazon Web Services General Reference. + ServiceNamespace *string `type:"string" required:"true" enum:"ServiceNamespace"` +} + +// String returns the string representation +func (s ScalableTarget) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ScalableTarget) GoString() string { + return s.String() +} + +// An object representing a scaling activity. +type ScalingActivity struct { + _ struct{} `type:"structure"` + + // The unique identifier string for the scaling activity. + ActivityId *string `type:"string" required:"true"` + + // A simple description of what caused the scaling activity to happen. + Cause *string `type:"string" required:"true"` + + // A simple description of what action the scaling activity intends to accomplish. + Description *string `type:"string" required:"true"` + + // The details about the scaling activity. + Details *string `type:"string"` + + // The Unix timestamp for when the scaling activity ended. + EndTime *time.Time `type:"timestamp" timestampFormat:"unix"` + + // The unique identifier string for the resource associated with the scaling + // activity. For Amazon ECS services, this value is the resource type, followed + // by the cluster name and service name, such as service/default/sample-webapp. + ResourceId *string `min:"1" type:"string" required:"true"` + + // The scalable dimension associated with the scaling activity. The scalable + // dimension contains the service namespace, resource type, and scaling property, + // such as ecs:service:DesiredCount for the desired task count of an Amazon + // ECS service. + ScalableDimension *string `type:"string" required:"true" enum:"ScalableDimension"` + + // The namespace for the AWS service that the scaling activity is associated + // with. For more information, see AWS Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#genref-aws-service-namespaces) + // in the Amazon Web Services General Reference. + ServiceNamespace *string `type:"string" required:"true" enum:"ServiceNamespace"` + + // The Unix timestamp for when the scaling activity began. + StartTime *time.Time `type:"timestamp" timestampFormat:"unix" required:"true"` + + // Indicates the status of the scaling activity. + StatusCode *string `type:"string" required:"true" enum:"ScalingActivityStatusCode"` + + // A simple message about the current status of the scaling activity. + StatusMessage *string `type:"string"` +} + +// String returns the string representation +func (s ScalingActivity) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ScalingActivity) GoString() string { + return s.String() +} + +// An object representing a scaling policy. +type ScalingPolicy struct { + _ struct{} `type:"structure"` + + // The CloudWatch alarms that are associated with the scaling policy. + Alarms []*Alarm `type:"list"` + + // The Unix timestamp for when the scaling policy was created. + CreationTime *time.Time `type:"timestamp" timestampFormat:"unix" required:"true"` + + // The Amazon Resource Name (ARN) of the scaling policy. + PolicyARN *string `min:"1" type:"string" required:"true"` + + // The name of the scaling policy. + PolicyName *string `min:"1" type:"string" required:"true"` + + // The scaling policy type. + PolicyType *string `type:"string" required:"true" enum:"PolicyType"` + + // The unique identifier string for the resource associated with the scaling + // policy. For Amazon ECS services, this value is the resource type, followed + // by the cluster name and service name, such as service/default/sample-webapp. + ResourceId *string `min:"1" type:"string" required:"true"` + + // The scalable dimension associated with the scaling policy. The scalable dimension + // contains the service namespace, resource type, and scaling property, such + // as ecs:service:DesiredCount for the desired task count of an Amazon ECS service. + ScalableDimension *string `type:"string" required:"true" enum:"ScalableDimension"` + + // The namespace for the AWS service that the scaling policy is associated with. + // For more information, see AWS Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#genref-aws-service-namespaces) + // in the Amazon Web Services General Reference. + ServiceNamespace *string `type:"string" required:"true" enum:"ServiceNamespace"` + + // The configuration for the step scaling policy. + StepScalingPolicyConfiguration *StepScalingPolicyConfiguration `type:"structure"` +} + +// String returns the string representation +func (s ScalingPolicy) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ScalingPolicy) GoString() string { + return s.String() +} + +// An object representing a step adjustment for a StepScalingPolicyConfiguration. +// Describes an adjustment based on the difference between the value of the +// aggregated CloudWatch metric and the breach threshold that you've defined +// for the alarm. +// +// For the following examples, suppose that you have an alarm with a breach +// threshold of 50: +// +// If you want the adjustment to be triggered when the metric is greater +// than or equal to 50 and less than 60, specify a lower bound of 0 and an upper +// bound of 10. +// +// If you want the adjustment to be triggered when the metric is greater +// than 40 and less than or equal to 50, specify a lower bound of -10 and an +// upper bound of 0. +// +// There are a few rules for the step adjustments for your step policy: +// +// The ranges of your step adjustments can't overlap or have a gap. +// +// At most one step adjustment can have a null lower bound. If one step adjustment +// has a negative lower bound, then there must be a step adjustment with a null +// lower bound. +// +// At most one step adjustment can have a null upper bound. If one step adjustment +// has a positive upper bound, then there must be a step adjustment with a null +// upper bound. +// +// The upper and lower bound can't be null in the same step adjustment. +type StepAdjustment struct { + _ struct{} `type:"structure"` + + // The lower bound for the difference between the alarm threshold and the CloudWatch + // metric. If the metric value is above the breach threshold, the lower bound + // is inclusive (the metric must be greater than or equal to the threshold plus + // the lower bound). Otherwise, it is exclusive (the metric must be greater + // than the threshold plus the lower bound). A null value indicates negative + // infinity. + MetricIntervalLowerBound *float64 `type:"double"` + + // The upper bound for the difference between the alarm threshold and the CloudWatch + // metric. If the metric value is above the breach threshold, the upper bound + // is exclusive (the metric must be less than the threshold plus the upper bound). + // Otherwise, it is inclusive (the metric must be less than or equal to the + // threshold plus the upper bound). A null value indicates positive infinity. + // + // The upper bound must be greater than the lower bound. + MetricIntervalUpperBound *float64 `type:"double"` + + // The amount by which to scale, based on the specified adjustment type. A positive + // value adds to the current scalable dimension while a negative number removes + // from the current scalable dimension. + ScalingAdjustment *int64 `type:"integer" required:"true"` +} + +// String returns the string representation +func (s StepAdjustment) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s StepAdjustment) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *StepAdjustment) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "StepAdjustment"} + if s.ScalingAdjustment == nil { + invalidParams.Add(request.NewErrParamRequired("ScalingAdjustment")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// An object representing a step scaling policy configuration. +type StepScalingPolicyConfiguration struct { + _ struct{} `type:"structure"` + + // The adjustment type, which specifies how the ScalingAdjustment parameter + // in a StepAdjustment is interpreted. + AdjustmentType *string `type:"string" enum:"AdjustmentType"` + + // The amount of time, in seconds, after a scaling activity completes where + // previous trigger-related scaling activities can influence future scaling + // events. + // + // For scale out policies, while Cooldown is in effect, the capacity that has + // been added by the previous scale out event that initiated the Cooldown is + // calculated as part of the desired capacity for the next scale out. The intention + // is to continuously (but not excessively) scale out. For example, an alarm + // triggers a step scaling policy to scale out an Amazon ECS service by 2 tasks, + // the scaling activity completes successfully, and a Cooldown period of 5 minutes + // starts. During the Cooldown period, if the alarm triggers the same policy + // again but at a more aggressive step adjustment to scale out the service by + // 3 tasks, the 2 tasks that were added in the previous scale out event are + // considered part of that capacity and only 1 additional task is added to the + // desired count. + // + // For scale in policies, the Cooldown period is used to block subsequent scale + // in requests until it has expired. The intention is to scale in conservatively + // to protect your application's availability. However, if another alarm triggers + // a scale out policy during the Cooldown period after a scale-in, Application + // Auto Scaling scales out your scalable target immediately. + Cooldown *int64 `type:"integer"` + + // The aggregation type for the CloudWatch metrics. Valid values are Minimum, + // Maximum, and Average. + MetricAggregationType *string `type:"string" enum:"MetricAggregationType"` + + // The minimum number to adjust your scalable dimension as a result of a scaling + // activity. If the adjustment type is PercentChangeInCapacity, the scaling + // policy changes the scalable dimension of the scalable target by this amount. + MinAdjustmentMagnitude *int64 `type:"integer"` + + // A set of adjustments that enable you to scale based on the size of the alarm + // breach. + StepAdjustments []*StepAdjustment `type:"list"` +} + +// String returns the string representation +func (s StepScalingPolicyConfiguration) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s StepScalingPolicyConfiguration) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *StepScalingPolicyConfiguration) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "StepScalingPolicyConfiguration"} + if s.StepAdjustments != nil { + for i, v := range s.StepAdjustments { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "StepAdjustments", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +const ( + // @enum AdjustmentType + AdjustmentTypeChangeInCapacity = "ChangeInCapacity" + // @enum AdjustmentType + AdjustmentTypePercentChangeInCapacity = "PercentChangeInCapacity" + // @enum AdjustmentType + AdjustmentTypeExactCapacity = "ExactCapacity" +) + +const ( + // @enum MetricAggregationType + MetricAggregationTypeAverage = "Average" + // @enum MetricAggregationType + MetricAggregationTypeMinimum = "Minimum" + // @enum MetricAggregationType + MetricAggregationTypeMaximum = "Maximum" +) + +const ( + // @enum PolicyType + PolicyTypeStepScaling = "StepScaling" +) + +const ( + // @enum ScalableDimension + ScalableDimensionEcsServiceDesiredCount = "ecs:service:DesiredCount" +) + +const ( + // @enum ScalingActivityStatusCode + ScalingActivityStatusCodePending = "Pending" + // @enum ScalingActivityStatusCode + ScalingActivityStatusCodeInProgress = "InProgress" + // @enum ScalingActivityStatusCode + ScalingActivityStatusCodeSuccessful = "Successful" + // @enum ScalingActivityStatusCode + ScalingActivityStatusCodeOverridden = "Overridden" + // @enum ScalingActivityStatusCode + ScalingActivityStatusCodeUnfulfilled = "Unfulfilled" + // @enum ScalingActivityStatusCode + ScalingActivityStatusCodeFailed = "Failed" +) + +const ( + // @enum ServiceNamespace + ServiceNamespaceEcs = "ecs" +) diff --git a/vendor/github.com/aws/aws-sdk-go/service/applicationautoscaling/service.go b/vendor/github.com/aws/aws-sdk-go/service/applicationautoscaling/service.go new file mode 100644 index 000000000000..d6e797ff2d40 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/applicationautoscaling/service.go @@ -0,0 +1,112 @@ +// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. + +package applicationautoscaling + +import ( + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/client" + "github.com/aws/aws-sdk-go/aws/client/metadata" + "github.com/aws/aws-sdk-go/aws/request" + "github.com/aws/aws-sdk-go/aws/signer/v4" + "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" +) + +// Application Auto Scaling is a general purpose Auto Scaling service for supported +// elastic AWS resources. With Application Auto Scaling, you can automatically +// scale your AWS resources, with an experience similar to that of Auto Scaling. +// +// At this time, Application Auto Scaling only supports scaling Amazon ECS +// services. +// +// For example, you can use Application Auto Scaling to accomplish the following +// tasks: +// +// Define scaling policies for automatically adjusting your application’s +// resources +// +// Scale your resources in response to CloudWatch alarms +// +// View history of your scaling events +// +// Application Auto Scaling is available in the following regions: +// +// us-east-1 +// +// us-west-2 +// +// eu-west-1 +//The service client's operations are safe to be used concurrently. +// It is not safe to mutate any of the client's properties though. +type ApplicationAutoScaling struct { + *client.Client +} + +// Used for custom client initialization logic +var initClient func(*client.Client) + +// Used for custom request initialization logic +var initRequest func(*request.Request) + +// A ServiceName is the name of the service the client will make API calls to. +const ServiceName = "autoscaling" + +// New creates a new instance of the ApplicationAutoScaling client with a session. +// If additional configuration is needed for the client instance use the optional +// aws.Config parameter to add your extra config. +// +// Example: +// // Create a ApplicationAutoScaling client from just a session. +// svc := applicationautoscaling.New(mySession) +// +// // Create a ApplicationAutoScaling client with additional configuration +// svc := applicationautoscaling.New(mySession, aws.NewConfig().WithRegion("us-west-2")) +func New(p client.ConfigProvider, cfgs ...*aws.Config) *ApplicationAutoScaling { + c := p.ClientConfig(ServiceName, cfgs...) + return newClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion) +} + +// newClient creates, initializes and returns a new service client instance. +func newClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion string) *ApplicationAutoScaling { + svc := &ApplicationAutoScaling{ + Client: client.New( + cfg, + metadata.ClientInfo{ + ServiceName: ServiceName, + SigningName: "application-autoscaling", + SigningRegion: signingRegion, + Endpoint: endpoint, + APIVersion: "2016-02-06", + JSONVersion: "1.1", + TargetPrefix: "AnyScaleFrontendService", + }, + handlers, + ), + } + + // Handlers + svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) + svc.Handlers.Build.PushBackNamed(jsonrpc.BuildHandler) + svc.Handlers.Unmarshal.PushBackNamed(jsonrpc.UnmarshalHandler) + svc.Handlers.UnmarshalMeta.PushBackNamed(jsonrpc.UnmarshalMetaHandler) + svc.Handlers.UnmarshalError.PushBackNamed(jsonrpc.UnmarshalErrorHandler) + + // Run custom client initialization if present + if initClient != nil { + initClient(svc.Client) + } + + return svc +} + +// newRequest creates a new request for a ApplicationAutoScaling operation and runs any +// custom request initialization. +func (c *ApplicationAutoScaling) newRequest(op *request.Operation, params, data interface{}) *request.Request { + req := c.NewRequest(op, params, data) + + // Run custom request initialization if present + if initRequest != nil { + initRequest(req) + } + + return req +} diff --git a/vendor/vendor.json b/vendor/vendor.json index b062792b67ed..c31f43c11ede 100644 --- a/vendor/vendor.json +++ b/vendor/vendor.json @@ -474,6 +474,12 @@ "revision": "3c37d29820480639ff03fd66df00a0f27984f88d", "revisionTime": "2016-07-13T21:13:24Z" }, + { + "checksumSHA1": "Td30Frd+lrCLlkMAirUTbjBXq5Q=", + "path": "github.com/aws/aws-sdk-go/service/applicationautoscaling", + "revision": "90dec2183a5f5458ee79cbaf4b8e9ab910bc81a6", + "revisionTime": "2016-07-08T00:08:20Z" + }, { "checksumSHA1": "AUA6op9dlm0X4vv1YPFnIFs6404=", "comment": "v1.1.23", From 2cfd072dd09f5b98adb75b6a9f48c3d5e2f35658 Mon Sep 17 00:00:00 2001 From: Andreas Skarmutsos Lindh Date: Mon, 25 Jul 2016 21:48:16 +0200 Subject: [PATCH 4/5] introduce a retry for scalable target creation Due to possible inconsistencies in IAM, let's retry creation of the scalable target before we fail. --- .../aws/resource_aws_appautoscaling_target.go | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/builtin/providers/aws/resource_aws_appautoscaling_target.go b/builtin/providers/aws/resource_aws_appautoscaling_target.go index bbfade4dd53d..705fee4653d4 100644 --- a/builtin/providers/aws/resource_aws_appautoscaling_target.go +++ b/builtin/providers/aws/resource_aws_appautoscaling_target.go @@ -88,7 +88,21 @@ func resourceAwsAppautoscalingTargetCreate(d *schema.ResourceData, meta interfac targetOpts.ServiceNamespace = aws.String(d.Get("service_namespace").(string)) log.Printf("[DEBUG] Application autoscaling target create configuration %#v", targetOpts) - _, err := conn.RegisterScalableTarget(&targetOpts) + var out *applicationautoscaling.RegisterScalableTargetOutput + var err error + err = resource.Retry(1*time.Minute, func() *resource.RetryError { + out, err = conn.RegisterScalableTarget(&targetOpts) + + if err != nil { + if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "ValidationException" { + log.Printf("[DEBUG] Retrying creation of Application Autoscaling Scalable Target due to possible issues with IAM: %s", awsErr) + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + + return nil + }) if err != nil { return fmt.Errorf("Error creating application autoscaling target: %s", err) } From fb4faf75b21bbddecc130bf1e2d7d0f6f2c00d6c Mon Sep 17 00:00:00 2001 From: Andreas Skarmutsos Lindh Date: Mon, 25 Jul 2016 21:48:41 +0200 Subject: [PATCH 5/5] Added IAM role as part of acceptance test --- ...resource_aws_appautoscaling_policy_test.go | 42 ++++-- ...resource_aws_appautoscaling_target_test.go | 124 ++++++++++++++++-- 2 files changed, 146 insertions(+), 20 deletions(-) diff --git a/builtin/providers/aws/resource_aws_appautoscaling_policy_test.go b/builtin/providers/aws/resource_aws_appautoscaling_policy_test.go index cef3d7d74705..62d6d777d68d 100644 --- a/builtin/providers/aws/resource_aws_appautoscaling_policy_test.go +++ b/builtin/providers/aws/resource_aws_appautoscaling_policy_test.go @@ -2,7 +2,6 @@ package aws import ( "fmt" - "os" "testing" "github.com/aws/aws-sdk-go/aws" @@ -14,9 +13,8 @@ import ( func TestAccAWSAppautoscalingPolicy_basic(t *testing.T) { var policy applicationautoscaling.ScalingPolicy - var awsAccountId = os.Getenv("AWS_ACCOUNT_ID") - randClusterName := fmt.Sprintf("cluster-%s", acctest.RandString(10)) + randClusterName := fmt.Sprintf("cluster%s", acctest.RandString(10)) // randResourceId := fmt.Sprintf("service/%s/%s", randClusterName, acctest.RandString(10)) randPolicyName := fmt.Sprintf("terraform-test-foobar-%s", acctest.RandString(5)) @@ -26,7 +24,7 @@ func TestAccAWSAppautoscalingPolicy_basic(t *testing.T) { CheckDestroy: testAccCheckAWSAppautoscalingPolicyDestroy, Steps: []resource.TestStep{ resource.TestStep{ - Config: testAccAWSAppautoscalingPolicyConfig(randClusterName, randPolicyName, awsAccountId), + Config: testAccAWSAppautoscalingPolicyConfig(randClusterName, randPolicyName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSAppautoscalingPolicyExists("aws_appautoscaling_policy.foobar_simple", &policy), resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_simple", "adjustment_type", "ChangeInCapacity"), @@ -90,9 +88,37 @@ func testAccCheckAWSAppautoscalingPolicyDestroy(s *terraform.State) error { func testAccAWSAppautoscalingPolicyConfig( randClusterName string, - randPolicyName string, - awsAccountId string) string { + randPolicyName string) string { return fmt.Sprintf(` +resource "aws_iam_role" "autoscale_role" { + name = "%s" + path = "/" + + assume_role_policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"*\"},\"Action\":[\"sts:AssumeRole\"]}]}" +} + +resource "aws_iam_role_policy" "autoscale_role_policy" { + name = "%s" + role = "${aws_iam_role.autoscale_role.id}" + + policy = <