-
Notifications
You must be signed in to change notification settings - Fork 0
/
metadata.go
62 lines (51 loc) · 1.32 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
package gcp
import (
"fmt"
"io/ioutil"
"net/http"
"time"
)
// GetProject return GCP project name
func GetProject() (string, error) {
return getMetadata("project/project-id")
}
// GetClusterName returns GKE cluster name
func GetClusterName() (string, error) {
return getMetadata("instance/attributes/cluster-name")
}
// GetClusterLocation returns GKE cluster location
func GetClusterLocation() (string, error) {
return getMetadata("instance/attributes/cluster-location")
}
func metadataRequest(urlPath string) (string, error) {
client := &http.Client{}
req, err := http.NewRequest("GET",
fmt.Sprintf("http://metadata/computeMetadata/v1/%s", urlPath), nil)
if err != nil {
return "", err
}
req.Header.Add("Metadata-Flavor", "Google")
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("GCP metadata server returned %d", resp.StatusCode)
}
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(bodyBytes), nil
}
func getMetadata(urlPath string) (string, error) {
for i := 1; i <= 3; i++ {
p, err := metadataRequest(urlPath)
if p != "" {
return p, err
}
time.Sleep(time.Second * time.Duration(i))
}
return "", fmt.Errorf("Failed to resolve metadata from %s", urlPath)
}