/
account.go
53 lines (43 loc) · 1.51 KB
/
account.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
package gke
import (
"net/http"
"golang.org/x/oauth2"
"golang.org/x/oauth2/jwt"
container "google.golang.org/api/container/v1"
)
const (
// ContainerScope is the Oauth2 scope required for interaction with the GKE API
ContainerScope = "https://www.googleapis.com/auth/cloud-platform"
// TokenURL is the Oauth2 token exchange URL for Google accounts
TokenURL = "https://accounts.google.com/o/oauth2/token"
)
// PrivateKey is the type for a JWT private key
type PrivateKey string
// String is the fmt.Stringer interface implementation
func (p PrivateKey) String() string {
return string(p)
}
// Bytes is a convenience function for []byte(p.String())
func (p PrivateKey) Bytes() []byte {
return []byte(p.String())
}
// Note: getJWTConf, getOAuthClient and GetContainerService are inspired by code in
// https://github.com/hashicorp/terraform/blob/master/builtin/providers/google/config.go
func getJWTConf(email string, pk PrivateKey) *jwt.Config {
return &jwt.Config{
Email: email,
PrivateKey: pk.Bytes(),
Scopes: []string{ContainerScope},
TokenURL: TokenURL,
}
}
func getOAuthClient(conf *jwt.Config) *http.Client {
return conf.Client(oauth2.NoContext)
}
// GetContainerService creates a GKE client by creating an OAuth2 capable HTTP client from the
// given JWT credentials, then creating a new container client with that HTTP client
func GetContainerService(email string, pk PrivateKey) (*container.Service, error) {
conf := getJWTConf(email, pk)
cl := getOAuthClient(conf)
return container.New(cl)
}