Created
November 20, 2020 15:05
-
-
Save emmanuelnk/a4dd33646fd628e58aa479e1d36ff6b8 to your computer and use it in GitHub Desktop.
Get latest Amazon EC2 AMI image ID just like in the AWS EC2 quick launch console using Node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as AWS from "aws-sdk" | |
export const getAMIImageID = async(imageName: string): Promise<string | undefined> => { | |
AWS.config.update({ region: "us-west-2" }) | |
const ec2 = new AWS.EC2() | |
// see https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#describeImages-property | |
const params = { | |
Filters: [ | |
{ | |
Name: "block-device-mapping.volume-type", | |
Values: ["gp2"], | |
}, | |
{ | |
Name: "name", | |
Values: [imageName], | |
}, | |
{ | |
Name: "state", | |
Values: ["available"], | |
}, | |
], | |
} | |
try { | |
const data = await ec2.describeImages(params).promise() | |
const imageInfo = data.Images?.sort((a, b) => +new Date(b.CreationDate || 0) - +new Date(a.CreationDate || 0))[0] | |
return imageInfo?.ImageId | |
} catch(err) { | |
console.error(err, err.stack) | |
return | |
} | |
} | |
;(async() => { | |
// you can use wild cards in the name | |
console.log(await getAMIImageID("ubuntu*20.04-amd64-server*")) | |
// logs ami-082e4f383a98efbe9 | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment