This repository has been archived by the owner on May 13, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathaccount_gcp.go
67 lines (58 loc) · 1.59 KB
/
account_gcp.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
// +build !appengine
package gcpvault
import (
"context"
"io/ioutil"
"net/http"
"strings"
"time"
"github.com/pkg/errors"
)
func getDefaultServiceAccountEmail(ctx context.Context, cfg Config) (string, error) {
result, err := callMetadataService(ctx, cfg)
if err != nil {
return "", errors.Wrap(err, "unable to retrieve default service account email")
}
return result, nil
}
func callMetadataService(ctx context.Context, cfg Config) (string, error) {
c := getHTTPClient(ctx, cfg)
if cfg.MetadataAddress == "" {
cfg.MetadataAddress = "http://metadata"
}
r, err := http.NewRequest(http.MethodGet,
cfg.MetadataAddress+
"/computeMetadata/v1/instance/service-accounts/default/email", nil)
if err != nil {
return "", errors.Wrap(err, "unable create metadata request")
}
r.Header.Add("Metadata-Flavor", "Google")
resp, err := c.Do(r)
if err != nil {
return "", errors.Wrap(err, "error connecting to metadata server")
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", errors.Errorf("unexpected status response from metadata service: %d",
resp.StatusCode)
}
bod, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", errors.Wrap(err, "unable to read metadata response")
}
result := strings.TrimSpace(string(bod))
if result == "" {
return "", errors.New("unexpected empty response from metadata service")
}
return result, nil
}
func getHTTPClient(ctx context.Context, cfg Config) *http.Client {
if cfg.HTTPClient != nil {
return cfg.HTTPClient
}
return &http.Client{
Transport: &http.Transport{
IdleConnTimeout: 1 * time.Second,
},
}
}