Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.
Gunakan TerminateInstanceInAutoScalingGroup
dengan AWS SDK atau CLI
Contoh kode berikut menunjukkan cara menggunakanTerminateInstanceInAutoScalingGroup
.
Contoh tindakan adalah kutipan kode dari program yang lebih besar dan harus dijalankan dalam konteks. Anda dapat melihat tindakan ini dalam konteks dalam contoh kode berikut:
- .NET
-
- AWS SDK for .NET
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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; }
-
Untuk detail API, lihat TerminateInstanceInAutoScalingGroupdi Referensi AWS SDK for .NET API.
-
- C++
-
- SDK untuk C++
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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; }
-
Untuk detail API, lihat TerminateInstanceInAutoScalingGroupdi Referensi AWS SDK for C++ API.
-
- CLI
-
- AWS CLI
-
Untuk mengakhiri instance dalam grup Auto Scaling
Contoh ini mengakhiri instance yang ditentukan dari grup Auto Scaling yang ditentukan tanpa memperbarui ukuran grup. Amazon EC2 Auto Scaling meluncurkan instance pengganti setelah instance yang ditentukan dihentikan.
aws autoscaling terminate-instance-in-auto-scaling-group \ --instance-id
i-061c63c5eb45f0416
\ --no-should-decrement-desired-capacityOutput:
{ "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\"}" } ] }
-
Untuk detail API, lihat TerminateInstanceInAutoScalingGroup
di Referensi AWS CLI Perintah.
-
- Java
-
- SDK untuk Java 2.x
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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); } }
-
Untuk detail API, lihat TerminateInstanceInAutoScalingGroupdi Referensi AWS SDK for Java 2.x API.
-
- Kotlin
-
- SDK untuk Kotlin
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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") } }
-
Untuk detail API, lihat TerminateInstanceInAutoScalingGroup
di AWS SDK untuk referensi API Kotlin.
-
- PHP
-
- SDK untuk PHP
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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; } } }
-
Untuk detail API, lihat TerminateInstanceInAutoScalingGroupdi Referensi AWS SDK for PHP API.
-
- PowerShell
-
- Alat untuk PowerShell
-
Contoh 1: Contoh ini mengakhiri instance yang ditentukan dan mengurangi kapasitas yang diinginkan dari grup Auto Scaling sehingga Auto Scaling tidak meluncurkan instance pengganti.
Stop-ASInstanceInAutoScalingGroup -InstanceId i-93633f9b -ShouldDecrementDesiredCapacity $true
Output:
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 :
Contoh 2: Contoh ini mengakhiri instance yang ditentukan tanpa mengurangi kapasitas yang diinginkan dari grup Auto Scaling. Auto Scaling meluncurkan instance pengganti.
Stop-ASInstanceInAutoScalingGroup -InstanceId i-93633f9b -ShouldDecrementDesiredCapacity $false
Output:
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 :
-
Untuk detail API, lihat TerminateInstanceInAutoScalingGroupdi Referensi AWS Tools for PowerShell Cmdlet.
-
- Python
-
- SDK untuk Python (Boto3)
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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
-
Untuk detail API, lihat TerminateInstanceInAutoScalingGroupdi AWS SDK for Python (Boto3) Referensi API.
-
- Rust
-
- SDK untuk Rust
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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()) }
-
Untuk detail API, lihat TerminateInstanceInAutoScalingGroup
referensi AWS SDK for Rust API.
-
Untuk daftar lengkap panduan pengembang AWS SDK dan contoh kode, lihatMenggunakan layanan ini dengan AWS SDK. Topik ini juga mencakup informasi tentang memulai dan detail tentang versi SDK sebelumnya.