Skip to content

Instantly share code, notes, and snippets.

@saeedvaziry
Created May 10, 2024 16:46
Show Gist options
  • Save saeedvaziry/1e0b9678ba7b35e0123af8e47a51cb1b to your computer and use it in GitHub Desktop.
Save saeedvaziry/1e0b9678ba7b35e0123af8e47a51cb1b to your computer and use it in GitHub Desktop.
Get AWS AMI Image IDs for Ubuntu
<?php
$supportedRegions = [
'ap-east-1',
'ap-northeast-1',
'ap-northeast-2',
'ap-northeast-3',
'ap-south-1',
'ap-south-2',
'ap-southeast-1',
'ap-southeast-2',
'ap-southeast-3',
'ap-southeast-4',
'ca-central-1',
'cn-north-1',
'cn-northwest-1',
'eu-central-1',
'eu-central-2',
'eu-north-1',
'eu-south-1',
'eu-south-2',
'eu-west-1',
'eu-west-2',
'eu-west-3',
'il-central-1',
'me-central-1',
'me-south-1',
'sa-east-1',
'us-east-1',
'us-east-2',
'us-west-1',
'us-west-2',
];
$url = 'https://cloud-images.ubuntu.com/locator/ec2/releasesTable';
// Initialize a cURL session
$ch = curl_init();
// Set cURL options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // This is used for HTTPS requests, if necessary
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
// Execute cURL session and get the response
$response = curl_exec($ch);
// Check for cURL errors
if (curl_errno($ch)) {
exit('Curl error: '.curl_error($ch));
}
// Close cURL session
curl_close($ch);
// Decode JSON response
$data = json_decode($response, true);
// Check if the 'aaData' key exists
if (! isset($data['aaData'])) {
exit('Invalid data received');
}
// Initialize an array to store the results
$regions = [];
foreach ($data['aaData'] as $item) {
$region = $item[0];
$description = $item[1];
$release = $item[2];
$architecture = $item[3];
$amiLinkHtml = $item[6];
// Continue only if the region is supported
if (! in_array($region, $supportedRegions)) {
continue;
}
// Continue only if architecture includes 'amd64'
if (! str_contains($architecture, 'amd64')) {
continue;
}
// Parse the AMI ID from HTML link
preg_match('/ami-[a-z0-9]+/', $amiLinkHtml, $matches);
if (empty($matches)) {
continue;
}
$amiId = $matches[0];
// Filter for Ubuntu 20, 22, 24
if (str_contains($release, '20.04')) {
$versionKey = 'ubuntu_20';
} elseif (str_contains($release, '22.04')) {
$versionKey = 'ubuntu_22';
} elseif (str_contains($release, '24.04')) {
$versionKey = 'ubuntu_24';
} else {
continue; // Skip other versions
}
// Fill the regions array appropriately
if (! isset($regions[$region])) {
$regions[$region] = [];
}
$regions[$region][$versionKey] = $amiId;
}
// Print the resultant array
var_export($regions);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment