Use SetDesiredCapacity with an AWS SDK or CLI - AWS SDK Code Examples

There are more AWS SDK examples available in the AWS Doc SDK Examples GitHub repo.

Use SetDesiredCapacity with an AWS SDK or CLI

The following code examples show how to use SetDesiredCapacity.

Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code example:

.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> /// Set the desired capacity of an Auto Scaling group. /// </summary> /// <param name="groupName">The name of the Auto Scaling group.</param> /// <param name="desiredCapacity">The desired capacity for the Auto /// Scaling group.</param> /// <returns>A Boolean value indicating the success of the action.</returns> public async Task<bool> SetDesiredCapacityAsync( string groupName, int desiredCapacity) { var capacityRequest = new SetDesiredCapacityRequest { AutoScalingGroupName = groupName, DesiredCapacity = desiredCapacity, }; var response = await _amazonAutoScaling.SetDesiredCapacityAsync(capacityRequest); Console.WriteLine($"You have set the DesiredCapacity to {desiredCapacity}."); 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::SetDesiredCapacityRequest request; request.SetAutoScalingGroupName(groupName); request.SetDesiredCapacity(2); Aws::AutoScaling::Model::SetDesiredCapacityOutcome outcome = autoScalingClient.SetDesiredCapacity(request); if (!outcome.IsSuccess()) { std::cerr << "Error with AutoScaling::SetDesiredCapacityRequest. " << outcome.GetError().GetMessage() << std::endl; }
CLI
AWS CLI

To set the desired capacity for an Auto Scaling group

This example sets the desired capacity for the specified Auto Scaling group.

aws autoscaling set-desired-capacity \ --auto-scaling-group-name my-asg \ --desired-capacity 2 \ --honor-cooldown

This command returns to the prompt if successful.

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 setDesiredCapacity(AutoScalingClient autoScalingClient, String groupName) { try { SetDesiredCapacityRequest capacityRequest = SetDesiredCapacityRequest.builder() .autoScalingGroupName(groupName) .desiredCapacity(2) .build(); autoScalingClient.setDesiredCapacity(capacityRequest); System.out.println("You have set the DesiredCapacity to 2"); } 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 setDesiredCapacity(groupName: String) { val capacityRequest = SetDesiredCapacityRequest { autoScalingGroupName = groupName desiredCapacity = 2 } AutoScalingClient { region = "us-east-1" }.use { autoScalingClient -> autoScalingClient.setDesiredCapacity(capacityRequest) println("You set the DesiredCapacity to 2") } }
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 setDesiredCapacity($autoScalingGroupName, $desiredCapacity) { return $this->autoScalingClient->setDesiredCapacity([ 'AutoScalingGroupName' => $autoScalingGroupName, 'DesiredCapacity' => $desiredCapacity, ]); }
PowerShell
Tools for PowerShell

Example 1: This example sets the size of the specified Auto Scaling group.

Set-ASDesiredCapacity -AutoScalingGroupName my-asg -DesiredCapacity 2

Example 2: This example sets the size of the specified Auto Scaling group and waits for the cooldown period to complete before scaling to the new size.

Set-ASDesiredCapacity -AutoScalingGroupName my-asg -DesiredCapacity 2 -HonorCooldown $true
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 set_desired_capacity(self, group_name: str, capacity: int) -> None: """ Sets the desired capacity of the group. Amazon EC2 Auto Scaling tries to keep the number of running instances equal to the desired capacity. :param group_name: The name of the group to update. :param capacity: The desired number of running instances. :return: None :raises ClientError: If there is an error setting the desired capacity. """ try: self.autoscaling_client.set_desired_capacity( AutoScalingGroupName=group_name, DesiredCapacity=capacity, HonorCooldown=False, ) logger.info( f"Successfully set desired capacity of {capacity} for Auto Scaling group '{group_name}'." ) except ClientError as err: error_code = err.response["Error"]["Code"] logger.error( f"Failed to set desired capacity for Auto Scaling group '{group_name}'." ) if error_code == "ScalingActivityInProgress": logger.error( f"A scaling activity is currently in progress for the Auto Scaling group '{group_name}'. " "Please wait for the activity to complete before attempting to set the desired capacity." ) logger.error(f"Full error:\n\t{err}") 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.

pub async fn scale_desired_capacity(&self, capacity: i32) -> Result<(), ScenarioError> { // 7. SetDesiredCapacity: set desired capacity to 2. // Wait for a second instance to launch. let update_group = self .autoscaling .set_desired_capacity() .auto_scaling_group_name(self.auto_scaling_group_name.clone()) .desired_capacity(capacity) .send() .await; if let Err(err) = update_group { return Err(ScenarioError::new( format!("Failed to update group to desired capacity ({capacity}))").as_str(), &err, )); } Ok(()) }