Olá, Auto Scaling - AWS SDKExemplos de código

Há mais AWS SDK exemplos disponíveis no GitHub repositório AWS Doc SDK Examples.

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

Olá, Auto Scaling

Os exemplos de código a seguir mostram como começar a usar o Auto Scaling.

.NET
AWS SDK for .NET
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

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++
SDKpara C++
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

Código para o CMakeLists arquivo.txtCMake.

# 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})

Código para o arquivo de origem hello_autoscalling.cpp.

#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
SDKpara Java 2.x
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

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 para PHP
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

public function helloService() { $autoScalingClient = new AutoScalingClient([ 'region' => 'us-west-2', 'version' => 'latest', 'profile' => 'default', ]); $groups = $autoScalingClient->describeAutoScalingGroups([]); var_dump($groups); }
Python
SDKpara Python (Boto3)
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

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 autoscaling_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"))
Ruby
SDKpara Ruby
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

require 'aws-sdk-autoscaling' require 'logger' # AutoScalingManager is a class responsible for managing AWS Auto Scaling operations # such as listing all Auto Scaling groups in the current AWS account. class AutoScalingManager def initialize(client) @client = client @logger = Logger.new($stdout) end # Gets and prints a list of Auto Scaling groups for the account. def list_auto_scaling_groups paginator = @client.describe_auto_scaling_groups auto_scaling_groups = [] paginator.each_page do |page| auto_scaling_groups.concat(page.auto_scaling_groups) end if auto_scaling_groups.empty? @logger.info('No Auto Scaling groups found for this account.') else auto_scaling_groups.each do |group| @logger.info("Auto Scaling group name: #{group.auto_scaling_group_name}") @logger.info(" Group ARN: #{group.auto_scaling_group_arn}") @logger.info(" Min/max/desired: #{group.min_size}/#{group.max_size}/#{group.desired_capacity}") @logger.info("\n") end end end end if $PROGRAM_NAME == __FILE__ autoscaling_client = Aws::AutoScaling::Client.new manager = AutoScalingManager.new(autoscaling_client) manager.list_auto_scaling_groups end
Rust
SDKpara Rust
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

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(()) }