-
Notifications
You must be signed in to change notification settings - Fork 271
/
instance_metadata.go
106 lines (88 loc) · 2.43 KB
/
instance_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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package providers
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
)
var securityCredURL = "http://100.100.100.200/latest/meta-data/ram/security-credentials/"
func NewInstanceMetadataProvider() Provider {
return &InstanceMetadataProvider{}
}
type InstanceMetadataProvider struct {
RoleName string
}
func get(url string) (status int, content string, err error) {
resp, err := http.Get(url)
if err != nil {
return
}
defer resp.Body.Close()
bodyBytes, err := ioutil.ReadAll(resp.Body)
return resp.StatusCode, string(bodyBytes), err
}
func (p *InstanceMetadataProvider) GetRoleName() (roleName string, err error) {
// Instances can have only one role name that never changes,
// so attempt to populate it.
// If this call is executed in an environment that doesn't support instance metadata,
// it will time out after 30 seconds and return an err.
status, roleName, err := get(securityCredURL)
if err != nil {
return
}
if status != 200 {
err = fmt.Errorf("received %d getting role name: %s", status, roleName)
return
}
if roleName == "" {
err = errors.New("unable to retrieve role name, it may be unset")
}
return
}
func (p *InstanceMetadataProvider) Retrieve() (auth.Credential, error) {
if p.RoleName == "" {
roleName, err := p.GetRoleName()
if err != nil {
return nil, err
}
p.RoleName = roleName
}
status, content, err := get(securityCredURL + p.RoleName)
if err != nil {
return nil, err
}
if status != 200 {
return nil, fmt.Errorf("received %d getting security credentials for %s", status, p.RoleName)
}
body := make(map[string]interface{})
if err := json.Unmarshal([]byte(content), &body); err != nil {
return nil, err
}
accessKeyID, err := extractString(body, "AccessKeyId")
if err != nil {
return nil, err
}
accessKeySecret, err := extractString(body, "AccessKeySecret")
if err != nil {
return nil, err
}
securityToken, err := extractString(body, "SecurityToken")
if err != nil {
return nil, err
}
return credentials.NewStsTokenCredential(accessKeyID, accessKeySecret, securityToken), nil
}
func extractString(m map[string]interface{}, key string) (string, error) {
raw, ok := m[key]
if !ok {
return "", fmt.Errorf("%s not in map", key)
}
str, ok := raw.(string)
if !ok {
return "", fmt.Errorf("%s is not a string in map", key)
}
return str, nil
}