/
structure_kubeconfig.go
253 lines (215 loc) · 7.9 KB
/
structure_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
250
251
252
253
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package vcluster
import (
"bytes"
"fmt"
"log"
"os"
"path/filepath"
"sync"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/mitchellh/go-homedir"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/client-go/discovery"
"k8s.io/client-go/rest"
"k8s.io/client-go/restmapper"
"k8s.io/client-go/tools/clientcmd"
apimachineryschema "k8s.io/apimachinery/pkg/runtime/schema"
memcached "k8s.io/client-go/discovery/cached/memory"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
)
// This file is shamelessly stolen from https://github.com/hashicorp/terraform-provider-helm/blob/main/helm/provider.go
var k8sPrefix = "kubernetes.0."
func k8sGetOk(d *schema.ResourceData, key string) (interface{}, bool) {
value, ok := d.GetOk(k8sPrefix + key)
// For boolean attributes the zero value is Ok
switch value.(type) {
case bool:
// TODO: replace deprecated GetOkExists with SDK v2 equivalent
// https://github.com/hashicorp/terraform-plugin-sdk/pull/350
value, ok = d.GetOkExists(k8sPrefix + key)
}
// fix: DefaultFunc is not being triggered on TypeList
s := kubernetesResource().Schema[key]
if !ok && s.DefaultFunc != nil {
value, _ = s.DefaultFunc()
switch v := value.(type) {
case string:
ok = len(v) != 0
case bool:
ok = v
}
}
return value, ok
}
func k8sGet(d *schema.ResourceData, key string) interface{} {
value, _ := k8sGetOk(d, key)
return value
}
func expandStringSlice(s []interface{}) []string {
result := make([]string, len(s), len(s))
for k, v := range s {
// Handle the Terraform parser bug which turns empty strings in lists to nil.
if v == nil {
result[k] = ""
} else {
result[k] = v.(string)
}
}
return result
}
// KubeConfig is a RESTClientGetter interface implementation
type KubeConfig struct {
ClientConfig clientcmd.ClientConfig
sync.Mutex
}
// ToRESTConfig implemented interface method
func (k *KubeConfig) ToRESTConfig() (*rest.Config, error) {
config, err := k.ToRawKubeConfigLoader().ClientConfig()
return config, err
}
// ToDiscoveryClient implemented interface method
func (k *KubeConfig) ToDiscoveryClient() (discovery.CachedDiscoveryInterface, error) {
config, err := k.ToRESTConfig()
if err != nil {
return nil, err
}
// The more groups you have, the more discovery requests you need to make.
// given 25 groups (our groups + a few custom resources) with one-ish version each, discovery needs to make 50 requests
// double it just so we don't end up here again for a while. This config is only used for discovery.
config.Burst = 100
return memcached.NewMemCacheClient(discovery.NewDiscoveryClientForConfigOrDie(config)), nil
}
// ToRESTMapper implemented interface method
func (k *KubeConfig) ToRESTMapper() (meta.RESTMapper, error) {
discoveryClient, err := k.ToDiscoveryClient()
if err != nil {
return nil, err
}
mapper := restmapper.NewDeferredDiscoveryRESTMapper(discoveryClient)
expander := restmapper.NewShortcutExpander(mapper, discoveryClient)
return expander, nil
}
// ToRawKubeConfigLoader implemented interface method
func (k *KubeConfig) ToRawKubeConfigLoader() clientcmd.ClientConfig {
return k.ClientConfig
}
func newKubeConfig(configData *schema.ResourceData, namespace *string) (*KubeConfig, error) {
overrides := &clientcmd.ConfigOverrides{}
loader := &clientcmd.ClientConfigLoadingRules{}
configPaths := []string{}
if v, ok := k8sGetOk(configData, "config_path"); ok && v != "" {
configPaths = []string{v.(string)}
} else if v, ok := k8sGetOk(configData, "config_paths"); ok {
for _, p := range v.([]interface{}) {
configPaths = append(configPaths, p.(string))
}
} else if v := os.Getenv("KUBE_CONFIG_PATHS"); v != "" {
// NOTE we have to do this here because the schema
// does not yet allow you to set a default for a TypeList
configPaths = filepath.SplitList(v)
}
if len(configPaths) > 0 {
expandedPaths := []string{}
for _, p := range configPaths {
path, err := homedir.Expand(p)
if err != nil {
return nil, err
}
log.Printf("[DEBUG] Using kubeconfig: %s", path)
expandedPaths = append(expandedPaths, path)
}
if len(expandedPaths) == 1 {
loader.ExplicitPath = expandedPaths[0]
} else {
loader.Precedence = expandedPaths
}
ctx, ctxOk := k8sGetOk(configData, "config_context")
authInfo, authInfoOk := k8sGetOk(configData, "config_context_auth_info")
cluster, clusterOk := k8sGetOk(configData, "config_context_cluster")
if ctxOk || authInfoOk || clusterOk {
if ctxOk {
overrides.CurrentContext = ctx.(string)
log.Printf("[DEBUG] Using custom current context: %q", overrides.CurrentContext)
}
overrides.Context = clientcmdapi.Context{}
if authInfoOk {
overrides.Context.AuthInfo = authInfo.(string)
}
if clusterOk {
overrides.Context.Cluster = cluster.(string)
}
log.Printf("[DEBUG] Using overidden context: %#v", overrides.Context)
}
}
// Overriding with static configuration
if v, ok := k8sGetOk(configData, "insecure"); ok {
overrides.ClusterInfo.InsecureSkipTLSVerify = v.(bool)
}
if v, ok := k8sGetOk(configData, "cluster_ca_certificate"); ok {
overrides.ClusterInfo.CertificateAuthorityData = bytes.NewBufferString(v.(string)).Bytes()
}
if v, ok := k8sGetOk(configData, "client_certificate"); ok {
overrides.AuthInfo.ClientCertificateData = bytes.NewBufferString(v.(string)).Bytes()
}
if v, ok := k8sGetOk(configData, "host"); ok {
// Server has to be the complete address of the kubernetes cluster (scheme://hostname:port), not just the hostname,
// because `overrides` are processed too late to be taken into account by `defaultServerUrlFor()`.
// This basically replicates what defaultServerUrlFor() does with config but for overrides,
// see https://github.com/kubernetes/client-go/blob/v12.0.0/rest/url_utils.go#L85-L87
hasCA := len(overrides.ClusterInfo.CertificateAuthorityData) != 0
hasCert := len(overrides.AuthInfo.ClientCertificateData) != 0
defaultTLS := hasCA || hasCert || overrides.ClusterInfo.InsecureSkipTLSVerify
host, _, err := rest.DefaultServerURL(v.(string), "", apimachineryschema.GroupVersion{}, defaultTLS)
if err != nil {
return nil, err
}
overrides.ClusterInfo.Server = host.String()
}
if v, ok := k8sGetOk(configData, "username"); ok {
overrides.AuthInfo.Username = v.(string)
}
if v, ok := k8sGetOk(configData, "password"); ok {
overrides.AuthInfo.Password = v.(string)
}
if v, ok := k8sGetOk(configData, "client_key"); ok {
overrides.AuthInfo.ClientKeyData = bytes.NewBufferString(v.(string)).Bytes()
}
if v, ok := k8sGetOk(configData, "token"); ok {
overrides.AuthInfo.Token = v.(string)
}
if v, ok := k8sGetOk(configData, "proxy_url"); ok {
overrides.ClusterDefaults.ProxyURL = v.(string)
}
if v, ok := k8sGetOk(configData, "exec"); ok {
exec := &clientcmdapi.ExecConfig{}
if spec, ok := v.([]interface{})[0].(map[string]interface{}); ok {
exec.InteractiveMode = clientcmdapi.IfAvailableExecInteractiveMode
exec.APIVersion = spec["api_version"].(string)
exec.Command = spec["command"].(string)
exec.Args = expandStringSlice(spec["args"].([]interface{}))
for kk, vv := range spec["env"].(map[string]interface{}) {
exec.Env = append(exec.Env, clientcmdapi.ExecEnvVar{Name: kk, Value: vv.(string)})
}
} else {
log.Printf("[ERROR] Failed to parse exec")
return nil, fmt.Errorf("failed to parse exec")
}
overrides.AuthInfo.Exec = exec
}
overrides.Context.Namespace = "default"
if namespace != nil {
overrides.Context.Namespace = *namespace
}
client := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loader, overrides)
if client == nil {
log.Printf("[ERROR] Failed to initialize kubernetes config")
return nil, nil
}
log.Printf("[INFO] Successfully initialized kubernetes config")
return &KubeConfig{ClientConfig: client}, nil
}