Use DescribeInstanceTypes com um AWS SDK ou CLI - 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á.

Use DescribeInstanceTypes com um AWS SDK ou CLI

Os exemplos de código a seguir mostram como usar o DescribeInstanceTypes.

Exemplos de ações são trechos de código de programas maiores e devem ser executados em contexto. É possível ver essa ação no contexto no seguinte exemplo de código:

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

/// <summary> /// Describe the instance types available. /// </summary> /// <returns>A list of instance type information.</returns> public async Task<List<InstanceTypeInfo>> DescribeInstanceTypes(ArchitectureValues architecture) { var request = new DescribeInstanceTypesRequest(); var filters = new List<Filter> { new Filter("processor-info.supported-architecture", new List<string> { architecture.ToString() }) }; filters.Add(new Filter("instance-type", new() { "*.micro", "*.small" })); request.Filters = filters; var instanceTypes = new List<InstanceTypeInfo>(); var paginator = _amazonEC2.Paginators.DescribeInstanceTypes(request); await foreach (var instanceType in paginator.InstanceTypes) { instanceTypes.Add(instanceType); } return instanceTypes; }
Bash
AWS CLI com script Bash
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.

############################################################################### # ec2_describe_instance_types # # This function describes EC2 instance types filtered by processor architecture # and optionally by instance type. It takes the following arguments: # # -a, --architecture ARCHITECTURE Specify the processor architecture (e.g., x86_64) # -t, --type INSTANCE_TYPE Comma-separated list of instance types (e.g., t2.micro) # -h, --help Show the usage help # # The function prints the instance type and supported architecture for each # matching instance type. ############################################################################### function ec2_describe_instance_types() { local architecture="" local instance_types="" # bashsupport disable=BP5008 function usage() { echo "Usage: ec2_describe_instance_types [-a|--architecture ARCHITECTURE] [-t|--type INSTANCE_TYPE] [-h|--help]" echo " -a, --architecture ARCHITECTURE Specify the processor architecture (e.g., x86_64)" echo " -t, --type INSTANCE_TYPE Comma-separated list of instance types (e.g., t2.micro)" echo " -h, --help Show this help message" } while [[ $# -gt 0 ]]; do case "$1" in -a | --architecture) architecture="$2" shift 2 ;; -t | --type) instance_types="$2" shift 2 ;; -h | --help) usage return 0 ;; *) echo "Unknown argument: $1" return 1 ;; esac done if [[ -z "$architecture" ]]; then errecho "Error: Architecture not specified." usage return 1 fi if [[ -z "$instance_types" ]]; then errecho "Error: Instance type not specified." usage return 1 fi local tmp_json_file="temp_ec2.json" echo -n '[ { "Name": "processor-info.supported-architecture", "Values": [' >"$tmp_json_file" local items IFS=',' read -ra items <<<"$architecture" local array_size array_size=${#items[@]} for i in $(seq 0 $((array_size - 1))); do echo -n '"'"${items[$i]}"'"' >>"$tmp_json_file" if [[ $i -lt $((array_size - 1)) ]]; then echo -n ',' >>"$tmp_json_file" fi done echo -n ']}, { "Name": "instance-type", "Values": [' >>"$tmp_json_file" IFS=',' read -ra items <<<"$instance_types" local array_size array_size=${#items[@]} for i in $(seq 0 $((array_size - 1))); do echo -n '"'"${items[$i]}"'"' >>"$tmp_json_file" if [[ $i -lt $((array_size - 1)) ]]; then echo -n ',' >>"$tmp_json_file" fi done echo -n ']}]' >>"$tmp_json_file" local response response=$(aws ec2 describe-instance-types --filters file://"$tmp_json_file" \ --query 'InstanceTypes[*].[InstanceType]' --output text) local error_code=$? rm "$tmp_json_file" if [[ $error_code -ne 0 ]]; then aws_cli_error_log $error_code echo "ERROR: AWS reports describe-instance-types operation failed." return 1 fi echo "$response" return 0 }

As funções utilitárias usadas neste exemplo.

############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################## # function aws_cli_error_log() # # This function is used to log the error messages from the AWS CLI. # # The function expects the following argument: # $1 - The error code returned by the AWS CLI. # # Returns: # 0: - Success. # ############################################################################## function aws_cli_error_log() { local err_code=$1 errecho "Error code : $err_code" if [ "$err_code" == 1 ]; then errecho " One or more S3 transfers failed." elif [ "$err_code" == 2 ]; then errecho " Command line failed to parse." elif [ "$err_code" == 130 ]; then errecho " Process received SIGINT." elif [ "$err_code" == 252 ]; then errecho " Command syntax invalid." elif [ "$err_code" == 253 ]; then errecho " The system environment or configuration was invalid." elif [ "$err_code" == 254 ]; then errecho " The service returned an error." elif [ "$err_code" == 255 ]; then errecho " 255 is a catch-all error." fi return 0 }
CLI
AWS CLI

