github.com/Cloud-Foundations/Dominator@v0.3.4/lib/awsutil/regions.go (about) 1 package awsutil 2 3 import ( 4 "encoding/json" 5 "errors" 6 "fmt" 7 "io/ioutil" 8 "net/http" 9 "sort" 10 "strings" 11 12 "github.com/aws/aws-sdk-go/aws" 13 "github.com/aws/aws-sdk-go/service/ec2" 14 15 "github.com/Cloud-Foundations/Dominator/lib/constants" 16 ) 17 18 var ( 19 instanceDocumentMap map[string]string 20 ) 21 22 func getLocalRegion() (string, error) { 23 if instanceDocumentMap == nil { 24 instanceDocumentMap = make(map[string]string) 25 } 26 if region, ok := instanceDocumentMap["region"]; ok { 27 return region, nil 28 } 29 resp, err := http.Get(constants.MetadataUrl + constants.MetadataIdentityDoc) 30 if err != nil { 31 return "", err 32 } 33 defer resp.Body.Close() 34 if resp.StatusCode != 200 { 35 return "", errors.New(resp.Status) 36 } 37 if body, err := ioutil.ReadAll(resp.Body); err != nil { 38 return "", err 39 } else { 40 value := strings.TrimSpace(string(body)) 41 if value == "" { 42 return "", errors.New("empty body") 43 } else { 44 data := []byte(value) 45 if err := json.Unmarshal(data, &instanceDocumentMap); err != nil { 46 return "", err 47 } 48 if region, ok := instanceDocumentMap["region"]; ok { 49 return region, nil 50 } 51 return "", errors.New("region not found in instance document") 52 } 53 } 54 55 } 56 57 func listRegions(awsService *ec2.EC2) ([]string, error) { 58 out, err := awsService.DescribeRegions(&ec2.DescribeRegionsInput{}) 59 if err != nil { 60 return nil, fmt.Errorf("ec2.DescribeRegions: %s", err) 61 } 62 regionNames := make([]string, 0, len(out.Regions)) 63 for _, region := range out.Regions { 64 regionNames = append(regionNames, aws.StringValue(region.RegionName)) 65 } 66 sort.Strings(regionNames) 67 return regionNames, nil 68 }