an AWS SDK 또는 CLIDeleteAutoScalingGroup와 함께 사용 - AWS SDK 코드 예제

AWS Doc SDK ExamplesWord AWS SDK 리포지토리에는 더 많은 GitHub 예제가 있습니다.

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

an AWS SDK 또는 CLIDeleteAutoScalingGroup와 함께 사용

다음 코드 예제는 DeleteAutoScalingGroup의 사용 방법을 보여 줍니다.

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.

.NET
AWS SDK for .NET
참고

더 많은 on GitHub가 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

Auto Scaling 그룹의 최소 크기를 0으로 업데이트하고 그룹의 모든 인스턴스를 해지한 다음 그룹을 삭제합니다.

/// <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++
C++ SDK
참고

더 많은 on 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: 지정된 Auto Scaling 그룹을 삭제하는 방법

이 예시에서는 지정된 Auto Scaling 그룹을 삭제합니다.

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

이 명령은 출력을 생성하지 않습니다.

자세한 내용은 Amazon Word Auto Scaling 사용 설명서의 Auto Scaling 인프라 삭제를 참조하세요. EC2 Auto Scaling

예 2: 지정된 Auto Scaling 그룹을 강제로 삭제하는 방법

그룹의 인스턴스가 종료될 때까지 기다리지 않고 Auto Scaling 그룹을 삭제하려면 --force-delete 옵션을 사용하세요.

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

이 명령은 출력을 생성하지 않습니다.

자세한 내용은 Amazon Word Auto Scaling 사용 설명서의 Auto Scaling 인프라 삭제를 참조하세요. EC2 Auto Scaling

Java
Java 2.x용 SDK
참고

더 많은 on 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
Kotlin용 SDK
참고

더 많은 on 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
PHP용 SDK
참고

더 많은 on GitHub가 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

public function deleteAutoScalingGroup($autoScalingGroupName) { return $this->autoScalingClient->deleteAutoScalingGroup([ 'AutoScalingGroupName' => $autoScalingGroupName, 'ForceDelete' => true, ]); }
PowerShell
for 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: 강제 파라미터를 지정하면 작업이 진행되기 전에 확인 메시지가 표시되지 않습니다.

Remove-ASAutoScalingGroup -AutoScalingGroupName my-asg -Force

예제 3: 이 예제에서는 지정된 Auto Scaling 그룹을 삭제하고 포함된 실행 중인 인스턴스를 모두 종료합니다.

Remove-ASAutoScalingGroup -AutoScalingGroupName my-asg -ForceDelete $true -Force
Python
Python용 SDK(Boto3)
참고

더 많은 on GitHub가 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

Auto Scaling 그룹의 최소 크기를 0으로 업데이트하고 그룹의 모든 인스턴스를 해지한 다음 그룹을 삭제합니다.

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}")
  • API 세부 정보는 Word for Python(Boto3) DeleteAutoScalingGroup 참조의 Word를 참조하세요. AWS SDK API

Rust
Rust용 SDK
참고

더 많은 on 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(()) }