Use DescribeScalingActivities 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 DescribeScalingActivities com um AWS SDK ou CLI

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

Exemplos de ações são trechos de código de programas maiores e devem ser executados em contexto. É possível ver essa ação no contexto no seguinte exemplo de código:

.NET
AWS SDK for .NET
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.

/// <summary> /// Retrieve a list of the Amazon EC2 Auto Scaling activities for an /// Amazon EC2 Auto Scaling group. /// </summary> /// <param name="groupName">The name of the Amazon EC2 Auto Scaling group.</param> /// <returns>A list of Amazon EC2 Auto Scaling activities.</returns> public async Task<List<Amazon.AutoScaling.Model.Activity>> DescribeScalingActivitiesAsync( string groupName) { var scalingActivitiesRequest = new DescribeScalingActivitiesRequest { AutoScalingGroupName = groupName, MaxRecords = 10, }; var response = await _amazonAutoScaling.DescribeScalingActivitiesAsync(scalingActivitiesRequest); return response.Activities; }
C++
SDKpara C++
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.

Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Aws::AutoScaling::AutoScalingClient autoScalingClient(clientConfig); Aws::AutoScaling::Model::DescribeScalingActivitiesRequest request; request.SetAutoScalingGroupName(groupName); Aws::Vector<Aws::AutoScaling::Model::Activity> allActivities; Aws::String nextToken; // Used for pagination; do { if (!nextToken.empty()) { request.SetNextToken(nextToken); } Aws::AutoScaling::Model::DescribeScalingActivitiesOutcome outcome = autoScalingClient.DescribeScalingActivities(request); if (outcome.IsSuccess()) { const Aws::Vector<Aws::AutoScaling::Model::Activity> &activities = outcome.GetResult().GetActivities(); allActivities.insert(allActivities.end(), activities.begin(), activities.end()); nextToken = outcome.GetResult().GetNextToken(); } else { std::cerr << "Error with AutoScaling::DescribeScalingActivities. " << outcome.GetError().GetMessage() << std::endl; } } while (!nextToken.empty()); std::cout << "Found " << allActivities.size() << " activities." << std::endl; std::cout << "Activities are ordered with the most recent first." << std::endl; for (const Aws::AutoScaling::Model::Activity &activity: allActivities) { std::cout << activity.GetDescription() << std::endl; std::cout << activity.GetDetails() << std::endl; }
CLI
AWS CLI

Exemplo 1: como descrever as ações de escalabilidade do grupo especificado

Este exemplo descreve as ações de escalabilidade do grupo do Auto Scaling especificado.

aws autoscaling describe-scaling-activities \ --auto-scaling-group-name my-asg

Saída:

{ "Activities": [ { "ActivityId": "f9f2d65b-f1f2-43e7-b46d-d86756459699", "Description": "Launching a new EC2 instance: i-0d44425630326060f", "AutoScalingGroupName": "my-asg", "Cause": "At 2020-10-30T19:35:51Z a user request update of AutoScalingGroup constraints to min: 0, max: 16, desired: 16 changing the desired capacity from 0 to 16. At 2020-10-30T19:36:07Z an instance was started in response to a difference between desired and actual capacity, increasing the capacity from 0 to 16.", "StartTime": "2020-10-30T19:36:09.766Z", "EndTime": "2020-10-30T19:36:41Z", "StatusCode": "Successful", "Progress": 100, "Details": "{\"Subnet ID\":\"subnet-5ea0c127\",\"Availability Zone\":\"us-west-2b\"}" } ] }

Para obter mais informações, consulte Verificar uma atividade de escalabilidade para um grupo de Auto Scaling no Guia do usuário do Amazon Auto EC2 Scaling.

Exemplo 2: como descrever as ações de escalabilidade de um grupo excluído

Adicione a opção --include-deleted-groups para descrever as ações de escalabilidade depois que o grupo do Auto Scaling for excluído.

aws autoscaling describe-scaling-activities \ --auto-scaling-group-name my-asg \ --include-deleted-groups

Saída:

{ "Activities": [ { "ActivityId": "e1f5de0e-f93e-1417-34ac-092a76fba220", "Description": "Launching a new EC2 instance. Status Reason: Your Spot request price of 0.001 is lower than the minimum required Spot request fulfillment price of 0.0031. Launching EC2 instance failed.", "AutoScalingGroupName": "my-asg", "Cause": "At 2021-01-13T20:47:24Z a user request update of AutoScalingGroup constraints to min: 1, max: 5, desired: 3 changing the desired capacity from 0 to 3. At 2021-01-13T20:47:27Z an instance was started in response to a difference between desired and actual capacity, increasing the capacity from 0 to 3.", "StartTime": "2021-01-13T20:47:30.094Z", "EndTime": "2021-01-13T20:47:30Z", "StatusCode": "Failed", "StatusMessage": "Your Spot request price of 0.001 is lower than the minimum required Spot request fulfillment price of 0.0031. Launching EC2 instance failed.", "Progress": 100, "Details": "{\"Subnet ID\":\"subnet-5ea0c127\",\"Availability Zone\":\"us-west-2b\"}", "AutoScalingGroupState": "Deleted", "AutoScalingGroupARN": "arn:aws:autoscaling:us-west-2:123456789012:autoScalingGroup:283179a2-f3ce-423d-93f6-66bb518232f7:autoScalingGroupName/my-asg" } ] }

Para obter mais informações, consulte Solucionar problemas do Amazon EC2 Auto Scaling no Guia do usuário do Amazon Auto EC2 Scaling.

Exemplo 3: como descrever um número especificado de ações de escalabilidade

Use a opção --max-items para retornar um número específico de ações.

aws autoscaling describe-scaling-activities \ --max-items 1

Saída:

{ "Activities": [ { "ActivityId": "f9f2d65b-f1f2-43e7-b46d-d86756459699", "Description": "Launching a new EC2 instance: i-0d44425630326060f", "AutoScalingGroupName": "my-asg", "Cause": "At 2020-10-30T19:35:51Z a user request update of AutoScalingGroup constraints to min: 0, max: 16, desired: 16 changing the desired capacity from 0 to 16. At 2020-10-30T19:36:07Z an instance was started in response to a difference between desired and actual capacity, increasing the capacity from 0 to 16.", "StartTime": "2020-10-30T19:36:09.766Z", "EndTime": "2020-10-30T19:36:41Z", "StatusCode": "Successful", "Progress": 100, "Details": "{\"Subnet ID\":\"subnet-5ea0c127\",\"Availability Zone\":\"us-west-2b\"}" } ] }

Se a saída incluir um campo NextToken, há mais ações. Para obter as ações adicionais, use o valor desse campo com a opção --starting-token em uma chamada subsequente da seguinte maneira.

aws autoscaling describe-scaling-activities \ --starting-token Z3M3LMPEXAMPLE

Para obter mais informações, consulte Verificar uma atividade de escalabilidade para um grupo de Auto Scaling no Guia do usuário do Amazon Auto EC2 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.

public static void describeScalingActivities(AutoScalingClient autoScalingClient, String groupName) { try { DescribeScalingActivitiesRequest scalingActivitiesRequest = DescribeScalingActivitiesRequest.builder() .autoScalingGroupName(groupName) .maxRecords(10) .build(); DescribeScalingActivitiesResponse response = autoScalingClient .describeScalingActivities(scalingActivitiesRequest); List<Activity> activities = response.activities(); for (Activity activity : activities) { System.out.println("The activity Id is " + activity.activityId()); System.out.println("The activity details are " + activity.details()); } } catch (AutoScalingException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
Kotlin
SDKpara Kotlin
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.

suspend fun describeAutoScalingGroups(groupName: String) { val groupsReques = DescribeAutoScalingGroupsRequest { autoScalingGroupNames = listOf(groupName) maxRecords = 10 } AutoScalingClient { region = "us-east-1" }.use { autoScalingClient -> val response = autoScalingClient.describeAutoScalingGroups(groupsReques) response.autoScalingGroups?.forEach { group -> println("The service to use for the health checks: ${group.healthCheckType}") } } }
PHP
SDK para PHP
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.

public function describeScalingActivities($autoScalingGroupName) { return $this->autoScalingClient->describeScalingActivities([ 'AutoScalingGroupName' => $autoScalingGroupName, ]); }
PowerShell
Ferramentas para PowerShell

Exemplo 1: Este exemplo descreve as atividades de escalonamento das últimas seis semanas para o grupo de Auto Scaling especificado.

Get-ASScalingActivity -AutoScalingGroupName my-asg

Saída:

ActivityId : 063308ae-aa22-4a9b-94f4-9fae4EXAMPLE AutoScalingGroupName : my-asg Cause : At 2015-11-22T15:45:16Z a user request explicitly set group desired capacity changing the desired capacity from 1 to 2. At 2015-11-22T15:45:34Z an instance was started in response to a difference between desired and actual capacity, increasing the capacity from 1 to 2. Description : Launching a new EC2 instance: i-26e715fc Details : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"} EndTime : 11/22/2015 7:46:09 AM Progress : 100 StartTime : 11/22/2015 7:45:35 AM StatusCode : Successful StatusMessage : ActivityId : ce719997-086d-4c73-a2f1-ab703EXAMPLE AutoScalingGroupName : my-asg Cause : At 2015-11-20T22:57:53Z a user request created an AutoScalingGroup changing the desired capacity from 0 to 1. At 2015-11-20T22:57:58Z an instance was started in response to a difference betwe en desired and actual capacity, increasing the capacity from 0 to 1. Description : Launching a new EC2 instance: i-93633f9b Details : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"} EndTime : 11/20/2015 2:58:32 PM Progress : 100 StartTime : 11/20/2015 2:57:59 PM StatusCode : Successful StatusMessage :

Exemplo 2: Este exemplo descreve a atividade de escalabilidade especificada.

Get-ASScalingActivity -ActivityId "063308ae-aa22-4a9b-94f4-9fae4EXAMPLE"

Exemplo 3: Este exemplo descreve as atividades de escalonamento das últimas seis semanas para todos os seus grupos de Auto Scaling.

Get-ASScalingActivity
Python
SDKpara Python (Boto3)
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.

class AutoScalingWrapper: """Encapsulates Amazon EC2 Auto Scaling actions.""" def __init__(self, autoscaling_client): """ :param autoscaling_client: A Boto3 Amazon EC2 Auto Scaling client. """ self.autoscaling_client = autoscaling_client def describe_scaling_activities(self, group_name: str) -> List[Dict[str, Any]]: """ Gets information about scaling activities for the group. Scaling activities are things like instances stopping or starting in response to user requests or capacity changes. :param group_name: The name of the group to look up. :return: A list of dictionaries representing the scaling activities for the group, ordered with the most recent activity first. :raises ClientError: If there is an error describing the scaling activities. """ try: paginator = self.autoscaling_client.get_paginator( "describe_scaling_activities" ) response_iterator = paginator.paginate(AutoScalingGroupName=group_name) activities = [] for response in response_iterator: activities.extend(response.get("Activities", [])) logger.info( f"Successfully described scaling activities for group '{group_name}'." ) except ClientError as err: error_code = err.response["Error"]["Code"] logger.error( f"Couldn't describe scaling activities for group '{group_name}'. Error code: {error_code}, Message: {err.response['Error']['Message']}" ) if error_code == "ResourceContentionFault": logger.error( f"There is a conflict with another operation that is modifying the Auto Scaling group '{group_name}'. " "Please try again later." ) raise else: return activities
Rust
SDKpara Rust
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.

pub async fn describe_scenario(&self) -> AutoScalingScenarioDescription { let group = self .autoscaling .describe_auto_scaling_groups() .auto_scaling_group_names(self.auto_scaling_group_name.clone()) .send() .await .map(|s| { s.auto_scaling_groups() .iter() .map(|s| { format!( "{}: {}", s.auto_scaling_group_name().unwrap_or("Unknown"), s.status().unwrap_or("Unknown") ) }) .collect::<Vec<String>>() }) .map_err(|e| { ScenarioError::new("Failed to describe auto scaling groups for scenario", &e) }); let instances = self .list_instances() .await .map_err(|e| anyhow!("There was an error listing instances: {e}",)); // 10. DescribeScalingActivities: list the scaling activities that have occurred for the group so far. // Bonus: use CloudWatch API to get and show some metrics collected for the group. // CW.ListMetrics with Namespace='AWS/AutoScaling' and Dimensions=[{'Name': 'AutoScalingGroupName', 'Value': }] // CW.GetMetricStatistics with Statistics='Sum'. Start and End times must be in UTC! let activities = self .autoscaling .describe_scaling_activities() .auto_scaling_group_name(self.auto_scaling_group_name.clone()) .into_paginator() .items() .send() .collect::<Result<Vec<_>, _>>() .await .map_err(|e| { anyhow!( "There was an error retrieving scaling activities: {}", DisplayErrorContext(&e) ) }); AutoScalingScenarioDescription { group, instances, activities, } }