Gunakan DescribeImages dengan AWS SDK atau CLI - AWS SDKContoh Kode

Ada lebih banyak AWS SDK contoh yang tersedia di GitHub repo SDKContoh AWS Dokumen.

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

Gunakan DescribeImages dengan AWS SDK atau CLI

Contoh kode berikut menunjukkan cara menggunakanDescribeImages.

Contoh tindakan adalah kutipan kode dari program yang lebih besar dan harus dijalankan dalam konteks. Anda dapat melihat tindakan ini dalam konteks dalam contoh kode berikut:

Bash
AWS CLI dengan skrip Bash
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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 }

Fungsi utilitas yang digunakan dalam contoh ini.

############################################################################### # 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 }
  • Untuk API detailnya, lihat DescribeImagesdi Referensi AWS CLI Perintah.

CLI
AWS CLI

Contoh 1: Untuk menggambarkan AMI

describe-imagesContoh berikut menjelaskan yang ditentukan AMI di Wilayah tertentu.

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

Output:

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

Untuk informasi selengkapnya, lihat Amazon Machine Images (AMI) di Panduan EC2 Pengguna Amazon.

Contoh 2: Untuk mendeskripsikan AMIs berdasarkan filter

describe-imagesContoh berikut menjelaskan Windows AMIs yang disediakan oleh Amazon yang didukung oleh AmazonEBS.

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

Untuk contoh output describe-images, lihat Contoh 1.

Untuk contoh tambahan menggunakan filter, lihat Mencantumkan dan memfilter sumber daya Anda di Panduan EC2 Pengguna Amazon.

Contoh 3: Untuk mendeskripsikan AMIs berdasarkan tag

describe-imagesContoh berikut menjelaskan semua AMIs yang memiliki tagType=Custom. Contoh menggunakan --query parameter untuk menampilkan hanya AMIIDs.

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

Output:

ami-1234567890EXAMPLE ami-0abcdef1234567890

Untuk contoh tambahan menggunakan filter tag, lihat Bekerja dengan tag di Panduan EC2 Pengguna Amazon.

  • Untuk API detailnya, lihat DescribeImagesdi Referensi AWS CLI Perintah.

JavaScript
SDKuntuk JavaScript (v3)
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

import { EC2Client, paginateDescribeImages } from "@aws-sdk/client-ec2"; /** * Describes the specified images (AMIs, AKIs, and ARIs) available to you or all of the images available to you. * @param {{ architecture: string, pageSize: number }} options */ export const main = async ({ architecture, pageSize }) => { pageSize = parseInt(pageSize); const client = new EC2Client({}); // 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 }, { // 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: [architecture] }], }, ); /** * @type {import('@aws-sdk/client-ec2').Image[]} */ const images = []; let recordsScanned = 0; try { for await (const page of paginator) { recordsScanned += pageSize; if (page.Images.length) { images.push(...page.Images); break; } else { console.log( `No matching image found yet. Searched ${recordsScanned} records.`, ); } } if (images.length) { console.log( `Found ${images.length} images:\n\n${images.map((image) => image.Name).join("\n")}\n`, ); } else { console.log( `No matching images found. Searched ${recordsScanned} records.\n`, ); } return images; } catch (caught) { if (caught instanceof Error && caught.name === "InvalidParameterValue") { console.warn(`${caught.message}`); return []; } throw caught; } };
  • Untuk API detailnya, lihat DescribeImagesdi AWS SDK for JavaScript APIReferensi.

PowerShell
Alat untuk PowerShell

Contoh 1: Contoh ini menjelaskan yang ditentukanAMI.

Get-EC2Image -ImageId ami-12345678

Output:

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

Contoh 2: Contoh ini menggambarkan AMIs yang Anda miliki.

Get-EC2Image -owner self

Contoh 3: Contoh ini menjelaskan publik AMIs yang menjalankan Microsoft Windows Server.

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

Contoh 4: Contoh ini menjelaskan semua publik AMIs di wilayah 'us-west-2'.

Get-EC2Image -Region us-west-2
  • Untuk API detailnya, lihat DescribeImagesdi AWS Tools for PowerShell Referensi Cmdlet.

Python
SDKuntuk Python (Boto3)
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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
Rust
SDKuntuk Rust
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode AWS.

pub async fn list_images(&self, ids: Vec<Parameter>) -> Result<Vec<Image>, EC2Error> { let image_ids = ids.into_iter().filter_map(|p| p.value).collect(); let output = self .client .describe_images() .set_image_ids(Some(image_ids)) .send() .await?; let images = output.images.unwrap_or_default(); if images.is_empty() { Err(EC2Error::new("No images for selected AMIs")) } else { Ok(images) } }

Menggunakan fungsi list_images dengan SSM to limit berdasarkan lingkungan Anda. Untuk detail lebih lanjut tentangSSM, lihat https://docs.aws.amazon.com/systems-manager/ GetParameters terbaru/userguide/example_ssm_ _section.html.

async fn find_image(&mut self) -> Result<ScenarioImage, EC2Error> { let params: Vec<Parameter> = self .ssm .list_path("/aws/service/ami-amazon-linux-latest") .await .map_err(|e| e.add_message("Could not find parameters for available images"))? .into_iter() .filter(|param| param.name().is_some_and(|name| name.contains("amzn2"))) .collect(); let amzn2_images: Vec<ScenarioImage> = self .ec2 .list_images(params) .await .map_err(|e| e.add_message("Could not find images"))? .into_iter() .map(ScenarioImage::from) .collect(); println!("We will now create an instance from an Amazon Linux 2 AMI"); let ami = self.util.select_scenario_image(amzn2_images)?; Ok(ami) }