2018-12-17 05:27:07 -05:00
|
|
|
package kubernetes
|
|
|
|
|
|
|
|
import (
|
2022-02-25 08:37:07 -05:00
|
|
|
"os"
|
2018-12-17 05:27:07 -05:00
|
|
|
|
|
|
|
"github.com/docker/cli/cli/context"
|
|
|
|
"k8s.io/client-go/tools/clientcmd"
|
|
|
|
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
|
|
|
|
)
|
|
|
|
|
|
|
|
// FromKubeConfig creates a Kubernetes endpoint from a Kubeconfig file
|
|
|
|
func FromKubeConfig(kubeconfig, kubeContext, namespaceOverride string) (Endpoint, error) {
|
|
|
|
cfg := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
|
|
|
|
&clientcmd.ClientConfigLoadingRules{ExplicitPath: kubeconfig},
|
|
|
|
&clientcmd.ConfigOverrides{CurrentContext: kubeContext, Context: clientcmdapi.Context{Namespace: namespaceOverride}})
|
|
|
|
ns, _, err := cfg.Namespace()
|
|
|
|
if err != nil {
|
|
|
|
return Endpoint{}, err
|
|
|
|
}
|
|
|
|
clientcfg, err := cfg.ClientConfig()
|
|
|
|
if err != nil {
|
|
|
|
return Endpoint{}, err
|
|
|
|
}
|
|
|
|
var ca, key, cert []byte
|
|
|
|
if ca, err = readFileOrDefault(clientcfg.CAFile, clientcfg.CAData); err != nil {
|
|
|
|
return Endpoint{}, err
|
|
|
|
}
|
|
|
|
if key, err = readFileOrDefault(clientcfg.KeyFile, clientcfg.KeyData); err != nil {
|
|
|
|
return Endpoint{}, err
|
|
|
|
}
|
|
|
|
if cert, err = readFileOrDefault(clientcfg.CertFile, clientcfg.CertData); err != nil {
|
|
|
|
return Endpoint{}, err
|
|
|
|
}
|
|
|
|
var tlsData *context.TLSData
|
|
|
|
if ca != nil || cert != nil || key != nil {
|
|
|
|
tlsData = &context.TLSData{
|
|
|
|
CA: ca,
|
|
|
|
Cert: cert,
|
|
|
|
Key: key,
|
|
|
|
}
|
|
|
|
}
|
2020-02-04 05:04:07 -05:00
|
|
|
var usernamePassword *UsernamePassword
|
|
|
|
if clientcfg.Username != "" || clientcfg.Password != "" {
|
|
|
|
usernamePassword = &UsernamePassword{
|
|
|
|
Username: clientcfg.Username,
|
|
|
|
Password: clientcfg.Password,
|
|
|
|
}
|
|
|
|
}
|
2018-12-17 05:27:07 -05:00
|
|
|
return Endpoint{
|
|
|
|
EndpointMeta: EndpointMeta{
|
|
|
|
EndpointMetaBase: context.EndpointMetaBase{
|
|
|
|
Host: clientcfg.Host,
|
|
|
|
SkipTLSVerify: clientcfg.Insecure,
|
|
|
|
},
|
|
|
|
DefaultNamespace: ns,
|
|
|
|
AuthProvider: clientcfg.AuthProvider,
|
|
|
|
Exec: clientcfg.ExecProvider,
|
2020-02-04 05:04:07 -05:00
|
|
|
UsernamePassword: usernamePassword,
|
2018-12-17 05:27:07 -05:00
|
|
|
},
|
|
|
|
TLSData: tlsData,
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func readFileOrDefault(path string, defaultValue []byte) ([]byte, error) {
|
|
|
|
if path != "" {
|
2022-02-25 08:37:07 -05:00
|
|
|
return os.ReadFile(path)
|
2018-12-17 05:27:07 -05:00
|
|
|
}
|
|
|
|
return defaultValue, nil
|
|
|
|
}
|