Amazon EC2: Find AMIs by Owner and Architecture
See more Amazon EC2 Examples
List available x86_64, HVM, EBS-backed images owned by your account. Set ownerId to a trusted publisher account ID for its images. Do not trust an image merely because its name looks familiar. Verify licensing, OS support, architecture, and application compatibility before launch. IDs are regional. Results are not sorted newest-first; review creationDate rather than taking the first match.
Follows nextToken even after an empty page. Tokens are opaque strings; replace the previous NextToken rather than adding duplicates. A repeated token or the 1000-page demonstration bound reports incomplete results. Pages are not an atomic snapshot, and response order is not guaranteed.
Uses the current EC2 Query API (Version=2016-11-15) over HTTPS. Chilkat.Rest and AuthAws sign the GET request with AWS Signature Version 4, service ec2. Set the region once; the code builds the corresponding commercial AWS endpoint. Other partitions require their own endpoint suffix. EC2 returns XML, unlike DynamoDB's JSON protocol. AddQueryParam encodes parameter values.
Load current IAM credentials from a private qa_data/aws/ec2.json with string fields access_key, secret_key, and, for temporary credentials, session_token. Prefer short-lived role credentials. The example explicitly reads this file; it does not discover profiles or refresh expired credentials. The session token is included in the signed query, so keep URLs and diagnostics private. A Socket enables TLS certificate verification before handing its connection to Rest.
IAM permissions for the illustrated requests: ec2:DescribeImages. Use least-privilege permissions for the intended resources; EC2 describe operations generally require Resource *.
Transport completion, HTTP status, and XML validity are checked separately. API errors contain Errors/Error/Code and RequestID; successful responses use requestId. Check the error code rather than assuming every HTTP 4xx means bad input. Use bounded exponential backoff with jitter for retryable failures. EC2 is eventually consistent: a recent resource change may not appear immediately. Verify account, region, ID, and observed state before retrying a change whose outcome is uncertain.
Chilkat PHP ActiveX Downloads
<?php
// Assumes Chilkat is unlocked. See Global Unlock Sample.
$success = 0;
// Private configuration, not a file in public web content or source control.
// Load current IAM credentials authorized for the EC2 operation.
$credentials = new COM("Chilkat.JsonObject");
$credentials->Strict = 1;
$success = $credentials->LoadFile('qa_data/aws/ec2.json');
if ($success != 1) {
print 'Could not load private AWS credentials.' . "\n";
exit;
}
if (($credentials->JsonTypeOf('access_key') != 1) or ($credentials->stringOf('access_key') == '')) {
print 'Missing or invalid access_key.' . "\n";
exit;
}
if (($credentials->JsonTypeOf('secret_key') != 1) or ($credentials->stringOf('secret_key') == '')) {
print 'Missing or invalid secret_key.' . "\n";
exit;
}
// Set this once to the region containing the instances.
$region = 'us-west-2';
$endpoint = new COM("Chilkat.StringBuilder");
$endpoint->Append('ec2.');
$endpoint->Append($region);
$endpoint->Append('.amazonaws.com');
$aws = new COM("Chilkat.AuthAws");
$aws->AccessKey = $credentials->stringOf('access_key');
$aws->SecretKey = $credentials->stringOf('secret_key');
$aws->Region = $region;
$aws->ServiceName = 'ec2';
$aws->SignatureVersion = 4;
$rest = new COM("Chilkat.Rest");
$rest->ConnectTimeoutMs = 20000;
$rest->IdleTimeoutMs = 60000;
$success = $rest->SetAuthAws($aws);
if ($success != 1) {
print 'Could not configure AWS signing.' . "\n";
exit;
}
// Temporary IAM/STS credentials require their session token on every signed request.
// AddQueryParam includes it in SigV4's canonical query. Never log the request URL.
// Leave session_token absent or empty only for credentials that do not have one.
if ($credentials->HasMember('session_token') == 1) {
if ($credentials->JsonTypeOf('session_token') != 1) {
print 'session_token must be a string.' . "\n";
exit;
}
if ($credentials->stringOf('session_token') != '') {
$success = $rest->AddQueryParam('X-Amz-Security-Token',$credentials->stringOf('session_token'));
if ($success != 1) {
print 'Could not set the session-token parameter.' . "\n";
exit;
}
}
}
// Supply a Socket to explicitly enable TLS certificate verification.
$connection = new COM("Chilkat.Socket");
$connection->RequireSslCertVerify = 1;
$connection->MaxReadIdleMs = 60000;
$connection->MaxSendIdleMs = 60000;
$success = $connection->Connect($endpoint->getAsString(),443,1,20000);
if ($success != 1) {
print 'TLS connection failed; inspect diagnostics privately.' . "\n";
exit;
}
$success = $rest->UseConnection($connection,1);
if ($success != 1) {
print 'Could not attach the TLS connection.' . "\n";
exit;
}
// EC2 uses the Query API and XML responses, not AWS JSON protocol headers.
// AddQueryParam URL-encodes the values; do not pre-encode IDs or tokens.
$xml = new COM("Chilkat.Xml");
$xml->Strict = 1;
$success = $rest->AddQueryParam('Version','2016-11-15');
if ($success != 1) {
print 'Could not set Version.' . "\n";
exit;
}
$responseXml = '';
$errorCode = '';
// Choose a trusted owner's account ID, or "self" for your own images.
$ownerId = 'self';
$i = 0;
$success = $rest->AddQueryParam('Action','DescribeImages');
if ($success != 1) {
print 'Could not set Action.' . "\n";
exit;
}
$success = $rest->AddQueryParam('Owner.1',$ownerId);
if ($success != 1) {
print 'Could not set Owner.1.' . "\n";
exit;
}
$success = $rest->AddQueryParam('Filter.1.Name','architecture');
if ($success != 1) {
print 'Could not set Filter.1.Name.' . "\n";
exit;
}
$success = $rest->AddQueryParam('Filter.1.Value.1','x86_64');
if ($success != 1) {
print 'Could not set Filter.1.Value.1.' . "\n";
exit;
}
$success = $rest->AddQueryParam('Filter.2.Name','root-device-type');
if ($success != 1) {
print 'Could not set Filter.2.Name.' . "\n";
exit;
}
$success = $rest->AddQueryParam('Filter.2.Value.1','ebs');
if ($success != 1) {
print 'Could not set Filter.2.Value.1.' . "\n";
exit;
}
$success = $rest->AddQueryParam('Filter.3.Name','virtualization-type');
if ($success != 1) {
print 'Could not set Filter.3.Name.' . "\n";
exit;
}
$success = $rest->AddQueryParam('Filter.3.Value.1','hvm');
if ($success != 1) {
print 'Could not set Filter.3.Value.1.' . "\n";
exit;
}
$success = $rest->AddQueryParam('Filter.4.Name','state');
if ($success != 1) {
print 'Could not set Filter.4.Name.' . "\n";
exit;
}
$success = $rest->AddQueryParam('Filter.4.Value.1','available');
if ($success != 1) {
print 'Could not set Filter.4.Value.1.' . "\n";
exit;
}
$success = $rest->AddQueryParam('MaxResults','100');
if ($success != 1) {
print 'Could not set MaxResults.' . "\n";
exit;
}
$seenTokens = new COM("Chilkat.Hashtable");
$nextToken = '';
$more = 1;
$page = 0;
while (($more == 1)) {
if ($page == 1000) {
print 'Page limit reached; enumeration is incomplete. Retain nextToken privately to resume.' . "\n";
exit;
}
$responseXml = $rest->fullRequestNoBody('GET','/');
if ($rest->LastMethodSuccess != 1) {
print 'Request did not complete; inspect diagnostics privately.' . "\n";
exit;
}
$success = $xml->LoadXml($responseXml);
if ($rest->ResponseStatusCode != 200) {
print 'EC2 HTTP status: ' . $rest->ResponseStatusCode . "\n";
if ($success == 1) {
if ($xml->HasChildWithTag('Errors|Error|Code') == 1) {
$errorCode = $xml->getChildContent('Errors|Error|Code');
print 'AWS error code: ' . $errorCode . "\n";
}
if ($xml->HasChildWithTag('RequestID') == 1) {
print 'AWS request ID: ' . $xml->getChildContent('RequestID') . "\n";
}
}
// Keep full error messages and signed request diagnostics private.
// UnauthorizedOperation is not a successful dry run. Check IAM permissions.
// Retry throttled reads with bounded backoff; renew expired credentials.
exit;
}
if ($success != 1) {
print 'Expected a well-formed XML response.' . "\n";
exit;
}
if ($xml->Tag != 'DescribeImagesResponse') {
print 'Unexpected EC2 response element.' . "\n";
exit;
}
if (($xml->HasChildWithTag('requestId') != 1) or ($xml->getChildContent('requestId') == '')) {
print 'Missing or empty requestId.' . "\n";
exit;
}
print 'AWS request ID: ' . $xml->getChildContent('requestId') . "\n";
if ($xml->HasChildWithTag('imagesSet') != 1) {
print 'Expected imagesSet.' . "\n";
exit;
}
$i = 0;
while (($i < $xml->NumChildrenAt('imagesSet'))) {
$xml->I = $i;
if (($xml->HasChildWithTag('imagesSet|item[i]|imageId') != 1) or ($xml->getChildContent('imagesSet|item[i]|imageId') == '')) {
print 'Missing or empty imagesSet|item[i]|imageId.' . "\n";
exit;
}
print 'AMI ID: ' . $xml->getChildContent('imagesSet|item[i]|imageId') . "\n";
if ($xml->HasChildWithTag('imagesSet|item[i]|name') == 1) {
print 'Name: ' . $xml->getChildContent('imagesSet|item[i]|name') . "\n";
}
if ($xml->HasChildWithTag('imagesSet|item[i]|imageOwnerId') == 1) {
print 'Owner: ' . $xml->getChildContent('imagesSet|item[i]|imageOwnerId') . "\n";
}
if ($xml->HasChildWithTag('imagesSet|item[i]|architecture') == 1) {
print 'Architecture: ' . $xml->getChildContent('imagesSet|item[i]|architecture') . "\n";
}
if ($xml->HasChildWithTag('imagesSet|item[i]|creationDate') == 1) {
print 'Created: ' . $xml->getChildContent('imagesSet|item[i]|creationDate') . "\n";
}
if ($xml->HasChildWithTag('imagesSet|item[i]|rootDeviceType') == 1) {
print 'Root device: ' . $xml->getChildContent('imagesSet|item[i]|rootDeviceType') . "\n";
}
if ($xml->HasChildWithTag('imagesSet|item[i]|imageState') == 1) {
print 'State: ' . $xml->getChildContent('imagesSet|item[i]|imageState') . "\n";
}
if ($xml->HasChildWithTag('imagesSet|item[i]|deprecationTime') == 1) {
print 'Deprecated after: ' . $xml->getChildContent('imagesSet|item[i]|deprecationTime') . "\n";
}
if ($xml->HasChildWithTag('imagesSet|item[i]|imageAllowed') == 1) {
print 'Allowed AMI: ' . $xml->getChildContent('imagesSet|item[i]|imageAllowed') . "\n";
}
$i = $i + 1;
}
$page = $page + 1;
$more = 0;
$nextToken = '';
if ($xml->HasChildWithTag('nextToken') == 1) {
$nextToken = $xml->getChildContent('nextToken');
}
if ($nextToken != '') {
if ($seenTokens->Contains($nextToken) == 1) {
print 'Repeated pagination token; enumeration is incomplete.' . "\n";
exit;
}
$success = $seenTokens->AddInt($nextToken,1);
if ($success != 1) {
print 'Could not track pages.' . "\n";
exit;
}
if ($page > 1) {
$success = $rest->RemoveQueryParam('NextToken');
if ($success != 1) {
print 'Could not replace pagination token.' . "\n";
exit;
}
}
$success = $rest->AddQueryParam('NextToken',$nextToken);
if ($success != 1) {
print 'Could not set NextToken.' . "\n";
exit;
}
$more = 1;
}
}
print 'Enumeration complete.' . "\n";
?>