Examples for creating and managing Auto Scaling groups with the Amazon SDKs
You can create an Auto Scaling group using the Amazon Web Services Management Console, the Amazon CLI, an Amazon SDK, and Amazon CloudFormation.
The following code examples show how to create, update, describe, and delete an Auto Scaling group in your favorite supported programming language using the Amazon SDKs.
Contents
Create an Auto Scaling group using an Amazon SDK
The following code examples show how to create an Auto Scaling group.
- .NET
-
- Amazon SDK for .NET
-
Note
There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository
. /// <summary> /// Create a new Amazon EC2 Auto Scaling group. /// </summary> /// <param name="groupName">The name to use for the new Auto Scaling /// group.</param> /// <param name="launchTemplateName">The name of the Amazon EC2 Auto Scaling /// launch template to use to create instances in the group.</param> /// <returns>A Boolean value indicating the success of the action.</returns> public async Task<bool> CreateAutoScalingGroupAsync( string groupName, string launchTemplateName, string availabilityZone) { var templateSpecification = new LaunchTemplateSpecification { LaunchTemplateName = launchTemplateName, }; var zoneList = new List<string> { availabilityZone, }; var request = new CreateAutoScalingGroupRequest { AutoScalingGroupName = groupName, AvailabilityZones = zoneList, LaunchTemplate = templateSpecification, MaxSize = 6, MinSize = 1 }; var response = await _amazonAutoScaling.CreateAutoScalingGroupAsync(request); Console.WriteLine($"{groupName} Auto Scaling Group created"); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; }
-
For API details, see CreateAutoScalingGroup in Amazon SDK for .NET API Reference.
-
- C++
-
- SDK for C++
-
Note
There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository
. 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::CreateAutoScalingGroupRequest request; request.SetAutoScalingGroupName(groupName); Aws::Vector<Aws::String> availabilityGroupZones; availabilityGroupZones.push_back( availabilityZones[availabilityZoneChoice - 1].GetZoneName()); request.SetAvailabilityZones(availabilityGroupZones); request.SetMaxSize(1); request.SetMinSize(1); Aws::AutoScaling::Model::LaunchTemplateSpecification launchTemplateSpecification; launchTemplateSpecification.SetLaunchTemplateName(templateName); request.SetLaunchTemplate(launchTemplateSpecification); Aws::AutoScaling::Model::CreateAutoScalingGroupOutcome outcome = autoScalingClient.CreateAutoScalingGroup(request); if (outcome.IsSuccess()) { std::cout << "Created Auto Scaling group '" << groupName << "'..." << std::endl; } else if (outcome.GetError().GetErrorType() == Aws::AutoScaling::AutoScalingErrors::ALREADY_EXISTS_FAULT) { std::cout << "Auto Scaling group '" << groupName << "' already exists." << std::endl; } else { std::cerr << "Error with AutoScaling::CreateAutoScalingGroup. " << outcome.GetError().GetMessage() << std::endl; }
-
For API details, see CreateAutoScalingGroup in Amazon SDK for C++ API Reference.
-
- Java
-
- SDK for Java 2.x
-
Note
There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository
. public static void createAutoScalingGroup(AutoScalingClient autoScalingClient, String groupName, String launchTemplateName, String vpcZoneId) { try { AutoScalingWaiter waiter = autoScalingClient.waiter(); LaunchTemplateSpecification templateSpecification = LaunchTemplateSpecification.builder() .launchTemplateName(launchTemplateName) .build(); CreateAutoScalingGroupRequest request = CreateAutoScalingGroupRequest.builder() .autoScalingGroupName(groupName) .availabilityZones("us-east-1a") .launchTemplate(templateSpecification) .maxSize(1) .minSize(1) .vpcZoneIdentifier(vpcZoneId) .build(); autoScalingClient.createAutoScalingGroup(request); DescribeAutoScalingGroupsRequest groupsRequest = DescribeAutoScalingGroupsRequest.builder() .autoScalingGroupNames(groupName) .build(); WaiterResponse<DescribeAutoScalingGroupsResponse> waiterResponse = waiter.waitUntilGroupExists(groupsRequest); waiterResponse.matched().response().ifPresent(System.out::println); System.out.println("Auto Scaling Group created"); } catch (AutoScalingException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
-
For API details, see CreateAutoScalingGroup in Amazon SDK for Java 2.x API Reference.
-
- Kotlin
-
- SDK for Kotlin
-
Note
There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository
. suspend fun createAutoScalingGroup(groupName: String, launchTemplateNameVal: String, serviceLinkedRoleARNVal: String, vpcZoneIdVal: String) { val templateSpecification = LaunchTemplateSpecification { launchTemplateName = launchTemplateNameVal } val request = CreateAutoScalingGroupRequest { autoScalingGroupName = groupName availabilityZones = listOf("us-east-1a") launchTemplate = templateSpecification maxSize = 1 minSize = 1 vpcZoneIdentifier = vpcZoneIdVal serviceLinkedRoleArn = serviceLinkedRoleARNVal } // This object is required for the waiter call. val groupsRequestWaiter = DescribeAutoScalingGroupsRequest { autoScalingGroupNames = listOf(groupName) } AutoScalingClient { region = "us-east-1" }.use { autoScalingClient -> autoScalingClient.createAutoScalingGroup(request) autoScalingClient.waitUntilGroupExists(groupsRequestWaiter) println("$groupName was created!") } }
-
For API details, see CreateAutoScalingGroup
in Amazon SDK for Kotlin API reference.
-
- PHP
-
- SDK for PHP
-
Note
There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository
. public function createAutoScalingGroup( $autoScalingGroupName, $availabilityZones, $minSize, $maxSize, $launchTemplateId ) { return $this->autoScalingClient->createAutoScalingGroup([ 'AutoScalingGroupName' => $autoScalingGroupName, 'AvailabilityZones' => $availabilityZones, 'MinSize' => $minSize, 'MaxSize' => $maxSize, 'LaunchTemplate' => [ 'LaunchTemplateId' => $launchTemplateId, ], ]); }
-
For API details, see CreateAutoScalingGroup in Amazon SDK for PHP API Reference.
-
- Python
-
- SDK for Python (Boto3)
-
Note
There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository
. 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 create_group( self, group_name, group_zones, launch_template_name, min_size, max_size ): """ Creates an Auto Scaling group. :param group_name: The name to give to the group. :param group_zones: The Availability Zones in which instances can be created. :param launch_template_name: The name of an existing Amazon EC2 launch template. The launch template specifies the configuration of instances that are created by auto scaling activities. :param min_size: The minimum number of active instances in the group. :param max_size: The maximum number of active instances in the group. """ try: self.autoscaling_client.create_auto_scaling_group( AutoScalingGroupName=group_name, AvailabilityZones=group_zones, LaunchTemplate={ "LaunchTemplateName": launch_template_name, "Version": "$Default", }, MinSize=min_size, MaxSize=max_size, ) except ClientError as err: logger.error( "Couldn't create group %s. Here's why: %s: %s", group_name, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise
-
For API details, see CreateAutoScalingGroup in Amazon SDK for Python (Boto3) API Reference.
-
- Rust
-
- SDK for Rust
-
Note
There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository
. async fn create_group(client: &Client, name: &str, id: &str) -> Result<(), Error> { client .create_auto_scaling_group() .auto_scaling_group_name(name) .instance_id(id) .min_size(1) .max_size(5) .send() .await?; println!("Created AutoScaling group"); Ok(()) }
-
For API details, see CreateAutoScalingGroup
in Amazon SDK for Rust API reference.
-
For examples you can use when creating mixed instances groups, see the following resources.
Update an Auto Scaling group using an Amazon SDK
The following code examples show how to update the configuration for an Auto Scaling group.
- .NET
-
- Amazon SDK for .NET
-
Note
There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository
. /// <summary> /// Update the capacity of an Auto Scaling group. /// </summary> /// <param name="groupName">The name of the Auto Scaling group.</param> /// <param name="launchTemplateName">The name of the EC2 launch template.</param> /// <param name="maxSize">The maximum number of instances that can be /// created for the Auto Scaling group.</param> /// <returns>A Boolean value indicating the success of the action.</returns> public async Task<bool> UpdateAutoScalingGroupAsync( string groupName, string launchTemplateName, int maxSize) { var templateSpecification = new LaunchTemplateSpecification { LaunchTemplateName = launchTemplateName, }; var groupRequest = new UpdateAutoScalingGroupRequest { MaxSize = maxSize, AutoScalingGroupName = groupName, LaunchTemplate = templateSpecification, }; var response = await _amazonAutoScaling.UpdateAutoScalingGroupAsync(groupRequest); if (response.HttpStatusCode == System.Net.HttpStatusCode.OK) { Console.WriteLine($"You successfully updated the Auto Scaling group {groupName}."); return true; } else { return false; } }
-
For API details, see UpdateAutoScalingGroup in Amazon SDK for .NET API Reference.
-
- C++
-
- SDK for C++
-
Note
There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository
. 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::UpdateAutoScalingGroupRequest request; request.SetAutoScalingGroupName(groupName); request.SetMaxSize(3); Aws::AutoScaling::Model::UpdateAutoScalingGroupOutcome outcome = autoScalingClient.UpdateAutoScalingGroup(request); if (!outcome.IsSuccess()) { std::cerr << "Error with AutoScaling::UpdateAutoScalingGroup. " << outcome.GetError().GetMessage() << std::endl; }
-
For API details, see UpdateAutoScalingGroup in Amazon SDK for C++ API Reference.
-
- Java
-
- SDK for Java 2.x
-
Note
There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository
. public static void updateAutoScalingGroup(AutoScalingClient autoScalingClient, String groupName, String launchTemplateName) { try { AutoScalingWaiter waiter = autoScalingClient.waiter(); LaunchTemplateSpecification templateSpecification = LaunchTemplateSpecification.builder() .launchTemplateName(launchTemplateName) .build(); UpdateAutoScalingGroupRequest groupRequest = UpdateAutoScalingGroupRequest.builder() .maxSize(3) .autoScalingGroupName(groupName) .launchTemplate(templateSpecification) .build(); autoScalingClient.updateAutoScalingGroup(groupRequest); DescribeAutoScalingGroupsRequest groupsRequest = DescribeAutoScalingGroupsRequest.builder() .autoScalingGroupNames(groupName) .build(); WaiterResponse<DescribeAutoScalingGroupsResponse> waiterResponse = waiter.waitUntilGroupInService(groupsRequest); waiterResponse.matched().response().ifPresent(System.out::println); System.out.println("You successfully updated the auto scaling group "+groupName); } catch (AutoScalingException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
-
For API details, see UpdateAutoScalingGroup in Amazon SDK for Java 2.x API Reference.
-
- Kotlin
-
- SDK for Kotlin
-
Note
There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository
. suspend fun updateAutoScalingGroup(groupName: String, launchTemplateNameVal: String, serviceLinkedRoleARNVal: String) { val templateSpecification = LaunchTemplateSpecification { launchTemplateName = launchTemplateNameVal } val groupRequest = UpdateAutoScalingGroupRequest { maxSize = 3 serviceLinkedRoleArn = serviceLinkedRoleARNVal autoScalingGroupName = groupName launchTemplate = templateSpecification } val groupsRequestWaiter = DescribeAutoScalingGroupsRequest { autoScalingGroupNames = listOf(groupName) } AutoScalingClient { region = "us-east-1" }.use { autoScalingClient -> autoScalingClient.updateAutoScalingGroup(groupRequest) autoScalingClient.waitUntilGroupExists(groupsRequestWaiter) println("You successfully updated the Auto Scaling group $groupName") } }
-
For API details, see UpdateAutoScalingGroup
in Amazon SDK for Kotlin API reference.
-
- PHP
-
- SDK for PHP
-
Note
There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository
. public function updateAutoScalingGroup($autoScalingGroupName, $args) { if (array_key_exists('MaxSize', $args)) { $maxSize = ['MaxSize' => $args['MaxSize']]; } else { $maxSize = []; } if (array_key_exists('MinSize', $args)) { $minSize = ['MinSize' => $args['MinSize']]; } else { $minSize = []; } $parameters = ['AutoScalingGroupName' => $autoScalingGroupName]; $parameters = array_merge($parameters, $minSize, $maxSize); return $this->autoScalingClient->updateAutoScalingGroup($parameters); }
-
For API details, see UpdateAutoScalingGroup in Amazon SDK for PHP API Reference.
-
- Python
-
- SDK for Python (Boto3)
-
Note
There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository
. 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 update_group(self, group_name, **kwargs): """ Updates an Auto Scaling group. :param group_name: The name of the group to update. :param kwargs: Keyword arguments to pass through to the service. """ try: self.autoscaling_client.update_auto_scaling_group( AutoScalingGroupName=group_name, **kwargs ) except ClientError as err: logger.error( "Couldn't update group %s. Here's why: %s: %s", group_name, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise
-
For API details, see UpdateAutoScalingGroup in Amazon SDK for Python (Boto3) API Reference.
-
- Rust
-
- SDK for Rust
-
Note
There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository
. async fn update_group(client: &Client, name: &str, size: i32) -> Result<(), Error> { client .update_auto_scaling_group() .auto_scaling_group_name(name) .max_size(size) .send() .await?; println!("Updated AutoScaling group"); Ok(()) }
-
For API details, see UpdateAutoScalingGroup
in Amazon SDK for Rust API reference.
-
Describe an Auto Scaling group using an Amazon SDK
The following code examples show how to get information about Auto Scaling groups.
- .NET
-
- Amazon SDK for .NET
-
Note
There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository
. /// <summary> /// Get data about the instances in 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 details.</returns> public async Task<List<AutoScalingInstanceDetails>> DescribeAutoScalingInstancesAsync( string groupName) { var groups = await DescribeAutoScalingGroupsAsync(groupName); var instanceIds = new List<string>(); groups!.ForEach(group => { if (group.AutoScalingGroupName == groupName) { group.Instances.ForEach(instance => { instanceIds.Add(instance.InstanceId); }); } }); var scalingGroupsRequest = new DescribeAutoScalingInstancesRequest { MaxRecords = 10, InstanceIds = instanceIds, }; var response = await _amazonAutoScaling.DescribeAutoScalingInstancesAsync(scalingGroupsRequest); var instanceDetails = response.AutoScalingInstances; return instanceDetails; }
-
For API details, see DescribeAutoScalingGroups in Amazon SDK for .NET API Reference.
-
- C++
-
- SDK for C++
-
Note
There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository
. 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::DescribeAutoScalingGroupsRequest request; Aws::Vector<Aws::String> groupNames; groupNames.push_back(groupName); request.SetAutoScalingGroupNames(groupNames); Aws::AutoScaling::Model::DescribeAutoScalingGroupsOutcome outcome = client.DescribeAutoScalingGroups(request); if (outcome.IsSuccess()) { autoScalingGroup = outcome.GetResult().GetAutoScalingGroups(); } else { std::cerr << "Error with AutoScaling::DescribeAutoScalingGroups. " << outcome.GetError().GetMessage() << std::endl; }
-
For API details, see DescribeAutoScalingGroups in Amazon SDK for C++ API Reference.
-
- Java
-
- SDK for Java 2.x
-
Note
There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository
. public static String getAutoScaling( AutoScalingClient autoScalingClient, String groupName) { try{ String instanceId = ""; DescribeAutoScalingGroupsRequest scalingGroupsRequest = DescribeAutoScalingGroupsRequest.builder() .autoScalingGroupNames(groupName) .build(); DescribeAutoScalingGroupsResponse response = autoScalingClient.describeAutoScalingGroups(scalingGroupsRequest); List<AutoScalingGroup> groups = response.autoScalingGroups(); for (AutoScalingGroup group: groups) { System.out.println("The group name is " + group.autoScalingGroupName()); System.out.println("The group ARN is " + group.autoScalingGroupARN()); List<Instance> instances = group.instances(); for (Instance instance : instances) { instanceId = instance.instanceId(); } } return instanceId; } catch (AutoScalingException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; }
-
For API details, see DescribeAutoScalingGroups in Amazon SDK for Java 2.x API Reference.
-
- Kotlin
-
- SDK for Kotlin
-
Note
There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository
. suspend fun getAutoScalingGroups(groupName: String) { val scalingGroupsRequest = DescribeAutoScalingGroupsRequest { autoScalingGroupNames = listOf(groupName) } AutoScalingClient { region = "us-east-1" }.use { autoScalingClient -> val response = autoScalingClient.describeAutoScalingGroups(scalingGroupsRequest) response.autoScalingGroups?.forEach { group -> println("The group name is ${group.autoScalingGroupName}") println("The group ARN is ${group.autoScalingGroupArn}") group.instances?.forEach { instance -> println("The instance id is ${instance.instanceId}") println("The lifecycle state is " + instance.lifecycleState) } } } }
-
For API details, see DescribeAutoScalingGroups
in Amazon SDK for Kotlin API reference.
-
- PHP
-
- SDK for PHP
-
Note
There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository
. public function describeAutoScalingGroups($autoScalingGroupNames) { return $this->autoScalingClient->describeAutoScalingGroups([ 'AutoScalingGroupNames' => $autoScalingGroupNames ]); }
-
For API details, see DescribeAutoScalingGroups in Amazon SDK for PHP API Reference.
-
- Python
-
- SDK for Python (Boto3)
-
Note
There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository
. 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_group(self, group_name): """ Gets information about an Auto Scaling group. :param group_name: The name of the group to look up. :return: Information about the group, if found. """ try: response = self.autoscaling_client.describe_auto_scaling_groups( AutoScalingGroupNames=[group_name] ) except ClientError as err: logger.error( "Couldn't describe group %s. Here's why: %s: %s", group_name, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: groups = response.get("AutoScalingGroups", []) return groups[0] if len(groups) > 0 else None
-
For API details, see DescribeAutoScalingGroups in Amazon SDK for Python (Boto3) API Reference.
-
- Rust
-
- SDK for Rust
-
Note
There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository
. async fn list_groups(client: &Client) -> Result<(), Error> { let resp = client.describe_auto_scaling_groups().send().await?; println!("Groups:"); let groups = resp.auto_scaling_groups(); for group in groups { println!( "Name: {}", group.auto_scaling_group_name().unwrap_or("Unknown") ); println!( "Arn: {}", group.auto_scaling_group_arn().unwrap_or("unknown"), ); println!("Zones: {:?}", group.availability_zones(),); println!(); } println!("Found {} group(s)", groups.len()); Ok(()) }
-
For API details, see DescribeAutoScalingGroups
in Amazon SDK for Rust API reference.
-
Delete an Auto Scaling group using an Amazon SDK
The following code examples show how to delete an Auto Scaling group.
- .NET
-
- Amazon SDK for .NET
-
Note
There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository
. /// <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; }
-
For API details, see DeleteAutoScalingGroup in Amazon SDK for .NET API Reference.
-
- C++
-
- SDK for C++
-
Note
There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository
. 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; } }
-
For API details, see DeleteAutoScalingGroup in Amazon SDK for C++ API Reference.
-
- Java
-
- SDK for Java 2.x
-
Note
There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository
. 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); } }
-
For API details, see DeleteAutoScalingGroup in Amazon SDK for Java 2.x API Reference.
-
- Kotlin
-
- SDK for Kotlin
-
Note
There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository
. 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") } }
-
For API details, see DeleteAutoScalingGroup
in Amazon SDK for Kotlin API reference.
-
- PHP
-
- SDK for PHP
-
Note
There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository
. public function deleteAutoScalingGroup($autoScalingGroupName) { return $this->autoScalingClient->deleteAutoScalingGroup([ 'AutoScalingGroupName' => $autoScalingGroupName, 'ForceDelete' => true, ]); }
-
For API details, see DeleteAutoScalingGroup in Amazon SDK for PHP API Reference.
-
- Python
-
- SDK for Python (Boto3)
-
Note
There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository
. Update the minimum size of an Auto Scaling group to zero, terminate all instances in the group, and delete the group.
class AutoScaler: """ Encapsulates Amazon EC2 Auto Scaling and EC2 management actions. """ def __init__( self, resource_prefix, inst_type, ami_param, autoscaling_client, ec2_client, ssm_client, iam_client, ): """ :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 self.launch_template_name = f"{resource_prefix}-template" self.group_name = f"{resource_prefix}-group" self.instance_policy_name = f"{resource_prefix}-pol" self.instance_role_name = f"{resource_prefix}-role" self.instance_profile_name = f"{resource_prefix}-prof" 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" self.key_pair_name = f"{resource_prefix}-key-pair" def _try_terminate_instance(self, inst_id): stopping = False log.info(f"Stopping {inst_id}.") while not stopping: try: self.autoscaling_client.terminate_instance_in_auto_scaling_group( InstanceId=inst_id, ShouldDecrementDesiredCapacity=True ) stopping = True except ClientError as err: if err.response["Error"]["Code"] == "ScalingActivityInProgress": log.info("Scaling activity in progress for %s. Waiting...", inst_id) time.sleep(10) else: raise AutoScalerError(f"Couldn't stop instance {inst_id}: {err}.") def _try_delete_group(self): """ Tries to delete the EC2 Auto Scaling group. If the group is in use or in progress, the function waits and retries until the group is successfully deleted. """ stopped = False while not stopped: try: self.autoscaling_client.delete_auto_scaling_group( AutoScalingGroupName=self.group_name ) stopped = True log.info("Deleted EC2 Auto Scaling group %s.", self.group_name) except ClientError as err: if ( err.response["Error"]["Code"] == "ResourceInUse" or err.response["Error"]["Code"] == "ScalingActivityInProgress" ): log.info( "Some instances are still running. Waiting for them to stop..." ) time.sleep(10) else: raise AutoScalerError( f"Couldn't delete group {self.group_name}: {err}." ) def delete_group(self): """ Terminates all instances in the group, deletes the EC2 Auto Scaling group. """ try: response = self.autoscaling_client.describe_auto_scaling_groups( AutoScalingGroupNames=[self.group_name] ) groups = response.get("AutoScalingGroups", []) if len(groups) > 0: self.autoscaling_client.update_auto_scaling_group( AutoScalingGroupName=self.group_name, MinSize=0 ) instance_ids = [inst["InstanceId"] for inst in groups[0]["Instances"]] for inst_id in instance_ids: self._try_terminate_instance(inst_id) self._try_delete_group() else: log.info("No groups found named %s, nothing to do.", self.group_name) except ClientError as err: raise AutoScalerError(f"Couldn't delete group {self.group_name}: {err}.")
-
For API details, see DeleteAutoScalingGroup in Amazon SDK for Python (Boto3) API Reference.
-
- Rust
-
- SDK for Rust
-
Note
There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository
. 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(()) }
-
For API details, see DeleteAutoScalingGroup
in Amazon SDK for Rust API reference.
-