|
| 1 | +package k8s |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "io/ioutil" |
| 6 | + |
| 7 | + "github.com/pkg/errors" |
| 8 | + restclient "k8s.io/client-go/rest" |
| 9 | +) |
| 10 | + |
| 11 | +type ClusterConfig struct { |
| 12 | + Name string `json:"name" pflag:",Friendly name of the remote cluster"` |
| 13 | + Endpoint string `json:"endpoint" pflag:", Remote K8s cluster endpoint"` |
| 14 | + Auth Auth `json:"auth" pflag:"-, Auth setting for the cluster"` |
| 15 | + Enabled bool `json:"enabled" pflag:", Boolean flag to enable or disable"` |
| 16 | +} |
| 17 | + |
| 18 | +type Auth struct { |
| 19 | + TokenPath string `json:"tokenPath" pflag:", Token path"` |
| 20 | + CaCertPath string `json:"caCertPath" pflag:", Certificate path"` |
| 21 | +} |
| 22 | + |
| 23 | +func (auth Auth) GetCA() ([]byte, error) { |
| 24 | + cert, err := ioutil.ReadFile(auth.CaCertPath) |
| 25 | + if err != nil { |
| 26 | + return nil, errors.Wrap(err, "failed to read k8s CA cert from configured path") |
| 27 | + } |
| 28 | + return cert, nil |
| 29 | +} |
| 30 | + |
| 31 | +func (auth Auth) GetToken() (string, error) { |
| 32 | + token, err := ioutil.ReadFile(auth.TokenPath) |
| 33 | + if err != nil { |
| 34 | + return "", errors.Wrap(err, "failed to read k8s bearer token from configured path") |
| 35 | + } |
| 36 | + return string(token), nil |
| 37 | +} |
| 38 | + |
| 39 | +// KubeClientConfig ... |
| 40 | +func KubeClientConfig(host string, auth Auth) (*restclient.Config, error) { |
| 41 | + tokenString, err := auth.GetToken() |
| 42 | + if err != nil { |
| 43 | + return nil, errors.New(fmt.Sprintf("Failed to get auth token: %+v", err)) |
| 44 | + } |
| 45 | + |
| 46 | + caCert, err := auth.GetCA() |
| 47 | + if err != nil { |
| 48 | + return nil, errors.New(fmt.Sprintf("Failed to get auth CA: %+v", err)) |
| 49 | + } |
| 50 | + |
| 51 | + tlsClientConfig := restclient.TLSClientConfig{} |
| 52 | + tlsClientConfig.CAData = caCert |
| 53 | + return &restclient.Config{ |
| 54 | + Host: host, |
| 55 | + TLSClientConfig: tlsClientConfig, |
| 56 | + BearerToken: tokenString, |
| 57 | + }, nil |
| 58 | +} |
0 commit comments