-
Notifications
You must be signed in to change notification settings - Fork 0
/
kubeconfig.go
52 lines (48 loc) · 1.59 KB
/
kubeconfig.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
package kubeconfig
import (
"crypto/x509"
"fmt"
"github.com/whalecold/utils/cert"
"k8s.io/apimachinery/pkg/runtime"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
clientcmdlatest "k8s.io/client-go/tools/clientcmd/api/latest"
)
func BuildKubeConfigByte(caCert, caKey []byte, apiserverURL, clusterName string) ([]byte, error) {
opts := &cert.Options{
CommonName: "kubernetes-admin",
Organization: []string{"system:masters"},
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
}
clientKey, clientCert, err := signFromCa(caCert, caKey, opts)
if err != nil {
return nil, err
}
config := createWithCerts(apiserverURL, clusterName, "kubernetes-admin", caCert, clientKey, clientCert)
return runtime.Encode(clientcmdlatest.Codec, config)
}
// createWithCerts creates a KubeConfig object with access to the API server with client certificates
func createWithCerts(serverURL, clusterName, userName string, caCert []byte, clientKey []byte, clientCert []byte) *clientcmdapi.Config {
// use the clusterId and accountId as the context name
contextName := fmt.Sprintf("%s@%s", clusterName, userName)
return &clientcmdapi.Config{
Clusters: map[string]*clientcmdapi.Cluster{
clusterName: {
Server: serverURL,
CertificateAuthorityData: caCert,
},
},
Contexts: map[string]*clientcmdapi.Context{
contextName: {
Cluster: clusterName,
AuthInfo: userName,
},
},
CurrentContext: contextName,
AuthInfos: map[string]*clientcmdapi.AuthInfo{
userName: {
ClientCertificateData: clientCert,
ClientKeyData: clientKey,
},
},
}
}