Code examples for Auto Scaling using AWS SDKs - AWS SDK Code Examples

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

Code examples for Auto Scaling using AWS SDKs

The following code examples show you how to use Amazon EC2 Auto Scaling with an AWS software development kit (SDK).

Actions are code excerpts from larger programs and must be run in context. While actions show you how to call individual service functions, you can see actions in context in their related scenarios and cross-service examples.

Scenarios are code examples that show you how to accomplish a specific task by calling multiple functions within the same service.

More resources

Get started

The following code examples show how to get started using Auto Scaling.

.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.

namespace AutoScalingActions; using Amazon.AutoScaling; public class HelloAutoScaling { /// <summary> /// Hello Amazon EC2 Auto Scaling. List EC2 Auto Scaling groups. /// </summary> /// <param name="args"></param> /// <returns>Async Task.</returns> static async Task Main(string[] args) { var client = new AmazonAutoScalingClient(); Console.WriteLine("Welcome to Amazon EC2 Auto Scaling."); Console.WriteLine("Let's get a description of your Auto Scaling groups."); var response = await client.DescribeAutoScalingGroupsAsync(); response.AutoScalingGroups.ForEach(autoScalingGroup => { Console.WriteLine($"{autoScalingGroup.AutoScalingGroupName}\t{autoScalingGroup.AvailabilityZones}"); }); if (response.AutoScalingGroups.Count == 0) { Console.WriteLine("Sorry, you don't have any Amazon EC2 Auto Scaling groups."); } } }
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.

Code for the CMakeLists.txt CMake file.

# Set the minimum required version of CMake for this project. cmake_minimum_required(VERSION 3.13) # Set the AWS service components used by this project. set(SERVICE_COMPONENTS autoscaling) # Set this project's name. project("hello_autoscaling") # Set the C++ standard to use to build this target. # At least C++ 11 is required for the AWS SDK for C++. set(CMAKE_CXX_STANDARD 11) # Use the MSVC variable to determine if this is a Windows build. set(WINDOWS_BUILD ${MSVC}) if (WINDOWS_BUILD) # Set the location where CMake can find the installed libraries for the AWS SDK. string(REPLACE ";" "/aws-cpp-sdk-all;" SYSTEM_MODULE_PATH "${CMAKE_SYSTEM_PREFIX_PATH}/aws-cpp-sdk-all") list(APPEND CMAKE_PREFIX_PATH ${SYSTEM_MODULE_PATH}) endif () # Find the AWS SDK for C++ package. find_package(AWSSDK REQUIRED COMPONENTS ${SERVICE_COMPONENTS}) if (WINDOWS_BUILD AND AWSSDK_INSTALL_AS_SHARED_LIBS) # Copy relevant AWS SDK for C++ libraries into the current binary directory for running and debugging. # set(BIN_SUB_DIR "/Debug") # If you are building from the command line, you may need to uncomment this # and set the proper subdirectory to the executables' location. AWSSDK_CPY_DYN_LIBS(SERVICE_COMPONENTS "" ${CMAKE_CURRENT_BINARY_DIR}${BIN_SUB_DIR}) endif () add_executable(${PROJECT_NAME} hello_autoscaling.cpp) target_link_libraries(${PROJECT_NAME} ${AWSSDK_LINK_LIBRARIES})

Code for the hello_autoscaling.cpp source file.

#include <aws/core/Aws.h> #include <aws/autoscaling/AutoScalingClient.h> #include <aws/autoscaling/model/DescribeAutoScalingGroupsRequest.h> #include <iostream> /* * A "Hello Autoscaling" starter application which initializes an Amazon EC2 Auto Scaling client and describes the * Amazon EC2 Auto Scaling groups. * * main function * * Usage: 'hello_autoscaling' * */ int main(int argc, char **argv) { Aws::SDKOptions options; // Optionally change the log level for debugging. // options.loggingOptions.logLevel = Utils::Logging::LogLevel::Debug; Aws::InitAPI(options); // Should only be called once. int result = 0; { Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Aws::AutoScaling::AutoScalingClient autoscalingClient(clientConfig); std::vector<Aws::String> groupNames; Aws::String nextToken; // Used for pagination. do { Aws::AutoScaling::Model::DescribeAutoScalingGroupsRequest request; if (!nextToken.empty()) { request.SetNextToken(nextToken); } Aws::AutoScaling::Model::DescribeAutoScalingGroupsOutcome outcome = autoscalingClient.DescribeAutoScalingGroups(request); if (outcome.IsSuccess()) { const Aws::Vector<Aws::AutoScaling::Model::AutoScalingGroup> &autoScalingGroups = outcome.GetResult().GetAutoScalingGroups(); for (auto &group: autoScalingGroups) { groupNames.push_back(group.GetAutoScalingGroupName()); } nextToken = outcome.GetResult().GetNextToken(); } else { std::cerr << "Error with AutoScaling::DescribeAutoScalingGroups. " << outcome.GetError().GetMessage() << std::endl; result = 1; break; } } while (!nextToken.empty()); std::cout << "Found " << groupNames.size() << " AutoScaling groups." << std::endl; for (auto &groupName: groupNames) { std::cout << "AutoScaling group: " << groupName << std::endl; } } Aws::ShutdownAPI(options); // Should only be called once. return result; }
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.AutoScalingGroup; import software.amazon.awssdk.services.autoscaling.model.DescribeAutoScalingGroupsResponse; 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 DescribeAutoScalingGroups { public static void main(String[] args) throws InterruptedException { AutoScalingClient autoScalingClient = AutoScalingClient.builder() .region(Region.US_EAST_1) .build(); describeGroups(autoScalingClient); } public static void describeGroups(AutoScalingClient autoScalingClient) { DescribeAutoScalingGroupsResponse response = autoScalingClient.describeAutoScalingGroups(); List<AutoScalingGroup> groups = response.autoScalingGroups(); groups.forEach(group -> { System.out.println("Group Name: " + group.autoScalingGroupName()); System.out.println("Group ARN: " + group.autoScalingGroupARN()); }); } }
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 helloService() { $autoScalingClient = new AutoScalingClient([ 'region' => 'us-west-2', 'version' => 'latest', 'profile' => 'default', ]); $groups = $autoScalingClient->describeAutoScalingGroups([]); var_dump($groups); }
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.

import boto3 def hello_autoscaling(autoscaling_client): """ Use the AWS SDK for Python (Boto3) to create an Amazon EC2 Auto Scaling client and list some of the Auto Scaling groups in your account. This example uses the default settings specified in your shared credentials and config files. :param auto-scaling_client: A Boto3 Amazon EC2 Auto Scaling client object. """ print( "Hello, Amazon EC2 Auto Scaling! Let's list up to ten of you Auto Scaling groups:" ) response = autoscaling_client.describe_auto_scaling_groups() groups = response.get("AutoScalingGroups", []) if groups: for group in groups: print(f"\t{group['AutoScalingGroupName']}: {group['AvailabilityZones']}") else: print("There are no Auto Scaling groups in your account.") if __name__ == "__main__": hello_autoscaling(boto3.client("autoscaling"))
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(()) }