Examples for creating and managing Auto Scaling groups with the AWS SDKs - Amazon EC2 Auto Scaling

Examples for creating and managing Auto Scaling groups with the AWS SDKs

You can create an Auto Scaling group using the AWS Management Console, the AWS CLI, an AWS SDK, and AWS 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 AWS SDKs.

Create an Auto Scaling group using an AWS SDK

The following code examples show how to use CreateAutoScalingGroup.

.NET
AWS SDK for .NET
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS 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; }
C++
SDK for C++
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS 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; }
CLI
AWS CLI

Example 1: To create an Auto Scaling group

The following create-auto-scaling-group example creates an Auto Scaling group in subnets in multiple Availability Zones within a Region. The instances launch with the default version of the specified launch template. Note that defaults are used for most other settings, such as the termination policies and health check configuration.

aws autoscaling create-auto-scaling-group \ --auto-scaling-group-name my-asg \ --launch-template LaunchTemplateId=lt-1234567890abcde12 \ --min-size 1 \ --max-size 5 \ --vpc-zone-identifier "subnet-5ea0c127,subnet-6194ea3b,subnet-c934b782"

This command produces no output.

For more information, see Auto Scaling groups in the Amazon EC2 Auto Scaling User Guide.

Example 2: To attach an Application Load Balancer, Network Load Balancer, or Gateway Load Balancer

This example specifies the ARN of a target group for a load balancer that supports the expected traffic. The health check type specifies ELB so that when Elastic Load Balancing reports an instance as unhealthy, the Auto Scaling group replaces it. The command also defines a health check grace period of 600 seconds. The grace period helps prevent premature termination of newly launched instances.

aws autoscaling create-auto-scaling-group \ --auto-scaling-group-name my-asg \ --launch-template LaunchTemplateId=lt-1234567890abcde12 \ --target-group-arns arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/943f017f100becff \ --health-check-type ELB \ --health-check-grace-period 600 \ --min-size 1 \ --max-size 5 \ --vpc-zone-identifier "subnet-5ea0c127,subnet-6194ea3b,subnet-c934b782"

This command produces no output.

For more information, see Elastic Load Balancing and Amazon EC2 Auto Scaling in the Amazon EC2 Auto Scaling User Guide.

Example 3: To specify a placement group and use the latest version of the launch template

This example launches instances into a placement group within a single Availability Zone. This can be useful for low-latency groups with HPC workloads. This example also specifies the minimum size, maximum size, and desired capacity of the group.

aws autoscaling create-auto-scaling-group \ --auto-scaling-group-name my-asg \ --launch-template LaunchTemplateId=lt-1234567890abcde12,Version='$Latest' \ --min-size 1 \ --max-size 5 \ --desired-capacity 3 \ --placement-group my-placement-group \ --vpc-zone-identifier "subnet-6194ea3b"

This command produces no output.

For more information, see Placement groups in the Amazon EC2 User Guide for Linux Instances.

Example 4: To specify a single instance Auto Scaling group and use a specific version of the launch template

This example creates an Auto Scaling group with minimum and maximum capacity set to 1 to enforce that one instance will be running. The command also specifies v1 of a launch template in which the ID of an existing ENI is specified. When you use a launch template that specifies an existing ENI for eth0, you must specify an Availability Zone for the Auto Scaling group that matches the network interface, without also specifying a subnet ID in the request.

aws autoscaling create-auto-scaling-group \ --auto-scaling-group-name my-asg-single-instance \ --launch-template LaunchTemplateName=my-template-for-auto-scaling,Version='1' \ --min-size 1 \ --max-size 1 \ --availability-zones us-west-2a

This command produces no output.

For more information, see Auto Scaling groups in the Amazon EC2 Auto Scaling User Guide.

Example 5: To specify a different termination policy

This example creates an Auto Scaling group using a launch configuration and sets the termination policy to terminate the oldest instances first. The command also applies a tag to the group and its instances, with a key of Role and a value of WebServer.

