Determining Your Current EC2 Region in Go

If you program in Go and use it to access AWS resources, you’ll notice that each of the services in the SDK require a region to be explicitly specified. This is because AWS constructs an API endpoint that is region-specific and some company resources may exist in a specific region (not necessarily where the code is being run). If the code is knowingly trying to access AWS resources in the same region, it can be annoying to hardcode a region into the code. It makes the code rigid and brittle (non-portable). There is a way to have your code automatically determine its region.

Wherever an AWS services runs, be it EC2, ECS or Lambda, there is the concept of a metadata service. This is an internal (privately-routable) service that provides server instances with information about itself (hence "metadata"), and also allows the service to gain AWS credentials so it can access other services. The metadata service is where your code should be asking about the region where its is deployed. This is easy to do in Go.

package main

import (
  “fmt”
  “github.com/aws/aws-sdk-go-v2/aws/external”
  “github.com/aws/aws-sdk-go-v2/aws/ec2metadata”
)

func main() {
  cfg, err := external.LoadDefaultAWSConfig()

  if err != nil {
    panic(“Unable to load SDK config, “ + err.Error())
  }

  md_svc := ec2metadata.New(cfg)

  if !md_svc.Available() {
    panic(“Metadata service cannot be reached.  Are you on an EC2/ECS/Lambda machine?”)
  }

  region, err := md_svc.Region()

  fmt.Println(“Region is: “ + region)
}

Note that this is using the new V2 AWS SDK for Go.