与 AWS SDK或DeleteAutoScalingGroup一起使用 CLI - AWS SDK代码示例

AWS 文档 AWS SDK示例 GitHub 存储库中还有更多SDK示例

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

与 AWS SDK或DeleteAutoScalingGroup一起使用 CLI

以下代码示例演示如何使用 DeleteAutoScalingGroup

操作示例是大型程序的代码摘录,必须在上下文中运行。您可以在以下代码示例中查看此操作的上下文:

.NET
AWS SDK for .NET
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

将自动扩缩组的最小大小更新为零,终止该组中的所有实例,然后删除该组。

/// <summary> /// Try to terminate an instance by its Id. /// </summary> /// <param name="instanceId">The Id of the instance to terminate.</param> /// <returns>Async task.</returns> public async Task TryTerminateInstanceById(string instanceId) { var stopping = false; Console.WriteLine($"Stopping {instanceId}..."); while (!stopping) { try { await _amazonAutoScaling.TerminateInstanceInAutoScalingGroupAsync( new TerminateInstanceInAutoScalingGroupRequest() { InstanceId = instanceId, ShouldDecrementDesiredCapacity = false }); stopping = true; } catch (ScalingActivityInProgressException) { Console.WriteLine($"Scaling activity in progress for {instanceId}. Waiting..."); Thread.Sleep(10000); } } } /// <summary> /// Tries to delete the EC2 Auto Scaling group. If the group is in use or in progress, /// waits and retries until the group is successfully deleted. /// </summary> /// <param name="groupName">The name of the group to try to delete.</param> /// <returns>Async task.</returns> public async Task TryDeleteGroupByName(string groupName) { var stopped = false; while (!stopped) { try { await _amazonAutoScaling.DeleteAutoScalingGroupAsync( new DeleteAutoScalingGroupRequest() { AutoScalingGroupName = groupName }); stopped = true; } catch (Exception e) when ((e is ScalingActivityInProgressException) || (e is Amazon.AutoScaling.Model.ResourceInUseException)) { Console.WriteLine($"Some instances are still running. Waiting..."); Thread.Sleep(10000); } } } /// <summary> /// Terminate instances and delete the Auto Scaling group by name. /// </summary> /// <param name="groupName">The name of the group to delete.</param> /// <returns>Async task.</returns> public async Task TerminateAndDeleteAutoScalingGroupWithName(string groupName) { var describeGroupsResponse = await _amazonAutoScaling.DescribeAutoScalingGroupsAsync( new DescribeAutoScalingGroupsRequest() { AutoScalingGroupNames = new List<string>() { groupName } }); if (describeGroupsResponse.AutoScalingGroups.Any()) { // Update the size to 0. await _amazonAutoScaling.UpdateAutoScalingGroupAsync( new UpdateAutoScalingGroupRequest() { AutoScalingGroupName = groupName, MinSize = 0 }); var group = describeGroupsResponse.AutoScalingGroups[0]; foreach (var instance in group.Instances) { await TryTerminateInstanceById(instance.InstanceId); } await TryDeleteGroupByName(groupName); } else { Console.WriteLine($"No groups found with name {groupName}."); } }
/// <summary> /// Delete an Auto Scaling group. /// </summary> /// <param name="groupName">The name of the Amazon EC2 Auto Scaling group.</param> /// <returns>A Boolean value indicating the success of the action.</returns> public async Task<bool> DeleteAutoScalingGroupAsync( string groupName) { var deleteAutoScalingGroupRequest = new DeleteAutoScalingGroupRequest { AutoScalingGroupName = groupName, ForceDelete = true, }; var response = await _amazonAutoScaling.DeleteAutoScalingGroupAsync(deleteAutoScalingGroupRequest); if (response.HttpStatusCode == System.Net.HttpStatusCode.OK) { Console.WriteLine($"You successfully deleted {groupName}"); return true; } Console.WriteLine($"Couldn't delete {groupName}."); return false; }
C++
SDK对于 C++
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 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::DeleteAutoScalingGroupRequest request; request.SetAutoScalingGroupName(groupName); Aws::AutoScaling::Model::DeleteAutoScalingGroupOutcome outcome = autoScalingClient.DeleteAutoScalingGroup(request); if (outcome.IsSuccess()) { std::cout << "Auto Scaling group '" << groupName << "' was deleted." << std::endl; } else { std::cerr << "Error with AutoScaling::DeleteAutoScalingGroup. " << outcome.GetError().GetMessage() << std::endl; result = false; } }
CLI
AWS CLI

