-
Notifications
You must be signed in to change notification settings - Fork 80
/
metadata.go
83 lines (73 loc) · 1.69 KB
/
metadata.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package metadata
import (
"fmt"
"io/ioutil"
"net/http"
"strings"
"time"
"go.uber.org/zap"
)
/*
curl -L http://169.254.169.254/latest/meta-data
ami-id
ami-launch-index
ami-manifest-path
block-device-mapping/
events/
hostname
instance-action
instance-id
instance-type
local-hostname
local-ipv4
mac
metrics/
network/
placement/
profile
public-hostname
public-ipv4
public-keys/
reservation-id
security-groups
services/
*/
func getMeta(lg *zap.Logger, timeout time.Duration, key string) (s string, err error) {
addr := fmt.Sprintf("http://169.254.169.254/latest/meta-data/%s", key)
cli := http.DefaultClient
if timeout > 0 {
cli.Timeout = timeout
}
for i := 0; i < 10; i++ {
var resp *http.Response
resp, err = cli.Get(addr)
if err != nil {
lg.Warn("failed to get metadata", zap.String("key", key), zap.Error(err))
time.Sleep(3 * time.Second)
continue
}
var d []byte
d, err = ioutil.ReadAll(resp.Body)
if err != nil {
lg.Warn("failed to get metadata", zap.String("key", key), zap.Error(err))
time.Sleep(3 * time.Second)
continue
}
resp.Body.Close()
s = strings.TrimSpace(string(d))
break
}
return s, nil
}
// PublicIPv4 returns the public IPv4 address of an EC2 instance.
func PublicIPv4(lg *zap.Logger, timeout time.Duration) (s string, err error) {
return getMeta(lg, timeout, "public-ipv4")
}
// PrivateIPv4 returns the private IPv4 address of an EC2 instance.
func PrivateIPv4(lg *zap.Logger, timeout time.Duration) (s string, err error) {
return getMeta(lg, timeout, "local-ipv4")
}
// InstanceID returns the instance ID of an EC2 instance.
func InstanceID(lg *zap.Logger, timeout time.Duration) (s string, err error) {
return getMeta(lg, timeout, "instance-id")
}