We announced
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
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
-
You have set up and configured the AWS SDK for Go.
-
You are familiar with AWS Regions and Availability Zones. To learn more, see Regions and Availability Zones in the Amazon EC2 User Guide or Regions and Availability Zones in the Amazon EC2 User Guide.
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