This repository has been archived by the owner on Jun 26, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathec2.go
65 lines (54 loc) · 1.6 KB
/
ec2.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package ecstaskports
import (
"context"
"net/http"
"io/ioutil"
"os"
"strings"
"time"
"golang.org/x/net/context/ctxhttp"
)
const (
instanceMetadataEndpointLocalIPv4 = "http://169.254.169.254/latest/meta-data/local-ipv4"
instanceMetadataEndpointAZ = "http://169.254.169.254/latest/meta-data/placement/availability-zone"
)
// GetEC2InstancePrivateIPAddress returns the private IP address of an EC2 instance
func GetEC2InstancePrivateIPAddress() ([]byte, error) {
ctx, cancelFunc := context.WithTimeout(context.Background(), time.Second)
defer cancelFunc()
resp, err := ctxhttp.Get(ctx, http.DefaultClient, instanceMetadataEndpointLocalIPv4)
if err != nil {
return nil, err
}
return ioutil.ReadAll(resp.Body)
}
// GetEC2InstanceAvailabilityZone returns the availability zone that an EC2 instance is running in
func GetEC2InstanceAvailabilityZone() ([]byte, error) {
ctx, cancelFunc := context.WithTimeout(context.Background(), time.Second)
defer cancelFunc()
resp, err := ctxhttp.Get(ctx, http.DefaultClient, instanceMetadataEndpointAZ)
if err != nil {
return nil, err
}
return ioutil.ReadAll(resp.Body)
}
// GetEC2InstanceRegion automatically discovers the AWS region from the runtime environment
func GetEC2InstanceRegion() string {
region := os.Getenv("AWS_REGION")
if region == "" {
region = os.Getenv("AWS_DEFAULT_REGION")
}
if region == "" {
data, err := GetEC2InstanceAvailabilityZone()
if err == nil {
region = strings.TrimSpace(string(data))
if len(region) > 0 {
region = region[0 : len(region)-1]
}
}
}
if region == "" {
region = "us-east-1"
}
return region
}