Utilícelo DescribeImages con un o AWS SDK CLI - Ejemplos de código de AWS SDK

Hay más AWS SDK ejemplos disponibles en el GitHub repositorio de AWS Doc SDK Examples.

Las traducciones son generadas a través de traducción automática. En caso de conflicto entre la traducción y la version original de inglés, prevalecerá la version en inglés.

Utilícelo DescribeImages con un o AWS SDK CLI

En los siguientes ejemplos de código, se muestra cómo utilizar DescribeImages.

Los ejemplos de acciones son extractos de código de programas más grandes y deben ejecutarse en contexto. Puede ver esta acción en contexto en el siguiente ejemplo de código:

Bash
AWS CLI con script Bash
nota

Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

############################################################################### # function ec2_describe_images # # This function describes one or more Amazon Elastic Compute Cloud (Amazon EC2) images. # # Parameters: # -i image_ids - A space-separated list of image IDs (optional). # -h - Display help. # # And: # 0 - If successful. # 1 - If it fails. ############################################################################### function ec2_describe_images() { local image_ids response local option OPTARG # Required to use getopts command in a function. # bashsupport disable=BP5008 function usage() { echo "function ec2_describe_images" echo "Describes one or more Amazon Elastic Compute Cloud (Amazon EC2) images." echo " -i image_ids - A space-separated list of image IDs (optional)." echo " -h - Display help." echo "" } # Retrieve the calling parameters. while getopts "i:h" option; do case "${option}" in i) image_ids="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 local aws_cli_args=() if [[ -n "$image_ids" ]]; then # shellcheck disable=SC2206 aws_cli_args+=("--image-ids" $image_ids) fi response=$(aws ec2 describe-images \ "${aws_cli_args[@]}" \ --query 'Images[*].[Description,Architecture,ImageId]' \ --output text) || { aws_cli_error_log ${?} errecho "ERROR: AWS reports describe-images operation failed.$response" return 1 } echo "$response" return 0 }

Las funciones de utilidad utilizadas en este ejemplo.

############################################################################### # 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 }
  • Para API obtener más información, consulte DescribeImagesla Referencia de AWS CLI comandos.

CLI
AWS CLI

Ejemplo 1: Para describir un AMI

El siguiente describe-images ejemplo describe lo especificado AMI en la región especificada.

aws ec2 describe-images \ --region us-east-1 \ --image-ids ami-1234567890EXAMPLE

Salida:

{ "Images": [ { "VirtualizationType": "hvm", "Description": "Provided by Red Hat, Inc.", "PlatformDetails": "Red Hat Enterprise Linux", "EnaSupport": true, "Hypervisor": "xen", "State": "available", "SriovNetSupport": "simple", "ImageId": "ami-1234567890EXAMPLE", "UsageOperation": "RunInstances:0010", "BlockDeviceMappings": [ { "DeviceName": "/dev/sda1", "Ebs": { "SnapshotId": "snap-111222333444aaabb", "DeleteOnTermination": true, "VolumeType": "gp2", "VolumeSize": 10, "Encrypted": false } } ], "Architecture": "x86_64", "ImageLocation": "123456789012/RHEL-8.0.0_HVM-20190618-x86_64-1-Hourly2-GP2", "RootDeviceType": "ebs", "OwnerId": "123456789012", "RootDeviceName": "/dev/sda1", "CreationDate": "2019-05-10T13:17:12.000Z", "Public": true, "ImageType": "machine", "Name": "RHEL-8.0.0_HVM-20190618-x86_64-1-Hourly2-GP2" } ] }

Para obtener más información, consulte Amazon Machine Images (AMI) en la Guía del EC2 usuario de Amazon.

Ejemplo 2: Para describir AMIs en función de filtros

El siguiente describe-images ejemplo describe los Windows AMIs proporcionados por Amazon y respaldados por AmazonEBS.

aws ec2 describe-images \ --owners amazon \ --filters "Name=platform,Values=windows" "Name=root-device-type,Values=ebs"

Para ver un ejemplo del resultado de describe-images, consulte el ejemplo 1.

Para ver ejemplos adicionales de uso de filtros, consulta Cómo publicar y filtrar tus recursos en la Guía del EC2 usuario de Amazon.

Ejemplo 3: Describir AMIs en función de las etiquetas

El siguiente describe-images ejemplo describe todos los AMIs que tienen la etiquetaType=Custom. En el ejemplo se utiliza el --query parámetro para mostrar solo el AMIIDs.