aws autoscaling create-auto-scaling-group \ --auto-scaling-group-name my-asg \ --launch-configuration-name my-lc \ --min-size 1 \ --max-size 5 \ --termination-policies "OldestInstance" \ --tags "ResourceId=my-asg,ResourceType=auto-scaling-group,Key=Role,Value=WebServer,PropagateAtLaunch=true" \ --vpc-zone-identifier "subnet-5ea0c127,subnet-6194ea3b,subnet-c934b782"

This command produces no output.

For more information, see Working with Amazon EC2 Auto Scaling termination policies in the Amazon EC2 Auto Scaling User Guide.

Example 6: To specify a launch lifecycle hook

This example creates an Auto Scaling group with a lifecycle hook that supports a custom action at instance launch.

aws autoscaling create-auto-scaling-group \ --cli-input-json file://~/config.json

Contents of config.json file:

{ "AutoScalingGroupName": "my-asg", "LaunchTemplate": { "LaunchTemplateId": "lt-1234567890abcde12" }, "LifecycleHookSpecificationList": [{ "LifecycleHookName": "my-launch-hook", "LifecycleTransition": "autoscaling:EC2_INSTANCE_LAUNCHING", "NotificationTargetARN": "arn:aws:sqs:us-west-2:123456789012:my-sqs-queue", "RoleARN": "arn:aws:iam::123456789012:role/my-notification-role", "NotificationMetadata": "SQS message metadata", "HeartbeatTimeout": 4800, "DefaultResult": "ABANDON" }], "MinSize": 1, "MaxSize": 5, "VPCZoneIdentifier": "subnet-5ea0c127,subnet-6194ea3b,subnet-c934b782", "Tags": [{ "ResourceType": "auto-scaling-group", "ResourceId": "my-asg", "PropagateAtLaunch": true, "Value": "test", "Key": "environment" }] }

This command produces no output.

For more information, see Amazon EC2 Auto Scaling lifecycle hooks in the Amazon EC2 Auto Scaling User Guide.

Example 7: To specify a termination lifecycle hook

This example creates an Auto Scaling group with a lifecycle hook that supports a custom action at instance termination.

aws autoscaling create-auto-scaling-group \ --cli-input-json file://~/config.json

Contents of config.json:

{ "AutoScalingGroupName": "my-asg", "LaunchTemplate": { "LaunchTemplateId": "lt-1234567890abcde12" }, "LifecycleHookSpecificationList": [{ "LifecycleHookName": "my-termination-hook", "LifecycleTransition": "autoscaling:EC2_INSTANCE_TERMINATING", "HeartbeatTimeout": 120, "DefaultResult": "CONTINUE" }], "MinSize": 1, "MaxSize": 5, "TargetGroupARNs": [ "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067" ], "VPCZoneIdentifier": "subnet-5ea0c127,subnet-6194ea3b,subnet-c934b782" }

This command produces no output.

For more information, see Amazon EC2 Auto Scaling lifecycle hooks in the Amazon EC2 Auto Scaling User Guide.

Example 8: To specify a custom termination policy

This example creates an Auto Scaling group that specifies a custom Lambda function termination policy that tells Amazon EC2 Auto Scaling which instances are safe to terminate on scale in.

aws autoscaling create-auto-scaling-group \ --auto-scaling-group-name my-asg-single-instance \ --launch-template LaunchTemplateName=my-template-for-auto-scaling \ --min-size 1 \ --max-size 5 \ --termination-policies "arn:aws:lambda:us-west-2:123456789012:function:HelloFunction:prod" \ --vpc-zone-identifier "subnet-5ea0c127,subnet-6194ea3b,subnet-c934b782"

This command produces no output.

For more information, see Creating a custom termination policy with Lambda in the Amazon EC2 Auto Scaling User Guide.

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 AWS Code Examples Repository.

