Use RegisterScalableTarget com um AWS SDK ou CLI - AWS SDKExemplos de código

Há mais AWS SDK exemplos disponíveis no GitHub repositório AWS Doc SDK Examples.

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

Use RegisterScalableTarget com um AWS SDK ou CLI

Os exemplos de código a seguir mostram como usar o RegisterScalableTarget.

CLI
AWS CLI

Exemplo 1: Para registrar um ECS serviço como um alvo escalável

O register-scalable-target exemplo a seguir registra um ECS serviço da Amazon com o Application Auto Scaling. Ele também adiciona uma tag com o nome da chave environment e o valor production ao alvo escalável.

aws application-autoscaling register-scalable-target \ --service-namespace ecs \ --scalable-dimension ecs:service:DesiredCount \ --resource-id service/default/web-app \ --min-capacity 1 --max-capacity 10 \ --tags environment=production

Saída:

{ "ScalableTargetARN": "arn:aws:application-autoscaling:us-west-2:123456789012:scalable-target/1234abcd56ab78cd901ef1234567890ab123" }

Para obter exemplos de outros AWS serviços e recursos personalizados, consulte os tópicos em AWS serviços que você pode usar com o Application Auto Scaling no Guia do Usuário do Application Auto Scaling.

Exemplo 2: Para suspender as atividades de escalabilidade para um alvo escalável

O register-scalable-target exemplo a seguir suspende as atividades de escalabilidade de um alvo escalável existente.

aws application-autoscaling register-scalable-target \ --service-namespace dynamodb \ --scalable-dimension dynamodb:table:ReadCapacityUnits \ --resource-id table/my-table \ --suspended-state DynamicScalingInSuspended=true,DynamicScalingOutSuspended=true,ScheduledScalingSuspended=true

Saída:

{ "ScalableTargetARN": "arn:aws:application-autoscaling:us-west-2:123456789012:scalable-target/1234abcd56ab78cd901ef1234567890ab123" }

Para obter mais informações, consulte Suspender e retomar o escalonamento do Application Auto Scaling no Guia do usuário do Application Auto Scaling.

Exemplo 3: Para retomar as atividades de escalabilidade para uma meta escalável

O register-scalable-target exemplo a seguir retoma as atividades de escalabilidade para uma meta escalável existente.

aws application-autoscaling register-scalable-target \ --service-namespace dynamodb \ --scalable-dimension dynamodb:table:ReadCapacityUnits \ --resource-id table/my-table \ --suspended-state DynamicScalingInSuspended=false,DynamicScalingOutSuspended=false,ScheduledScalingSuspended=false

Saída:

{ "ScalableTargetARN": "arn:aws:application-autoscaling:us-west-2:123456789012:scalable-target/1234abcd56ab78cd901ef1234567890ab123" }

Para obter mais informações, consulte Suspender e retomar o escalonamento do Application Auto Scaling no Guia do usuário do Application Auto Scaling.

