Chatwithcloud logo

ChatWithCloud

AWS GenAI Tools

JavaScript code to query for AWS Reserved EC2 Instances That Are About to Expire.

The following piece of code will help you fetch the list of Reserved Instances (RI) that are about to expire using AWS SDK for JavaScript in Node.js.

const AWS = require('aws-sdk'); const EC2 = new AWS.EC2({apiVersion: '2016-11-15'}); async function fetchExpiringReservations() { var params = {Filters: [{Name: 'state', Values: ['active']}]}; let reservations = await EC2.describeReservedInstances(params).promise(); let expiringReservations = reservations.ReservedInstances.filter(ri => (new Date(ri.End) - new Date())/(1000*60*60*24) < 30); console.log(expiringReservations); }

Detailed Code Explanation

We start by importing the aws-sdk and creating a new instance of the EC2 service.

The function fetchExpiringReservations is then defined to fetch the Reserved Instances (RIs) that are about to expire in the next 30 days. In this function, we first define the parameters for the API call using AWS's SDK, specifying that we want to fetch the active reserved instances with the describeReservedInstances method.

The .describeReservedInstances(params).promise() function retrieves all active RIs. This is an async function and we await the result.

Finally, we filter the instances less than 30 days to expiration using the filter method. The filtered result is then logged in the console.

Expected Output Format

Here's what you should expect as the output of the fetchExpiringReservations function above, logged to the console:

[ { "ReservedInstancesId": "12345678-1234-1234-1234-123456789012", "InstanceType": "t2.medium", "AvailabilityZone": "us-west-2a", "Start": "2022-02-22T09:32:36.000Z", "End": "2022-05-22T09:32:31.000Z", "Duration": 31536000, "FixedPrice": 0.0, "UsagePrice": 0.0, "CurrencyCode": "USD", "InstanceCount": 1, "ProductDescription": "Linux/UNIX", "State": "active", "InstanceTenancy": "default", "OfferingClass": "standard", "OfferingType": "No Upfront", "Scope": "Availability Zone", "RecurringCharges": [], "Tags": [] } ]

Considerations & Caveats

The EC2.describeReservedInstances API used here returns paginated results, so for a large number of Reserved Instances, this API call might need to be called multiple times with the NextToken parameter to retrieve all the data.

Also, please take into account the date/time differences due to the timezone. The AWS API returns dates and times in UTC.

Required IAM Permissions and Example Policy

The following AWS IAM policy should be added to the IAM user, group, or role running the script. This policy will allow the DescribeReservedInstances action on EC2 resources:

{ "Version": "2012-10-17", "Statement": [ { "Sid": "VisualEditor0", "Effect": "Allow", "Action": "ec2:DescribeReservedInstances", "Resource": "*" } ] }

Frequently Asked Questions

1. How can I adjust the code to check for RIs expiring in a different timeframe?

You can change the number of days in this line (new Date(ri.End) - new Date())/(1000*60*60*24) < 30 to your desired number.

2. Why do I need to use promises and async/await?

Promises and async/await are features of modern JavaScript that allows for more readable asynchronous code. Promises simplify deferred and asynchronous computations which is a way of saying "I complete part of this task now, and the rest of it later".

3. What do I do if I get a message saying the IAM policy is not sufficient?

Check that the policy given has been applied correctly to the IAM user/group/role. Ensure the user/group/role executing the function has this policy. If you're assuming a role, check the trust policy and permissions as well.

4. Why am I getting incomplete results?

If you are having more than 1000 active RIs, AWS API will paginate the results. You can use the NextToken parameter to make additional calls to retrieve all data.





Related articles
Step By Step Troubleshoot Why My Route53 Domain and Cloudfront Distribution Is Not Working