2020-09-24 07:14:34 +00:00
|
|
|
package clientaccess
|
|
|
|
|
|
|
|
import (
|
2022-10-08 00:36:57 +00:00
|
|
|
"os"
|
2020-09-24 07:14:34 +00:00
|
|
|
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
"k8s.io/client-go/tools/clientcmd"
|
|
|
|
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
|
|
|
|
)
|
|
|
|
|
|
|
|
// WriteClientKubeConfig generates a kubeconfig at destFile that can be used to connect to a server at url with the given certs and keys
|
2021-10-07 19:47:00 +00:00
|
|
|
func WriteClientKubeConfig(destFile, url, serverCAFile, clientCertFile, clientKeyFile string) error {
|
2022-10-08 00:36:57 +00:00
|
|
|
serverCA, err := os.ReadFile(serverCAFile)
|
2020-09-24 07:14:34 +00:00
|
|
|
if err != nil {
|
|
|
|
return errors.Wrapf(err, "failed to read %s", serverCAFile)
|
|
|
|
}
|
|
|
|
|
2022-10-08 00:36:57 +00:00
|
|
|
clientCert, err := os.ReadFile(clientCertFile)
|
2020-09-24 07:14:34 +00:00
|
|
|
if err != nil {
|
|
|
|
return errors.Wrapf(err, "failed to read %s", clientCertFile)
|
|
|
|
}
|
|
|
|
|
2022-10-08 00:36:57 +00:00
|
|
|
clientKey, err := os.ReadFile(clientKeyFile)
|
2020-09-24 07:14:34 +00:00
|
|
|
if err != nil {
|
|
|
|
return errors.Wrapf(err, "failed to read %s", clientKeyFile)
|
|
|
|
}
|
|
|
|
|
|
|
|
config := clientcmdapi.NewConfig()
|
|
|
|
|
|
|
|
cluster := clientcmdapi.NewCluster()
|
|
|
|
cluster.CertificateAuthorityData = serverCA
|
|
|
|
cluster.Server = url
|
|
|
|
|
|
|
|
authInfo := clientcmdapi.NewAuthInfo()
|
|
|
|
authInfo.ClientCertificateData = clientCert
|
|
|
|
authInfo.ClientKeyData = clientKey
|
|
|
|
|
|
|
|
context := clientcmdapi.NewContext()
|
|
|
|
context.AuthInfo = "default"
|
|
|
|
context.Cluster = "default"
|
|
|
|
|
|
|
|
config.Clusters["default"] = cluster
|
|
|
|
config.AuthInfos["default"] = authInfo
|
|
|
|
config.Contexts["default"] = context
|
|
|
|
config.CurrentContext = "default"
|
|
|
|
|
|
|
|
return clientcmd.WriteToFile(*config, destFile)
|
|
|
|
}
|