Verwenden Sie es DescribeInstanceTypes mit einem AWS SDK oder CLI - AWS SDKCode-Beispiele

Weitere AWS SDK Beispiele sind im Repo AWS Doc SDK Examples GitHub verfügbar.

Die vorliegende Übersetzung wurde maschinell erstellt. Im Falle eines Konflikts oder eines Widerspruchs zwischen dieser übersetzten Fassung und der englischen Fassung (einschließlich infolge von Verzögerungen bei der Übersetzung) ist die englische Fassung maßgeblich.

Verwenden Sie es DescribeInstanceTypes mit einem AWS SDK oder CLI

Die folgenden Codebeispiele zeigen, wie man es benutztDescribeInstanceTypes.

Beispiele für Aktionen sind Codeauszüge aus größeren Programmen und müssen im Kontext ausgeführt werden. Im folgenden Codebeispiel können Sie diese Aktion im Kontext sehen:

.NET
AWS SDK for .NET
Anmerkung

Es gibt noch mehr dazu GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

/// <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 mit Bash-Skript
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

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

Die in diesem Beispiel verwendeten Dienstprogrammfunktionen.

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

Beispiel 1: So beschreiben Sie einen Instance-Typ

Im folgenden describe-instance-types-Beispiel werden die Details für den angegebenen Instance-Typ angezeigt.

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

Ausgabe:

{ "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 } ] }

Weitere Informationen finden Sie unter Instance-Typen im Amazon Elastic Compute Cloud-Benutzerhandbuch für Linux-Instances.

Beispiel 2: So filtern Sie die verfügbaren Instance-Typen

Sie können einen Filter angeben, um die Ergebnisse auf Instance-Typen mit einem bestimmten Merkmal zu beschränken. Im folgenden describe-instance-types-Beispiel werden die Instance-Typen aufgeführt, die den Ruhezustand unterstützen.

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

Ausgabe:

[ "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" ]

Weitere Informationen finden Sie unter Instance-Typen im Amazon Elastic Compute Cloud-Benutzerhandbuch für Linux-Instances.

Java
SDKfür Java 2.x
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

/** * 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
SDKfür JavaScript (v3)
Anmerkung

Es gibt noch mehr dazu GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

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
SDKfür Kotlin
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

// 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
SDKfür Python (Boto3)
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

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
SDKfür Rust
Anmerkung

Es gibt noch mehr dazu GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

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