aws ec2 describe-images \ --filters "Name=tag:Type,Values=Custom" \ --query 'Images[*].[ImageId]' \ --output text

Salida:

ami-1234567890EXAMPLE ami-0abcdef1234567890

Para ver más ejemplos de uso de filtros de etiquetas, consulta Cómo trabajar con etiquetas en la Guía del EC2 usuario de Amazon.

  • Para API obtener más información, consulte DescribeImagesla Referencia de AWS CLI comandos.

JavaScript
SDKpara JavaScript (v3)
nota

Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

import { paginateDescribeImages } from "@aws-sdk/client-ec2"; import { client } from "../libs/client.js"; // List at least the first i386 image available for EC2 instances. export const main = async () => { // The paginate function is a wrapper around the base command. const paginator = paginateDescribeImages( // Without limiting the page size, this call can take a long time. pageSize is just sugar for // the MaxResults property in the base command. { client, pageSize: 25 }, { // There are almost 70,000 images available. Be specific with your filtering // to increase efficiency. // See https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-ec2/interfaces/describeimagescommandinput.html#filters Filters: [{ Name: "architecture", Values: ["x86_64"] }], }, ); try { const arm64Images = []; for await (const page of paginator) { if (page.Images.length) { arm64Images.push(...page.Images); // Once we have at least 1 result, we can stop. if (arm64Images.length >= 1) { break; } } } console.log(arm64Images); } catch (err) { console.error(err); } };
  • Para API obtener más información, consulte DescribeImagesla AWS SDK for JavaScript APIReferencia.

PowerShell
Herramientas para PowerShell

Ejemplo 1: En este ejemplo se describe lo especificadoAMI.

Get-EC2Image -ImageId ami-12345678

Salida:

Architecture : x86_64 BlockDeviceMappings : {/dev/xvda} CreationDate : 2014-10-20T00:56:28.000Z Description : My image Hypervisor : xen ImageId : ami-12345678 ImageLocation : 123456789012/my-image ImageOwnerAlias : ImageType : machine KernelId : Name : my-image OwnerId : 123456789012 Platform : ProductCodes : {} Public : False RamdiskId : RootDeviceName : /dev/xvda RootDeviceType : ebs SriovNetSupport : simple State : available StateReason : Tags : {Name} VirtualizationType : hvm

Ejemplo 2: En este ejemplo se describe lo AMIs que tienes.

Get-EC2Image -owner self

Ejemplo 3: En este ejemplo se describe el público AMIs que ejecuta Microsoft Windows Server.

Get-EC2Image -Filter @{ Name="platform"; Values="windows" }

Ejemplo 4: En este ejemplo se describen todos los públicos AMIs de la región «us-west-2".

Get-EC2Image -Region us-west-2
  • Para API obtener más información, consulte AWS Tools for PowerShell Cmdlet DescribeImagesReference.

Python
SDKpara Python (Boto3)
nota

Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de 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_images(self, image_ids): """ Gets information about Amazon Machine Images (AMIs) from a list of AMI IDs. :param image_ids: The list of AMIs to look up. :return: A list of Boto3 Image objects that represent the requested AMIs. """ try: images = list(self.ec2_resource.images.filter(ImageIds=image_ids)) except ClientError as err: logger.error( "Couldn't get images. Here's why: %s: %s", err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return images
  • Para API obtener más información, consulte DescribeImagesla AWS SDKreferencia de Python (Boto3). API

Rust
SDKpara Rust
nota

Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

// A simple Rust program to list all Amazon images in the currently configured region. #[tokio::main] async fn main() -> Result<(), Error> { let config = aws_config::load_from_env().await; let client = Client::new(&config); let resp = client.describe_images().owners("amazon").send().await?; println!("AWS SDK for Rust v{}", PKG_VERSION); println!("Describing Amazon Machine Images (AMIs):"); let mut images: Vec<_> = resp .images() .iter() .filter(|i| { i.description() .filter(|i| i.contains("Amazon Linux AMI 2023")) .is_some() }) .collect(); images.sort_by(|a, b| a.description.cmp(&b.description)); if images.is_empty() { println!("No images found."); return Ok(()); } for image in images { let id = image.image_id().unwrap_or_default(); let description = image.description().unwrap_or_default(); println!("{id}: {description}"); } Ok(()) }
  • Para API obtener más información, consulte DescribeImagesla APIreferencia AWS SDK de Rust.