Golang: Get EC2 AWS instance region

Following is the golang code to get the region of an EC2 machine in AWS.

package main

import (
        "fmt"
    "io/ioutil"
    "net/http"
)

func getRegion() string{
    link := "http://169.254.169.254/latest/meta-data/placement/availability-zone"
    response, err := http.Get(link)
    if err != nil {
        fmt.Println(err)
    }
    defer response.Body.Close()

    //block forever at the next line
    content, _ := ioutil.ReadAll(response.Body)

    return string(content)
}

func main() {
    aws_region := getRegion()
    fmt.Println(aws_region)

}

Leave a Reply

Your email address will not be published. Required fields are marked *