AWS Developer Tools Blog

Working with Multiple Regions

In a previous blog post, I introduced the new :region configuration option for the AWS SDK for Ruby (aws-sdk gem). Beyond simplified configuration, the Ruby SDK provides additional helpers for working with multiple regions.

There are two new helper classes for working with regions, AWS::Core::Region and AWS::Core::RegionCollection. The AWS module provides helper methods so that you should not need to instantiate these classes directly.

Region Objects

If you know the name of a region you need to work with, you can create it like so:

# no HTTP request required, simply returns a new AWS::Core::Region object
region = AWS.regions['us-west-2']

A region object provides access to service interface objects. Every service can be accessed using its short name.

region = AWS.regions['us-west-2']

# collect the ids of instances running in this region
region.ec2.instances.map(&:id)

# collect the name of tables created in this region
region.dynamo_db.tables.map(&:name)

See the Region class API documentation for a complete list of service interface helper methods.

RegionCollection

Besides returning a single region object, the region collection can also enumerate all public (non GovCloud) regions.

AWS.regions.each do |region|
  puts region.name
end

Please note that when you enumerate regions, an HTTP request is made to get a current list of regions and services. The response is cached for the life of the process.

Enumerating Regions from a Service

Not all services are available in every region. You can safely enumerate only regions a service operates in using a region collection from a service interface. In the following example we use the regions helper method to enumerate what regions Amazon DynamoDB and Amazon Redshift operate in.

AWS::DynamoDB.regions.map(&:name)
#=> ["us-east-1", "us-west-1", "us-west-2", "eu-west-1", "ap-northeast-1", "ap-southeast-1", "ap-southeast-2", "sa-east-1"] 

AWS::Redshift.regions.map(&:name)
#=> ["us-east-1", "us-west-2", "eu-west-1"] 

You can use the region object to operate on a service resource in each region it exists in. As a service expands to additional regions, you code will automatically include those regions when enumerating. In the following example, we list all of the Amazon DynamoDB tables, grouped by region.

# generate a list of DynamoDB tables for every region
AWS::DynamoDB.regions.each do |region|
  table_names = region.dynamo_db.tables.map(&:name)
  unless table_names.empty?
    puts "Region: " + region.name
    puts "Tables:"
    puts table_names.join("n")
    puts ""
  end
end

Take the new regions interfaces for a spin and let us know what you think!