Exemplo 1: descrever um tipo de instância

O exemplo describe-instance-types a seguir exibe os detalhes do tipo da instância especificado.

aws ec2 describe-instance-types \ --instance-types t2.micro

Saída:

{ "InstanceTypes": [ { "InstanceType": "t2.micro", "CurrentGeneration": true, "FreeTierEligible": true, "SupportedUsageClasses": [ "on-demand", "spot" ], "SupportedRootDeviceTypes": [ "ebs" ], "BareMetal": false, "Hypervisor": "xen", "ProcessorInfo": { "SupportedArchitectures": [ "i386", "x86_64" ], "SustainedClockSpeedInGhz": 2.5 }, "VCpuInfo": { "DefaultVCpus": 1, "DefaultCores": 1, "DefaultThreadsPerCore": 1, "ValidCores": [ 1 ], "ValidThreadsPerCore": [ 1 ] }, "MemoryInfo": { "SizeInMiB": 1024 }, "InstanceStorageSupported": false, "EbsInfo": { "EbsOptimizedSupport": "unsupported", "EncryptionSupport": "supported" }, "NetworkInfo": { "NetworkPerformance": "Low to Moderate", "MaximumNetworkInterfaces": 2, "Ipv4AddressesPerInterface": 2, "Ipv6AddressesPerInterface": 2, "Ipv6Supported": true, "EnaSupport": "unsupported" }, "PlacementGroupInfo": { "SupportedStrategies": [ "partition", "spread" ] }, "HibernationSupported": false, "BurstablePerformanceSupported": true, "DedicatedHostsSupported": false, "AutoRecoverySupported": true } ] }

Para obter mais informações, consulte Tipos de instância no Guia do usuário do Amazon Elastic Compute Cloud para instâncias Linux.

Exemplo 2: filtrar os tipos de instância disponíveis

Você pode especificar um filtro para definir o escopo dos resultados para os tipos de instância que tenham uma característica específica. O exemplo describe-instance-types a seguir lista os tipos de instância compatíveis com hibernação.

aws ec2 describe-instance-types \ --filters Name=hibernation-supported,Values=true --query 'InstanceTypes[*].InstanceType'

Saída:

[ "m5.8xlarge", "r3.large", "c3.8xlarge", "r5.large", "m4.4xlarge", "c4.large", "m5.xlarge", "m4.xlarge", "c3.large", "c4.8xlarge", "c4.4xlarge", "c5.xlarge", "c5.12xlarge", "r5.4xlarge", "c5.4xlarge" ]

Para obter mais informações, consulte Tipos de instância no Guia do usuário do Amazon Elastic Compute Cloud para instâncias Linux.

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.

