/
kubeconfig.go
98 lines (86 loc) · 2.09 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package kubeconfig
import (
"fmt"
"os"
"github.com/ghodss/yaml"
"github.com/pkg/errors"
clientcmd "k8s.io/client-go/tools/clientcmd/api/v1"
"github.com/openshift/installer/pkg/asset"
"github.com/openshift/installer/pkg/asset/tls"
"github.com/openshift/installer/pkg/types"
)
type kubeconfig struct {
Config *clientcmd.Config
File *asset.File
}
// generate generates the kubeconfig.
func (k *kubeconfig) generate(
ca tls.CertInterface,
clientCertKey tls.CertKeyInterface,
installConfig *types.InstallConfig,
userName string,
kubeconfigPath string,
) error {
k.Config = &clientcmd.Config{
Clusters: []clientcmd.NamedCluster{
{
Name: installConfig.ObjectMeta.Name,
Cluster: clientcmd.Cluster{
Server: fmt.Sprintf("https://api.%s:6443", installConfig.ClusterDomain()),
CertificateAuthorityData: ca.Cert(),
},
},
},
AuthInfos: []clientcmd.NamedAuthInfo{
{
Name: userName,
AuthInfo: clientcmd.AuthInfo{
ClientCertificateData: clientCertKey.Cert(),
ClientKeyData: clientCertKey.Key(),
},
},
},
Contexts: []clientcmd.NamedContext{
{
Name: userName,
Context: clientcmd.Context{
Cluster: installConfig.ObjectMeta.Name,
AuthInfo: userName,
},
},
},
CurrentContext: userName,
}
data, err := yaml.Marshal(k.Config)
if err != nil {
return errors.Wrap(err, "failed to Marshal kubeconfig")
}
k.File = &asset.File{
Filename: kubeconfigPath,
Data: data,
}
return nil
}
// Files returns the files generated by the asset.
func (k *kubeconfig) Files() []*asset.File {
if k.File != nil {
return []*asset.File{k.File}
}
return []*asset.File{}
}
// load returns the kubeconfig from disk.
func (k *kubeconfig) load(f asset.FileFetcher, name string) (found bool, err error) {
file, err := f.FetchByName(name)
if err != nil {
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
config := &clientcmd.Config{}
if err := yaml.Unmarshal(file.Data, config); err != nil {
return false, errors.Wrap(err, "failed to unmarshal")
}
k.File, k.Config = file, config
return true, nil
}