import software.amazon.awssdk.core.waiters.WaiterResponse; 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.CreateAutoScalingGroupRequest; import software.amazon.awssdk.services.autoscaling.model.DescribeAutoScalingGroupsRequest; import software.amazon.awssdk.services.autoscaling.model.DescribeAutoScalingGroupsResponse; import software.amazon.awssdk.services.autoscaling.model.LaunchTemplateSpecification; import software.amazon.awssdk.services.autoscaling.waiters.AutoScalingWaiter; /** * 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 CreateAutoScalingGroup { public static void main(String[] args) { final String usage = """ Usage: <groupName> <launchTemplateName> <serviceLinkedRoleARN> <vpcZoneId> Where: groupName - The name of the Auto Scaling group. launchTemplateName - The name of the launch template.\s vpcZoneId - A subnet Id for a virtual private cloud (VPC) where instances in the Auto Scaling group can be created. """; if (args.length != 3) { System.out.println(usage); System.exit(1); } String groupName = args[0]; String launchTemplateName = args[1]; String vpcZoneId = args[2]; AutoScalingClient autoScalingClient = AutoScalingClient.builder() .region(Region.US_EAST_1) .build(); createAutoScalingGroup(autoScalingClient, groupName, launchTemplateName, vpcZoneId); autoScalingClient.close(); } 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); } } }
Kotlin
SDK for Kotlin
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS 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!") } }
PHP
SDK for PHP
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS 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, ], ]); }
PowerShell
Tools for PowerShell

Example 1: This example creates an Auto Scaling group with the specified name and attributes. The default desired capacity is the minimum size. Therefore, this Auto Scaling group launches two instances, one in each of the specified two Availability Zones.

New-ASAutoScalingGroup -AutoScalingGroupName my-asg -LaunchConfigurationName my-lc -MinSize 2 -MaxSize 6 -AvailabilityZone @("us-west-2a", "us-west-2b")
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 AWS 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
Rust
SDK for Rust
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS 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 examples you can use when creating mixed instances groups, see the following resources.

Update an Auto Scaling group using an AWS SDK

The following code examples show how to use UpdateAutoScalingGroup.

.NET
AWS SDK for .NET
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS 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; } }
C++
SDK for C++
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS 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; }
CLI
AWS CLI

Example 1: To update the size limits of an Auto Scaling group

This example updates the specified Auto Scaling group with a minimum size of 2 and a maximum size of 10.

aws autoscaling update-auto-scaling-group \ --auto-scaling-group-name my-asg \ --min-size 2 \ --max-size 10

This command produces no output.

For more information, see Setting capacity limits for your Auto Scaling group in the Amazon EC2 Auto Scaling User Guide.

Example 2: To add Elastic Load Balancing health checks and specify which Availability Zones and subnets to use

This example updates the specified Auto Scaling group to add Elastic Load Balancing health checks. This command also updates the value of --vpc-zone-identifier with a list of subnet IDs in multiple Availability Zones.

aws autoscaling update-auto-scaling-group \ --auto-scaling-group-name my-asg \ --health-check-type ELB \ --health-check-grace-period 600 \ --vpc-zone-identifier "subnet-5ea0c127,subnet-6194ea3b,subnet-c934b782"

This command produces no output.

For more information, see Elastic Load Balancing and Amazon EC2 Auto Scaling in the Amazon EC2 Auto Scaling User Guide.

Example 3: To update the placement group and termination policy

This example updates the placement group and termination policy to use.

aws autoscaling update-auto-scaling-group \ --auto-scaling-group-name my-asg \ --placement-group my-placement-group \ --termination-policies "OldestInstance"

This command produces no output.

For more information, see Auto Scaling groups in the Amazon EC2 Auto Scaling User Guide.

Example 4: To use the latest version of the launch template

This example updates the specified Auto Scaling group to use the latest version of the specified launch template.

aws autoscaling update-auto-scaling-group \ --auto-scaling-group-name my-asg \ --launch-template LaunchTemplateId=lt-1234567890abcde12,Version='$Latest'

This command produces no output.

For more information, see Launch templates in the Amazon EC2 Auto Scaling User Guide.

Example 5: To use a specific version of the launch template

This example updates the specified Auto Scaling group to use a specific version of a launch template instead of the latest or default version.

aws autoscaling update-auto-scaling-group \ --auto-scaling-group-name my-asg \ --launch-template LaunchTemplateName=my-template-for-auto-scaling,Version='2'

This command produces no output.

For more information, see Launch templates in the Amazon EC2 Auto Scaling User Guide.

Example 6: To define a mixed instances policy and enable capacity rebalancing

This example updates the specified Auto Scaling group to use a mixed instances policy and enables capacity rebalancing. This structure lets you specify groups with Spot and On-Demand capacities and use different launch templates for different architectures.

aws autoscaling update-auto-scaling-group \ --cli-input-json file://~/config.json

Contents of config.json:

{ "AutoScalingGroupName": "my-asg", "CapacityRebalance": true, "MixedInstancesPolicy": { "LaunchTemplate": { "LaunchTemplateSpecification": { "LaunchTemplateName": "my-launch-template-for-x86", "Version": "$Latest" }, "Overrides": [ { "InstanceType": "c6g.large", "LaunchTemplateSpecification": { "LaunchTemplateName": "my-launch-template-for-arm", "Version": "$Latest" } }, { "InstanceType": "c5.large" }, { "InstanceType": "c5a.large" } ] }, "InstancesDistribution": { "OnDemandPercentageAboveBaseCapacity": 50, "SpotAllocationStrategy": "capacity-optimized" } } }

This command produces no output.

For more information, see Auto Scaling groups with multiple instance types and purchase options in the Amazon EC2 Auto Scaling User Guide.

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 AWS 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); } }
Kotlin
SDK for Kotlin
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS 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") } }
PHP
SDK for PHP
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS 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); }
PowerShell
Tools for PowerShell

Example 1: This example updates the minimum and maximum size of the specified Auto Scaling group.

Update-ASAutoScalingGroup -AutoScalingGroupName my-asg -MaxSize 5 -MinSize 1

Example 2: This example updates the default cooldown period of the specified Auto Scaling group.

Update-ASAutoScalingGroup -AutoScalingGroupName my-asg -DefaultCooldown 10

Example 3: This example updates the Availability Zones of the specified Auto Scaling group.

Update-ASAutoScalingGroup -AutoScalingGroupName my-asg -AvailabilityZone @("us-west-2a", "us-west-2b")

Example 4: This example updates the specified Auto Scaling group to use Elastic Load Balancing health checks.

Update-ASAutoScalingGroup -AutoScalingGroupName my-asg -HealthCheckType ELB -HealthCheckGracePeriod 60
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 AWS 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
Rust
SDK for Rust
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS 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(()) }

Describe an Auto Scaling group using an AWS SDK

The following code examples show how to use DescribeAutoScalingGroups.

.NET
AWS SDK for .NET
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS 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; }
C++
SDK for C++
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS 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; }
CLI
AWS CLI

Example 1: To describe the specified Auto Scaling group

This example describes the specified Auto Scaling group.

aws autoscaling describe-auto-scaling-groups \ --auto-scaling-group-name my-asg

Output:

{ "AutoScalingGroups": [ { "AutoScalingGroupName": "my-asg", "AutoScalingGroupARN": "arn:aws:autoscaling:us-west-2:123456789012:autoScalingGroup:930d940e-891e-4781-a11a-7b0acd480f03:autoScalingGroupName/my-asg", "LaunchTemplate": { "LaunchTemplateName": "my-launch-template", "Version": "1", "LaunchTemplateId": "lt-1234567890abcde12" }, "MinSize": 0, "MaxSize": 1, "DesiredCapacity": 1, "DefaultCooldown": 300, "AvailabilityZones": [ "us-west-2a", "us-west-2b", "us-west-2c" ], "LoadBalancerNames": [], "TargetGroupARNs": [], "HealthCheckType": "EC2", "HealthCheckGracePeriod": 0, "Instances": [ { "InstanceId": "i-06905f55584de02da", "InstanceType": "t2.micro", "AvailabilityZone": "us-west-2a", "HealthStatus": "Healthy", "LifecycleState": "InService", "ProtectedFromScaleIn": false, "LaunchTemplate": { "LaunchTemplateName": "my-launch-template", "Version": "1", "LaunchTemplateId": "lt-1234567890abcde12" } } ], "CreatedTime": "2023-10-28T02:39:22.152Z", "SuspendedProcesses": [], "VPCZoneIdentifier": "subnet-5ea0c127,subnet-6194ea3b,subnet-c934b782", "EnabledMetrics": [], "Tags": [], "TerminationPolicies": [ "Default" ], "NewInstancesProtectedFromScaleIn": false, "ServiceLinkedRoleARN":"arn", "TrafficSources": [] } ] }

Example 2: To describe the first 100 specified Auto Scaling group

This example describes the specified Auto Scaling groups. It allows you to specify up to 100 group names.

aws autoscaling describe-auto-scaling-groups \ --max-items 100 \ --auto-scaling-group-name "group1" "group2" "group3" "group4"

See example 1 for sample output.

Example 3: To describe an Auto Scaling group in the specified region

This example describes the Auto Scaling groups in the specified region, up to a maximum of 75 groups.

aws autoscaling describe-auto-scaling-groups \ --max-items 75 \ --region us-east-1

See example 1 for sample output.

Example 4: To describe the specified number of Auto Scaling group

To return a specific number of Auto Scaling groups, use the --max-items option.

aws autoscaling describe-auto-scaling-groups \ --max-items 1

See example 1 for sample output.

If the output includes a NextToken field, there are more groups. To get the additional groups, use the value of this field with the --starting-token option in a subsequent call as follows.

aws autoscaling describe-auto-scaling-groups \ --starting-token Z3M3LMPEXAMPLE

See example 1 for sample output.

Example 5: To describe Auto Scaling groups that use launch configurations

This example uses the --query option to describe Auto Scaling groups that use launch configurations.

aws autoscaling describe-auto-scaling-groups \ --query 'AutoScalingGroups[?LaunchConfigurationName!=`null`]'

Output:

[ { "AutoScalingGroupName": "my-asg", "AutoScalingGroupARN": "arn:aws:autoscaling:us-west-2:123456789012:autoScalingGroup:930d940e-891e-4781-a11a-7b0acd480f03:autoScalingGroupName/my-asg", "LaunchConfigurationName": "my-lc", "MinSize": 0, "MaxSize": 1, "DesiredCapacity": 1, "DefaultCooldown": 300, "AvailabilityZones": [ "us-west-2a", "us-west-2b", "us-west-2c" ], "LoadBalancerNames": [], "TargetGroupARNs": [], "HealthCheckType": "EC2", "HealthCheckGracePeriod": 0, "Instances": [ { "InstanceId": "i-088c57934a6449037", "InstanceType": "t2.micro", "AvailabilityZone": "us-west-2c", "HealthStatus": "Healthy", "LifecycleState": "InService", "LaunchConfigurationName": "my-lc", "ProtectedFromScaleIn": false } ], "CreatedTime": "2023-10-28T02:39:22.152Z", "SuspendedProcesses": [], "VPCZoneIdentifier": "subnet-5ea0c127,subnet-6194ea3b,subnet-c934b782", "EnabledMetrics": [], "Tags": [], "TerminationPolicies": [ "Default" ], "NewInstancesProtectedFromScaleIn": false, "ServiceLinkedRoleARN":"arn", "TrafficSources": [] } ]

For more information, see Filter AWS CLI output in the AWS Command Line Interface User Guide.

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 AWS Code Examples Repository.

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.AutoScalingGroup; import software.amazon.awssdk.services.autoscaling.model.DescribeAutoScalingGroupsResponse; import software.amazon.awssdk.services.autoscaling.model.DescribeAutoScalingGroupsRequest; import software.amazon.awssdk.services.autoscaling.model.Instance; import java.util.List; /** * 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 DescribeAutoScalingInstances { 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(); String instanceId = getAutoScaling(autoScalingClient, groupName); System.out.println(instanceId); autoScalingClient.close(); } 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 ""; } }
Kotlin
SDK for Kotlin
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS 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) } } } }
PHP
SDK for PHP
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

public function describeAutoScalingGroups($autoScalingGroupNames) { return $this->autoScalingClient->describeAutoScalingGroups([ 'AutoScalingGroupNames' => $autoScalingGroupNames ]); }
PowerShell
Tools for PowerShell

Example 1: This example lists the names of your Auto Scaling groups.

Get-ASAutoScalingGroup | format-table -property AutoScalingGroupName

Output:

AutoScalingGroupName -------------------- my-asg-1 my-asg-2 my-asg-3 my-asg-4 my-asg-5 my-asg-6

Example 2: This example describes the specified Auto Scaling group.

Get-ASAutoScalingGroup -AutoScalingGroupName my-asg-1

Output:

AutoScalingGroupARN : arn:aws:autoscaling:us-west-2:123456789012:autoScalingGroup:930d940e-891e-4781-a11a-7b0acd480 f03:autoScalingGroupName/my-asg-1 AutoScalingGroupName : my-asg-1 AvailabilityZones : {us-west-2b, us-west-2a} CreatedTime : 3/1/2015 9:05:31 AM DefaultCooldown : 300 DesiredCapacity : 2 EnabledMetrics : {} HealthCheckGracePeriod : 300 HealthCheckType : EC2 Instances : {my-lc} LaunchConfigurationName : my-lc LoadBalancerNames : {} MaxSize : 0 MinSize : 0 PlacementGroup : Status : SuspendedProcesses : {} Tags : {} TerminationPolicies : {Default} VPCZoneIdentifier : subnet-e4f33493,subnet-5264e837

Example 3: This example describes the specified two Auto Scaling groups.

Get-ASAutoScalingGroup -AutoScalingGroupName @("my-asg-1", "my-asg-2")

Example 4: This example describes the Auto Scaling instances for the specified Auto Scaling group.

(Get-ASAutoScalingGroup -AutoScalingGroupName my-asg-1).Instances

Example 5: This example describes all your Auto Scaling groups.

Get-ASAutoScalingGroup

Example 6: This example describes all your Auto Scaling groups, in batches of 10.

$nextToken = $null do { Get-ASAutoScalingGroup -NextToken $nextToken -MaxRecord 10 $nextToken = $AWSHistory.LastServiceResponse.NextToken } while ($nextToken -ne $null)

Example 7: This example describes LaunchTemplate for the specified Auto Scaling group. This example assumes that the "Instance purchase options" is set to "Adhere to launch template". In case this option is set to "Combine purchase options and instance types", LaunchTemplate could be accessed using "MixedInstancesPolicy.LaunchTemplate" property.

(Get-ASAutoScalingGroup -AutoScalingGroupName my-ag-1).LaunchTemplate

Output:

LaunchTemplateId LaunchTemplateName Version ---------------- ------------------ ------- lt-06095fd619cb40371 test-launch-template $Default
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 AWS 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
Rust
SDK for Rust
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS 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(()) }

Delete an Auto Scaling group using an AWS SDK

The following code examples show how to use DeleteAutoScalingGroup.

.NET
AWS SDK for .NET
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

Update the minimum size of an Auto Scaling group to zero, terminate all instances in the group, and delete the group.

/// <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 for C++
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS 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; } }
CLI
AWS CLI

Example 1: To delete the specified Auto Scaling group

This example deletes the specified Auto Scaling group.

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

This command produces no output.

For more information, see Deleting your Auto Scaling infrastructure in the Amazon EC2 Auto Scaling User Guide.

Example 2: To force delete the specified Auto Scaling group

To delete the Auto Scaling group without waiting for the instances in the group to terminate, use the --force-delete option.

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

This command produces no output.

For more information, see Deleting your Auto Scaling infrastructure in the Amazon EC2 Auto Scaling User Guide.

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 AWS Code Examples Repository.

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 for Kotlin
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS 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") } }
PHP
SDK for PHP
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

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

Example 1: This example deletes the specified Auto Scaling group if it has no running instances. You are prompted for confirmation before the operation proceeds.

Remove-ASAutoScalingGroup -AutoScalingGroupName my-asg

Output:

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"):

Example 2: If you specify the Force parameter, you are not prompted for confirmation before the operation proceeds.

Remove-ASAutoScalingGroup -AutoScalingGroupName my-asg -Force

Example 3: This example deletes the specified Auto Scaling group and terminates any running instances that it contains.

Remove-ASAutoScalingGroup -AutoScalingGroupName my-asg -ForceDelete $true -Force
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 AWS 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}.")
Rust
SDK for Rust
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS 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(()) }
Example availability

Can't find what you need? Request a new code example by using the Provide feedback link at the bottom of this page.