Menu
AWS SDK for JavaScript
Developer Guide for SDK v2.154.0

Using Regions and Availability Zones with Amazon EC2

JavaScript code example that applies to Node.js execution

This Node.js code example shows:

  • 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 then setting the region for your code. In this example, the region is set to us-west-2.

Copy
// Load the SDK for JavaScript var AWS = require('aws-sdk'); // Set the region AWS.config.update({region: 'us-west-2'});

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'); // Set the region AWS.config.update({region: 'REGION'}); // 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.