示例 1:删除指定的自动扩缩组

此示例将删除指定的自动扩缩组。

aws autoscaling delete-auto-scaling-group \ --auto-scaling-group-name my-asg

此命令不生成任何输出。

有关更多信息,请参阅 Amazon Auto Scaling 用户指南中的删除EC2自动扩展基础设施

示例 2:强制删除指定的自动扩缩组

要在不等待自动扩缩组中的实例终止的情况下删除该组,请使用 --force-delete 选项。

aws autoscaling delete-auto-scaling-group \ --auto-scaling-group-name my-asg \ --force-delete

此命令不生成任何输出。

有关更多信息,请参阅 Amazon Auto Scaling 用户指南中的删除EC2自动扩展基础设施

Java
SDK适用于 Java 2.x
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.autoscaling.AutoScalingClient; import software.amazon.awssdk.services.autoscaling.model.AutoScalingException; import software.amazon.awssdk.services.autoscaling.model.DeleteAutoScalingGroupRequest; /** * Before running this SDK for Java (v2) code example, set up your development * environment, including your credentials. * * For more information, see the following documentation: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class DeleteAutoScalingGroup { public static void main(String[] args) { final String usage = """ Usage: <groupName> Where: groupName - The name of the Auto Scaling group. """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String groupName = args[0]; AutoScalingClient autoScalingClient = AutoScalingClient.builder() .region(Region.US_EAST_1) .build(); deleteAutoScalingGroup(autoScalingClient, groupName); autoScalingClient.close(); } public static void deleteAutoScalingGroup(AutoScalingClient autoScalingClient, String groupName) { try { DeleteAutoScalingGroupRequest deleteAutoScalingGroupRequest = DeleteAutoScalingGroupRequest.builder() .autoScalingGroupName(groupName) .forceDelete(true) .build(); autoScalingClient.deleteAutoScalingGroup(deleteAutoScalingGroupRequest); System.out.println("You successfully deleted " + groupName); } catch (AutoScalingException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
Kotlin
SDK对于 Kotlin 来说
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

suspend fun deleteSpecificAutoScalingGroup(groupName: String) { val deleteAutoScalingGroupRequest = DeleteAutoScalingGroupRequest { autoScalingGroupName = groupName forceDelete = true } AutoScalingClient { region = "us-east-1" }.use { autoScalingClient -> autoScalingClient.deleteAutoScalingGroup(deleteAutoScalingGroupRequest) println("You successfully deleted $groupName") } }
PHP
SDK for PHP
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

public function deleteAutoScalingGroup($autoScalingGroupName) { return $this->autoScalingClient->deleteAutoScalingGroup([ 'AutoScalingGroupName' => $autoScalingGroupName, 'ForceDelete' => true, ]); }
PowerShell
用于 PowerShell

示例 1:如果指定的 Auto Scaling 组没有正在运行的实例,则此示例将其删除。在操作继续之前,系统会提示您进行确认。

Remove-ASAutoScalingGroup -AutoScalingGroupName my-asg

输出:

Confirm Are you sure you want to perform this action? Performing operation "Remove-ASAutoScalingGroup (DeleteAutoScalingGroup)" on Target "my-asg". [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"):

示例 2:如果您指定 Force 参数,则在操作继续之前不会提示您进行确认。

Remove-ASAutoScalingGroup -AutoScalingGroupName my-asg -Force

示例 3:此示例删除指定的 Auto Scaling 组并终止该组包含的所有正在运行的实例。

Remove-ASAutoScalingGroup -AutoScalingGroupName my-asg -ForceDelete $true -Force
Python
SDK适用于 Python (Boto3)
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

将自动扩缩组的最小大小更新为零,终止该组中的所有实例,然后删除该组。

class AutoScalingWrapper: """ Encapsulates Amazon EC2 Auto Scaling and EC2 management actions. """ def __init__( self, resource_prefix: str, inst_type: str, ami_param: str, autoscaling_client: boto3.client, ec2_client: boto3.client, ssm_client: boto3.client, iam_client: boto3.client, ): """ Initializes the AutoScaler class with the necessary parameters. :param resource_prefix: The prefix for naming AWS resources that are created by this class. :param inst_type: The type of EC2 instance to create, such as t3.micro. :param ami_param: The Systems Manager parameter used to look up the AMI that is created. :param autoscaling_client: A Boto3 EC2 Auto Scaling client. :param ec2_client: A Boto3 EC2 client. :param ssm_client: A Boto3 Systems Manager client. :param iam_client: A Boto3 IAM client. """ self.inst_type = inst_type self.ami_param = ami_param self.autoscaling_client = autoscaling_client self.ec2_client = ec2_client self.ssm_client = ssm_client self.iam_client = iam_client sts_client = boto3.client("sts") self.account_id = sts_client.get_caller_identity()["Account"] self.key_pair_name = f"{resource_prefix}-key-pair" self.launch_template_name = f"{resource_prefix}-template-" self.group_name = f"{resource_prefix}-group" # Happy path self.instance_policy_name = f"{resource_prefix}-pol" self.instance_role_name = f"{resource_prefix}-role" self.instance_profile_name = f"{resource_prefix}-prof" # Failure mode self.bad_creds_policy_name = f"{resource_prefix}-bc-pol" self.bad_creds_role_name = f"{resource_prefix}-bc-role" self.bad_creds_profile_name = f"{resource_prefix}-bc-prof" def delete_autoscaling_group(self, group_name: str) -> None: """ Terminates all instances in the group, then deletes the EC2 Auto Scaling group. :param group_name: The name of the group to delete. """ try: response = self.autoscaling_client.describe_auto_scaling_groups( AutoScalingGroupNames=[group_name] ) groups = response.get("AutoScalingGroups", []) if len(groups) > 0: self.autoscaling_client.update_auto_scaling_group( AutoScalingGroupName=group_name, MinSize=0 ) instance_ids = [inst["InstanceId"] for inst in groups[0]["Instances"]] for inst_id in instance_ids: self.terminate_instance(inst_id) # Wait for all instances to be terminated if instance_ids: waiter = self.ec2_client.get_waiter("instance_terminated") log.info("Waiting for all instances to be terminated...") waiter.wait(InstanceIds=instance_ids) log.info("All instances have been terminated.") else: log.info(f"No groups found named '{group_name}'! Nothing to do.") except ClientError as err: error_code = err.response["Error"]["Code"] log.error(f"Failed to delete Auto Scaling group '{group_name}'.") if error_code == "ScalingActivityInProgressFault": log.error( "Scaling activity is currently in progress. " "Wait for the scaling activity to complete before attempting to delete the group again." ) elif error_code == "ResourceContentionFault": log.error( "The request failed due to a resource contention issue. " "Ensure that no conflicting operations are being performed on the group." ) log.error(f"Full error:\n\t{err}")
Rust
SDK对于 Rust
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

async fn delete_group(client: &Client, name: &str, force: bool) -> Result<(), Error> { client .delete_auto_scaling_group() .auto_scaling_group_name(name) .set_force_delete(if force { Some(true) } else { None }) .send() .await?; println!("Deleted Auto Scaling group"); Ok(()) }