Using Regions and Availability Zones with Amazon EC2 - AWS SDK for Go (version 1)

We announced the upcoming end-of-support for AWS SDK for Go V1. We recommend that you migrate to AWS SDK for Go V2. For dates, additional details, and information on how to migrate, please refer to the linked announcement.

Using Regions and Availability Zones with Amazon EC2

These Go examples show you how to retrieve details about AWS Regions and Availability Zones.

The code in this example uses the AWS SDK for Go to perform these tasks by using these methods of the Amazon EC2 client class:

You can download complete versions of these example files from the aws-doc-sdk-examples repository on GitHub.

Scenario

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

In this example, you use Go code to retrieve details about regions and Availability Zones. The code uses the AWS SDK for Go tomanage instances by using the following methods of the Amazon EC2 client class:

Prerequisites

List the Regions

This example lists the regions in which Amazon EC2 is available.

To get started, create a new Go file named regions_and_availability.go.

You must import the relevant Go and AWS SDK for Go packages by adding the following lines.

package main import ( "fmt" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/ec2" )

In the main function, create a session with credentials from the shared credentials file, ~/.aws/credentials, and create a new EC2 client.

func main() { // Load session from shared config sess := session.Must(session.NewSessionWithOptions(session.Options{ SharedConfigState: session.SharedConfigEnable, })) // Create new EC2 client svc := ec2.New(sess)

Print out the list of regions that work with Amazon EC2 that are returned by calling DescribeRegions.

resultRegions, err := svc.DescribeRegions(nil) if err != nil { fmt.Println("Error", err) return }

Add a call that retrieves Availability Zones only for the region of the EC2 service object.

resultAvalZones, err := svc.DescribeAvailabilityZones(nil) if err != nil { fmt.Println("Error", err) return } fmt.Println("Success", resultAvalZones.AvailabilityZones) }

See the complete example on GitHub.