-
Notifications
You must be signed in to change notification settings - Fork 378
/
create_kubeconfig.go
249 lines (216 loc) · 7.64 KB
/
create_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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
package createkubeconfig
import (
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"github.com/spf13/cobra"
"k8s.io/klog"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/cli-runtime/pkg/genericclioptions"
"k8s.io/client-go/util/cert"
kcmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
"k8s.io/kubernetes/pkg/kubectl/util/templates"
"github.com/openshift/library-go/pkg/crypto"
"github.com/openshift/oc/pkg/helpers/kubeconfig"
"k8s.io/client-go/tools/clientcmd"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
)
const CreateKubeConfigCommandName = "create-kubeconfig"
var createKubeConfigLongDesc = templates.LongDesc(`
Create's a .kubeconfig file at <--kubeconfig> that looks like this:
clusters:
- cluster:
certificate-authority-data: <contents of --certificate-authority>
server: <--master>
name: <--cluster>
- cluster:
certificate-authority-data: <contents of --certificate-authority>
server: <--public-master>
name: public-<--cluster>
contexts:
- context:
cluster: <--cluster>
user: <--user>
namespace: <--namespace>
name: <--context>
- context:
cluster: public-<--cluster>
user: <--user>
namespace: <--namespace>
name: public-<--context>
current-context: <--context>
kind: Config
users:
- name: <--user>
user:
client-certificate-data: <contents of --client-certificate>
client-key-data: <contents of --client-key>`)
type CreateKubeConfigOptions struct {
APIServerURL string
PublicAPIServerURL string
APIServerCAFiles []string
CertFile string
KeyFile string
ContextNamespace string
KubeConfigFile string
genericclioptions.IOStreams
}
func NewCreateKubeConfigOptions(streams genericclioptions.IOStreams) *CreateKubeConfigOptions {
return &CreateKubeConfigOptions{
APIServerURL: "https://localhost:8443",
APIServerCAFiles: []string{"openshift.local.config/master/ca.crt"},
ContextNamespace: metav1.NamespaceDefault,
KubeConfigFile: ".kubeconfig",
IOStreams: streams,
}
}
func NewCommandCreateKubeConfig(commandName string, fullName string, streams genericclioptions.IOStreams) *cobra.Command {
o := NewCreateKubeConfigOptions(streams)
cmd := &cobra.Command{
Use: commandName,
Short: "Create a basic .kubeconfig file from client certs",
Long: createKubeConfigLongDesc,
Run: func(cmd *cobra.Command, args []string) {
kcmdutil.CheckErr(o.Validate(args))
if _, err := o.CreateKubeConfig(); err != nil {
kcmdutil.CheckErr(err)
}
},
}
cmd.Flags().StringVar(&o.APIServerURL, "master", o.APIServerURL, "The API server's URL.")
cmd.Flags().StringVar(&o.PublicAPIServerURL, "public-master", o.PublicAPIServerURL, "The API public facing server's URL (if applicable).")
cmd.Flags().StringSliceVar(&o.APIServerCAFiles, "certificate-authority", o.APIServerCAFiles, "Files containing signing authorities to use to verify the API server's serving certificate.")
cmd.Flags().StringVar(&o.CertFile, "client-certificate", o.CertFile, "The client cert file.")
cmd.Flags().StringVar(&o.KeyFile, "client-key", o.KeyFile, "The client key file.")
cmd.Flags().StringVar(&o.ContextNamespace, "namespace", o.ContextNamespace, "Namespace for this context in .kubeconfig.")
cmd.Flags().StringVar(&o.KubeConfigFile, "kubeconfig", o.KubeConfigFile, "Path for the resulting .kubeconfig file.")
// autocompletion hints
cmd.MarkFlagFilename("certificate-authority")
cmd.MarkFlagFilename("client-certificate")
cmd.MarkFlagFilename("client-key")
cmd.MarkFlagFilename("kubeconfig")
return cmd
}
func (o CreateKubeConfigOptions) Validate(args []string) error {
if len(args) != 0 {
return errors.New("no arguments are supported")
}
if len(o.KubeConfigFile) == 0 {
return errors.New("kubeconfig must be provided")
}
if len(o.CertFile) == 0 {
return errors.New("client-certificate must be provided")
}
if len(o.KeyFile) == 0 {
return errors.New("client-key must be provided")
}
if len(o.APIServerCAFiles) == 0 {
return errors.New("certificate-authority must be provided")
} else {
for _, caFile := range o.APIServerCAFiles {
if _, err := cert.NewPool(caFile); err != nil {
return fmt.Errorf("certificate-authority must be a valid certificate file: %v", err)
}
}
}
if len(o.ContextNamespace) == 0 {
return errors.New("namespace must be provided")
}
if len(o.APIServerURL) == 0 {
return errors.New("master must be provided")
}
return nil
}
func (o CreateKubeConfigOptions) CreateKubeConfig() (*clientcmdapi.Config, error) {
klog.V(4).Infof("creating a .kubeconfig with: %#v", o)
// read all the referenced filenames
caData, err := readFiles(o.APIServerCAFiles, []byte("\n"))
if err != nil {
return nil, err
}
certData, err := ioutil.ReadFile(o.CertFile)
if err != nil {
return nil, err
}
keyData, err := ioutil.ReadFile(o.KeyFile)
if err != nil {
return nil, err
}
certConfig, err := crypto.GetTLSCertificateConfig(o.CertFile, o.KeyFile)
if err != nil {
return nil, err
}
// determine all the nicknames
clusterNick, err := kubeconfig.GetClusterNicknameFromURL(o.APIServerURL)
if err != nil {
return nil, err
}
userNick, err := kubeconfig.GetUserNicknameFromCert(clusterNick, certConfig.Certs...)
if err != nil {
return nil, err
}
contextNick := kubeconfig.GetContextNickname(o.ContextNamespace, clusterNick, userNick)
credentials := make(map[string]*clientcmdapi.AuthInfo)
credentials[userNick] = &clientcmdapi.AuthInfo{
ClientCertificateData: certData,
ClientKeyData: keyData,
}
// normalize the provided server to a format expected by config
o.APIServerURL, err = kubeconfig.NormalizeServerURL(o.APIServerURL)
if err != nil {
return nil, err
}
clusters := make(map[string]*clientcmdapi.Cluster)
clusters[clusterNick] = &clientcmdapi.Cluster{
Server: o.APIServerURL,
CertificateAuthorityData: caData,
}
contexts := make(map[string]*clientcmdapi.Context)
contexts[contextNick] = &clientcmdapi.Context{Cluster: clusterNick, AuthInfo: userNick, Namespace: o.ContextNamespace}
createPublic := (len(o.PublicAPIServerURL) > 0) && o.APIServerURL != o.PublicAPIServerURL
if createPublic {
publicClusterNick, err := kubeconfig.GetClusterNicknameFromURL(o.PublicAPIServerURL)
if err != nil {
return nil, err
}
publicContextNick := kubeconfig.GetContextNickname(o.ContextNamespace, publicClusterNick, userNick)
clusters[publicClusterNick] = &clientcmdapi.Cluster{
Server: o.PublicAPIServerURL,
CertificateAuthorityData: caData,
}
contexts[publicContextNick] = &clientcmdapi.Context{Cluster: publicClusterNick, AuthInfo: userNick, Namespace: o.ContextNamespace}
}
kubeConfig := &clientcmdapi.Config{
Clusters: clusters,
AuthInfos: credentials,
Contexts: contexts,
CurrentContext: contextNick,
}
klog.V(3).Infof("Generating '%s' API client config as %s\n", userNick, o.KubeConfigFile)
// Ensure the parent dir exists
if err := os.MkdirAll(filepath.Dir(o.KubeConfigFile), os.FileMode(0755)); err != nil {
return nil, err
}
if err := clientcmd.WriteToFile(*kubeConfig, o.KubeConfigFile); err != nil {
return nil, err
}
return kubeConfig, nil
}
// readFiles returns a byte array containing the contents of all the given filenames,
// optionally separated by a delimiter, or an error if any of the files cannot be read
func readFiles(srcFiles []string, separator []byte) ([]byte, error) {
data := []byte{}
for _, srcFile := range srcFiles {
fileData, err := ioutil.ReadFile(srcFile)
if err != nil {
return nil, err
}
if len(data) > 0 && len(separator) > 0 {
data = append(data, separator...)
}
data = append(data, fileData...)
}
return data, nil
}