While the kubernetes golang api example for out-of-cluster authentication works fine, and creating a service account and exporting the bearer token works great, it feels silly to write the pieces to a temporary file only to tell the API to read it. Is there an API way to pass these pieces as an object rather than write to a file?
clusterData := map[string]string{
"BEARER_TOKEN": bearerToken,
"CA_DATA": clusterCA,
"ENDPOINT": clusterUrl,
}
const kubeConfigTmpl = `
apiVersion: v1
clusters:
- cluster:
certificate-authority-data: {{.CA_DATA}}
server: {{.HOST_IP_ADDRESS}}
name: kubernetes
contexts:
- context:
cluster: kubernetes
namespace: default
user: lamdba-serviceaccount-default-kubernetes
name: lamdba-serviceaccount-default-kubernetes
current-context: lamdba-serviceaccount-default-kubernetes
kind: Config
preferences: {}
users:
- name: lamdba-serviceaccount-default-kubernetes
user:
token: {{.BEARER_TOKEN}}
`
t := template.Must(template.New("registration").Parse(kubeConfigTmpl))
buf := &bytes.Buffer{}
if err := t.Execute(buf, clusterData); err != nil {
panic(err)
}
registrationPayload := buf.String()
d1 := []byte(registrationPayload)
err := ioutil.WriteFile("/tmp/config", d1, 0644)
The rest.Config
struct passed to the NewFromConfig
client constructors lets you specify bearer tokens and/or client certificate/key data directly.
Looking at the source code, this should work:
// error handling omitted for brevity
cc, _ := clientcmd.NewClientConfigFromBytes([]byte(d1))
config, _ := cc.ClientConfig()
clientset, _ := kubernetes.NewForConfig(config)