Menu
AWS SDK for JavaScript
Developer Guide for SDK version 2.122.0

Using Regions and Availability Zones with Amazon EC2


                                            Relationship between JavaScript environments, the SDK, and Lambda

This Node.js example shows you how to retrieve descriptions for regions and Availability Zones.

The Scenario

Amazon EC2 is hosted in multiple locations worldwide. These locations are composed of regions and Availability Zones. Each region is a separate geographic area. Each region has multiple, isolated locations known as Availability Zones. Amazon EC2 provides the ability to place instances and data in multiple locations.

In this example, you use a series of Node.js modules to retrieve details about regions and Availability Zones. The Node.js modules use the SDK for JavaScript to manage instances by using the following methods of the Amazon EC2 client class:

For more information about regions and Availability Zones, see Regions and Availability Zones in the Amazon EC2 User Guide for Linux Instances or Regions and Availability Zones in the Amazon EC2 User Guide for Windows Instances.

Prerequisite Tasks

To set up and run this example, you must first complete these tasks:

Configuring the SDK

Configure the SDK for JavaScript by creating a global configuration object, setting the region, and providing credentials for your code. In this example, you use the JSON file you created to provide the credentials.

Copy
// Load the SDK for JavaScript var AWS = require('aws-sdk'); // Load credentials and set region from JSON file AWS.config.loadFromPath('./config.json');

Describing Regions and Availability Zones

Create a Node.js module with the file name ec2_describeregionsandzones.js. Be sure to configure the SDK as previously shown. To access Amazon EC2, create an AWS.EC2 service object. Create an empty JSON object to pass as parameters, which returns all available descriptions. Then call the describeRegions and describeAvailabilityZones methods.

Copy
// Load the AWS SDK for Node.js var AWS = require('aws-sdk'); // Load credentials and set region from JSON file AWS.config.loadFromPath('./config.json'); // Create EC2 service object var ec2 = new AWS.EC2({apiVersion: '2016-11-15'}); var params = {}; // Retrieves all regions/endpoints that work with EC2 ec2.describeRegions(params, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Regions: ", data.Regions); } }); // Retrieves availability zones only for region of the ec2 service object ec2.describeAvailabilityZones(params, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Availability Zones: ", data.AvailabilityZones); } });

To run the example, type the following at the command line.

Copy
node ec2_describeregionsandzones.js

This sample code can be found here on GitHub.