Java
SDKpara Java 2.x
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.applicationautoscaling.ApplicationAutoScalingClient; import software.amazon.awssdk.services.applicationautoscaling.model.ApplicationAutoScalingException; import software.amazon.awssdk.services.applicationautoscaling.model.DescribeScalableTargetsRequest; import software.amazon.awssdk.services.applicationautoscaling.model.DescribeScalableTargetsResponse; import software.amazon.awssdk.services.applicationautoscaling.model.DescribeScalingPoliciesRequest; import software.amazon.awssdk.services.applicationautoscaling.model.DescribeScalingPoliciesResponse; import software.amazon.awssdk.services.applicationautoscaling.model.PolicyType; import software.amazon.awssdk.services.applicationautoscaling.model.PredefinedMetricSpecification; import software.amazon.awssdk.services.applicationautoscaling.model.PutScalingPolicyRequest; import software.amazon.awssdk.services.applicationautoscaling.model.RegisterScalableTargetRequest; import software.amazon.awssdk.services.applicationautoscaling.model.ScalingPolicy; import software.amazon.awssdk.services.applicationautoscaling.model.ServiceNamespace; import software.amazon.awssdk.services.applicationautoscaling.model.ScalableDimension; import software.amazon.awssdk.services.applicationautoscaling.model.MetricType; import software.amazon.awssdk.services.applicationautoscaling.model.TargetTrackingScalingPolicyConfiguration; import java.util.List; /** * Before running this Java V2 code example, set up your development environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class EnableDynamoDBAutoscaling { public static void main(String[] args) { final String usage = """ Usage: <tableId> <roleARN> <policyName>\s Where: tableId - The table Id value (for example, table/Music). roleARN - The ARN of the role that has ApplicationAutoScaling permissions. policyName - The name of the policy to create. """; if (args.length != 3) { System.out.println(usage); System.exit(1); } System.out.println("This example registers an Amazon DynamoDB table, which is the resource to scale."); String tableId = args[0]; String roleARN = args[1]; String policyName = args[2]; ServiceNamespace ns = ServiceNamespace.DYNAMODB; ScalableDimension tableWCUs = ScalableDimension.DYNAMODB_TABLE_WRITE_CAPACITY_UNITS; ApplicationAutoScalingClient appAutoScalingClient = ApplicationAutoScalingClient.builder() .region(Region.US_EAST_1) .build(); registerScalableTarget(appAutoScalingClient, tableId, roleARN, ns, tableWCUs); verifyTarget(appAutoScalingClient, tableId, ns, tableWCUs); configureScalingPolicy(appAutoScalingClient, tableId, ns, tableWCUs, policyName); } public static void registerScalableTarget(ApplicationAutoScalingClient appAutoScalingClient, String tableId, String roleARN, ServiceNamespace ns, ScalableDimension tableWCUs) { try { RegisterScalableTargetRequest targetRequest = RegisterScalableTargetRequest.builder() .serviceNamespace(ns) .scalableDimension(tableWCUs) .resourceId(tableId) .roleARN(roleARN) .minCapacity(5) .maxCapacity(10) .build(); appAutoScalingClient.registerScalableTarget(targetRequest); System.out.println("You have registered " + tableId); } catch (ApplicationAutoScalingException e) { System.err.println(e.awsErrorDetails().errorMessage()); } } // Verify that the target was created. public static void verifyTarget(ApplicationAutoScalingClient appAutoScalingClient, String tableId, ServiceNamespace ns, ScalableDimension tableWCUs) { DescribeScalableTargetsRequest dscRequest = DescribeScalableTargetsRequest.builder() .scalableDimension(tableWCUs) .serviceNamespace(ns) .resourceIds(tableId) .build(); DescribeScalableTargetsResponse response = appAutoScalingClient.describeScalableTargets(dscRequest); System.out.println("DescribeScalableTargets result: "); System.out.println(response); } // Configure a scaling policy. public static void configureScalingPolicy(ApplicationAutoScalingClient appAutoScalingClient, String tableId, ServiceNamespace ns, ScalableDimension tableWCUs, String policyName) { // Check if the policy exists before creating a new one. DescribeScalingPoliciesResponse describeScalingPoliciesResponse = appAutoScalingClient.describeScalingPolicies(DescribeScalingPoliciesRequest.builder() .serviceNamespace(ns) .resourceId(tableId) .scalableDimension(tableWCUs) .build()); if (!describeScalingPoliciesResponse.scalingPolicies().isEmpty()) { // If policies exist, consider updating an existing policy instead of creating a new one. System.out.println("Policy already exists. Consider updating it instead."); List<ScalingPolicy> polList = describeScalingPoliciesResponse.scalingPolicies(); for (ScalingPolicy pol : polList) { System.out.println("Policy name:" +pol.policyName()); } } else { // If no policies exist, proceed with creating a new policy. PredefinedMetricSpecification specification = PredefinedMetricSpecification.builder() .predefinedMetricType(MetricType.DYNAMO_DB_WRITE_CAPACITY_UTILIZATION) .build(); TargetTrackingScalingPolicyConfiguration policyConfiguration = TargetTrackingScalingPolicyConfiguration.builder() .predefinedMetricSpecification(specification) .targetValue(50.0) .scaleInCooldown(60) .scaleOutCooldown(60) .build(); PutScalingPolicyRequest putScalingPolicyRequest = PutScalingPolicyRequest.builder() .targetTrackingScalingPolicyConfiguration(policyConfiguration) .serviceNamespace(ns) .scalableDimension(tableWCUs) .resourceId(tableId) .policyName(policyName) .policyType(PolicyType.TARGET_TRACKING_SCALING) .build(); try { appAutoScalingClient.putScalingPolicy(putScalingPolicyRequest); System.out.println("You have successfully created a scaling policy for an Application Auto Scaling scalable target"); } catch (ApplicationAutoScalingException e) { System.err.println("Error: " + e.awsErrorDetails().errorMessage()); } } } }
PowerShell
Ferramentas para PowerShell

Exemplo 1: Esse cmdlet registra ou atualiza um destino escalável. Uma meta escalável é um recurso que o Application Auto Scaling pode escalar para fora e para dentro.

Add-AASScalableTarget -ServiceNamespace AppStream -ResourceId fleet/MyFleet -ScalableDimension appstream:fleet:DesiredCapacity -MinCapacity 2 -MaxCapacity 10