/** * Asynchronously retrieves the instance types available in the current AWS region. * <p> * This method uses the AWS SDK's asynchronous API to fetch the available instance types * and then processes the response. It logs the memory information, network information, * and instance type for each instance type returned. Additionally, it returns a * {@link CompletableFuture} that resolves to the instance type string for the "t2.2xlarge" * instance type, if it is found in the response. If the "t2.2xlarge" instance type is not * found, an empty string is returned. * </p> * * @return a {@link CompletableFuture} that resolves to the instance type string for the * "t2.2xlarge" instance type, or an empty string if the instance type is not found */ public CompletableFuture<String> getInstanceTypesAsync() { DescribeInstanceTypesRequest typesRequest = DescribeInstanceTypesRequest.builder() .maxResults(10) .build(); CompletableFuture<DescribeInstanceTypesResponse> response = getAsyncClient().describeInstanceTypes(typesRequest); response.whenComplete((resp, ex) -> { if (resp != null) { List<InstanceTypeInfo> instanceTypes = resp.instanceTypes(); for (InstanceTypeInfo type : instanceTypes) { logger.info("The memory information of this type is " + type.memoryInfo().sizeInMiB()); logger.info("Network information is " + type.networkInfo().toString()); logger.info("Instance type is " + type.instanceType().toString()); } } else { throw (RuntimeException) ex; } }); return response.thenApply(resp -> { for (InstanceTypeInfo type : resp.instanceTypes()) { String instanceType = type.instanceType().toString(); if (instanceType.equals("t2.2xlarge")) { return instanceType; } } return ""; }); }
JavaScript
SDKpara JavaScript (v3)
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 { EC2Client, paginateDescribeInstanceTypes } from "@aws-sdk/client-ec2"; /** * Describes the specified instance types. By default, all instance types for the * current Region are described. Alternatively, you can filter the results. * @param {{ pageSize: string, supportedArch: string[], freeTier: boolean }} options */ export const main = async ({ pageSize, supportedArch, freeTier }) => { pageSize = parseInt(pageSize); const client = new EC2Client({}); // The paginate function is a wrapper around the underlying command. const paginator = paginateDescribeInstanceTypes( // Without limiting the page size, this call can take a long time. pageSize is just sugar for // the MaxResults property in the underlying command. { client, pageSize }, { Filters: [ { Name: "processor-info.supported-architecture", Values: supportedArch, }, { Name: "free-tier-eligible", Values: [freeTier ? "true" : "false"] }, ], }, ); try { /** * @type {import('@aws-sdk/client-ec2').InstanceTypeInfo[]} */ const instanceTypes = []; for await (const page of paginator) { if (page.InstanceTypes.length) { instanceTypes.push(...page.InstanceTypes); // When we have at least 1 result, we can stop. if (instanceTypes.length >= 1) { break; } } } console.log( `Memory size in MiB for matching instance types:\n\n${instanceTypes.map((it) => `${it.InstanceType}: ${it.MemoryInfo.SizeInMiB} MiB`).join("\n")}`, ); } catch (caught) { if (caught instanceof Error && caught.name === "InvalidParameterValue") { console.warn(`${caught.message}`); return []; } throw caught; } };
Kotlin
SDKpara Kotlin
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.

// Get a list of instance types. suspend fun getInstanceTypesSc(): String { var instanceType = "" val filterObs = ArrayList<Filter>() val filter = Filter { name = "processor-info.supported-architecture" values = listOf("arm64") } filterObs.add(filter) val typesRequest = DescribeInstanceTypesRequest { filters = filterObs maxResults = 10 } Ec2Client { region = "us-west-2" }.use { ec2 -> val response = ec2.describeInstanceTypes(typesRequest) response.instanceTypes?.forEach { type -> println("The memory information of this type is ${type.memoryInfo?.sizeInMib}") println("Maximum number of network cards is ${type.networkInfo?.maximumNetworkCards}") instanceType = type.instanceType.toString() } return instanceType } }
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.

class InstanceWrapper: """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) instance actions.""" def __init__(self, ec2_resource, instance=None): """ :param ec2_resource: A Boto3 Amazon EC2 resource. This high-level resource is used to create additional high-level objects that wrap low-level Amazon EC2 service actions. :param instance: A Boto3 Instance object. This is a high-level object that wraps instance actions. """ self.ec2_resource = ec2_resource self.instance = instance @classmethod def from_resource(cls): ec2_resource = boto3.resource("ec2") return cls(ec2_resource) def get_instance_types(self, architecture): """ Gets instance types that support the specified architecture and are designated as either 'micro' or 'small'. When an instance is created, the instance type you specify must support the architecture of the AMI you use. :param architecture: The kind of architecture the instance types must support, such as 'x86_64'. :return: A list of instance types that support the specified architecture and are either 'micro' or 'small'. """ try: inst_types = [] it_paginator = self.ec2_resource.meta.client.get_paginator( "describe_instance_types" ) for page in it_paginator.paginate( Filters=[ { "Name": "processor-info.supported-architecture", "Values": [architecture], }, {"Name": "instance-type", "Values": ["*.micro", "*.small"]}, ] ): inst_types += page["InstanceTypes"] except ClientError as err: logger.error( "Couldn't get instance types. Here's why: %s: %s", err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return inst_types
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.

/// List instance types that match an image's architecture and are free tier eligible. pub async fn list_instance_types(&self, image: &Image) -> Result<Vec<InstanceType>, EC2Error> { let architecture = format!( "{}", image.architecture().ok_or_else(|| EC2Error::new(format!( "Image {:?} does not have a listed architecture", image.image_id() )))? ); let free_tier_eligible_filter = Filter::builder() .name("free-tier-eligible") .values("false") .build(); let supported_architecture_filter = Filter::builder() .name("processor-info.supported-architecture") .values(architecture) .build(); let response = self .client .describe_instance_types() .filters(free_tier_eligible_filter) .filters(supported_architecture_filter) .send() .await?; Ok(response .instance_types .unwrap_or_default() .into_iter() .filter_map(|iti| iti.instance_type) .collect()) }