Generate a Report of EC2 Instances by Type, Running Time, and Region
This guide will walk you through how to create a list of EC2 Instances based on their types, running time, and region using AWS JavaScript Software Development Kit (SDK).
Code
const AWS = require('aws-sdk'); const ec2 = new AWS.EC2({ apiVersion: '2021-04-27', region: 'us-west-2' }); const params = { MaxResults: 100, }; ec2.describeInstances(params, function(err, data) { if (err) { console.log("Error", err.stack); } else { let instances = []; data.Reservations.forEach((res) => { res.Instances.forEach((inst) => { instances.push({ InstanceId: inst.InstanceId, InstanceType: inst.InstanceType, LaunchTime: inst.LaunchTime, Region: 'us-west-2', }); }); }); console.log(JSON.stringify(instances, null, 2)); } });
Detailed Code Explanation
We start by requiring the aws-sdk
module and creating a service object ec2
using the AWS.EC2
constructor, set to the us-west-2
region.
We then define the params
object to specify the maximum number of instances that AWS.EC2.describeInstances
should return.
The describeInstances
method is then called with params
. If an error occurs, we print the error; otherwise, we process the returned data.
We loop through each Reservation
and Instance
nested within, pushing an object containing the InstanceId
, InstanceType
, LaunchTime
, and Region
to the instances
array.
Finally, we stringify the instances
array into a pretty JSON format and log it to the console.
Expected Output Format
The expected output is an array of objects, each representing an instance, in JSON format.
[ { "InstanceId": "i-0abcdef1234567890", "InstanceType": "t2.micro", "LaunchTime": "2021-04-27T14:00:00.000Z", "Region": "us-west-2" }, {...} ]
Considerations & Caveats
- The returned information only includes instances for the specified region (in this case,
us-west-2
). - You're only returning information about a maximum of 100 instances due to the
MaxResults
parameter. - The
describeInstances
function used here retrieves information about instances whether they're running or stopped.
Required IAM Permissions and Example Policy
Your IAM user or role must have the ec2:DescribeInstances
permission. Here's an example policy that grants this permission:
{ "Version": "2012-10-17", "Statement": [ { "Sid": "VisualEditor0", "Effect": "Allow", "Action": "ec2:DescribeInstances", "Resource": "*" } ] }
FAQ
Q: Why do I need the aws-sdk
module?
A: The aws-sdk
module allows your script to interact with AWS services.
Q: Can I use this script to get details from other AWS regions?
A: Yes, you can replace us-west-2
in region: 'us-west-2'
with the desired region.
Q: What if I want more than 100 instances?
A: You can adjust MaxResults
parameter accordingly but keep in mind AWS may limit the number of instances returned in one call for API throttling reasons.
Q: Can I filter the instances by their statuses?
A: Yes, you can add Filters
to the params
object to specify the instance state.