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 TerminateInstanceInAutoScalingGroup
com um AWS SDK ou CLI
Os exemplos de código a seguir mostram como usar o TerminateInstanceInAutoScalingGroup
.
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 em contexto nos seguintes exemplos 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> /// Terminate all instances in the Auto Scaling group in preparation for /// deleting the group. /// </summary> /// <param name="instanceId">The instance Id of the instance to terminate.</param> /// <returns>A Boolean value that indicates the success or failure of /// the operation.</returns> public async Task<bool> TerminateInstanceInAutoScalingGroupAsync( string instanceId) { var request = new TerminateInstanceInAutoScalingGroupRequest { InstanceId = instanceId, ShouldDecrementDesiredCapacity = false, }; var response = await _amazonAutoScaling.TerminateInstanceInAutoScalingGroupAsync(request); if (response.HttpStatusCode == System.Net.HttpStatusCode.OK) { Console.WriteLine($"You have terminated the instance: {instanceId}"); return true; } Console.WriteLine($"Could not terminate {instanceId}"); return false; }
-
Para API obter detalhes, consulte TerminateInstanceInAutoScalingGroupem AWS SDK for .NET APIReferência.
-
- 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::TerminateInstanceInAutoScalingGroupRequest request; request.SetInstanceId(instanceIDs[instanceNumber - 1]); request.SetShouldDecrementDesiredCapacity(false); Aws::AutoScaling::Model::TerminateInstanceInAutoScalingGroupOutcome outcome = autoScalingClient.TerminateInstanceInAutoScalingGroup(request); if (outcome.IsSuccess()) { std::cout << "Waiting for EC2 instance with ID '" << instanceIDs[instanceNumber - 1] << "' to terminate..." << std::endl; } else { std::cerr << "Error with AutoScaling::TerminateInstanceInAutoScalingGroup. " << outcome.GetError().GetMessage() << std::endl; }
-
Para API obter detalhes, consulte TerminateInstanceInAutoScalingGroupem AWS SDK for C++ APIReferência.
-
- CLI
-
- AWS CLI
-
Como encerrar uma instância em um grupo do Auto Scaling
Este exemplo encerra a instância especificada do grupo do Auto Scaling especificado sem atualizar o tamanho do grupo. O Amazon EC2 Auto Scaling inicia uma instância substituta após o término da instância especificada.
aws autoscaling terminate-instance-in-auto-scaling-group \ --instance-id
i-061c63c5eb45f0416
\ --no-should-decrement-desired-capacitySaída:
{ "Activities": [ { "ActivityId": "8c35d601-793c-400c-fcd0-f64a27530df7", "AutoScalingGroupName": "my-asg", "Description": "Terminating EC2 instance: i-061c63c5eb45f0416", "Cause": "", "StartTime": "2020-10-31T20:34:25.680Z", "StatusCode": "InProgress", "Progress": 0, "Details": "{\"Subnet ID\":\"subnet-6194ea3b\",\"Availability Zone\":\"us-west-2c\"}" } ] }
-
Para API obter detalhes, consulte TerminateInstanceInAutoScalingGroup
na Referência de AWS CLI Comandos.
-
- 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 terminateInstanceInAutoScalingGroup(AutoScalingClient autoScalingClient, String instanceId) { try { TerminateInstanceInAutoScalingGroupRequest request = TerminateInstanceInAutoScalingGroupRequest.builder() .instanceId(instanceId) .shouldDecrementDesiredCapacity(false) .build(); autoScalingClient.terminateInstanceInAutoScalingGroup(request); System.out.println("You have terminated instance " + instanceId); } catch (AutoScalingException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
-
Para API obter detalhes, consulte TerminateInstanceInAutoScalingGroupem AWS SDK for Java 2.x APIReferência.
-
- 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 terminateInstanceInAutoScalingGroup(instanceIdVal: String) { val request = TerminateInstanceInAutoScalingGroupRequest { instanceId = instanceIdVal shouldDecrementDesiredCapacity = false } AutoScalingClient { region = "us-east-1" }.use { autoScalingClient -> autoScalingClient.terminateInstanceInAutoScalingGroup(request) println("You have terminated instance $instanceIdVal") } }
-
Para API obter detalhes, consulte a TerminateInstanceInAutoScalingGroup
referência AWS SDKdo Kotlin API.
-
- 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 terminateInstanceInAutoScalingGroup( $instanceId, $shouldDecrementDesiredCapacity = true, $attempts = 0 ) { try { return $this->autoScalingClient->terminateInstanceInAutoScalingGroup([ 'InstanceId' => $instanceId, 'ShouldDecrementDesiredCapacity' => $shouldDecrementDesiredCapacity, ]); } catch (AutoScalingException $exception) { if ($exception->getAwsErrorCode() == "ScalingActivityInProgress" && $attempts < 5) { error_log("Cannot terminate an instance while it is still pending. Waiting then trying again."); sleep(5 * (1 + $attempts)); return $this->terminateInstanceInAutoScalingGroup( $instanceId, $shouldDecrementDesiredCapacity, ++$attempts ); } else { throw $exception; } } }
-
Para API obter detalhes, consulte TerminateInstanceInAutoScalingGroupem AWS SDK for PHP APIReferência.
-
- PowerShell
-
- Ferramentas para PowerShell
-
Exemplo 1: Esse exemplo encerra a instância especificada e diminui a capacidade desejada de seu grupo de Auto Scaling para que o Auto Scaling não execute uma instância substituta.
Stop-ASInstanceInAutoScalingGroup -InstanceId i-93633f9b -ShouldDecrementDesiredCapacity $true
Saída:
ActivityId : 2e40d9bd-1902-444c-abf3-6ea0002efdc5 AutoScalingGroupName : Cause : At 2015-11-22T16:09:03Z instance i-93633f9b was taken out of service in response to a user request, shrinking the capacity from 2 to 1. Description : Terminating EC2 instance: i-93633f9b Details : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"} EndTime : Progress : 0 StartTime : 11/22/2015 8:09:03 AM StatusCode : InProgress StatusMessage :
Exemplo 2: Esse exemplo encerra a instância especificada sem diminuir a capacidade desejada do grupo Auto Scaling. O Auto Scaling inicia uma instância substituta.
Stop-ASInstanceInAutoScalingGroup -InstanceId i-93633f9b -ShouldDecrementDesiredCapacity $false
Saída:
ActivityId : 2e40d9bd-1902-444c-abf3-6ea0002efdc5 AutoScalingGroupName : Cause : At 2015-11-22T16:09:03Z instance i-93633f9b was taken out of service in response to a user request. Description : Terminating EC2 instance: i-93633f9b Details : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"} EndTime : Progress : 0 StartTime : 11/22/2015 8:09:03 AM StatusCode : InProgress StatusMessage :
-
Para API obter detalhes, consulte TerminateInstanceInAutoScalingGroupem Referência de AWS Tools for PowerShell cmdlet.
-
- 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 terminate_instance( self, instance_id: str, decrease_capacity: bool ) -> Dict[str, Any]: """ Stops an instance. :param instance_id: The ID of the instance to stop. :param decrease_capacity: Specifies whether to decrease the desired capacity of the group. When passing True for this parameter, you can stop an instance without having a replacement instance start when the desired capacity threshold is crossed. :return: A dictionary containing details of the scaling activity that occurs in response to this action. :raises ClientError: If there is an error terminating the instance. """ try: response = self.autoscaling_client.terminate_instance_in_auto_scaling_group( InstanceId=instance_id, ShouldDecrementDesiredCapacity=decrease_capacity ) logger.info(f"Successfully terminated instance {instance_id}.") return response["Activity"] except ClientError as err: error_code = err.response["Error"]["Code"] logger.error(f"Failed to terminate instance {instance_id}.") if error_code == "ScalingActivityInProgress": logger.error( "A scaling activity is currently in progress for the Auto Scaling group " f"associated with instance '{instance_id}'. " "Please wait for the activity to complete before attempting to terminate the instance." ) elif error_code == "ResourceInUse": logger.error( f"The instance '{instance_id}' or an associated resource is currently in use " "and cannot be terminated. " "Ensure the instance is not involved in any ongoing processes and try again." ) logger.error(f"Full error:\n\t{err}") raise
-
Para API obter detalhes, consulte a TerminateInstanceInAutoScalingGroupReferência AWS SDK do Python (Boto3). API
-
- 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 terminate_some_instance(&self) -> Result<(), ScenarioError> { // Retrieve a list of instances in the auto scaling group. let auto_scaling_group = self.get_group().await?; let instances = auto_scaling_group.instances(); // Or use other logic to find an instance to terminate. let instance = instances.first(); if let Some(instance) = instance { let instance_id = if let Some(instance_id) = instance.instance_id() { instance_id } else { return Err(ScenarioError::with("Missing instance id")); }; let termination = self .ec2 .terminate_instances() .instance_ids(instance_id) .send() .await; if let Err(err) = termination { Err(ScenarioError::new( "There was a problem terminating an instance", &err, )) } else { Ok(()) } } else { Err(ScenarioError::with("There was no instance to terminate")) } } async fn get_group(&self) -> Result<AutoScalingGroup, ScenarioError> { let describe_auto_scaling_groups = self .autoscaling .describe_auto_scaling_groups() .auto_scaling_group_names(self.auto_scaling_group_name.clone()) .send() .await; if let Err(err) = describe_auto_scaling_groups { return Err(ScenarioError::new( format!( "Failed to get status of autoscaling group {}", self.auto_scaling_group_name.clone() ) .as_str(), &err, )); } let describe_auto_scaling_groups_output = describe_auto_scaling_groups.unwrap(); let auto_scaling_groups = describe_auto_scaling_groups_output.auto_scaling_groups(); let auto_scaling_group = auto_scaling_groups.first(); if auto_scaling_group.is_none() { return Err(ScenarioError::with(format!( "Could not find autoscaling group {}", self.auto_scaling_group_name.clone() ))); } Ok(auto_scaling_group.unwrap().clone()) }
-
Para API obter detalhes, consulte TerminateInstanceInAutoScalingGroup
a AWS SDKAPIreferência do Rust.
-