Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How do I create kube config file from rest.Config object? #711

Closed
vadasambar opened this issue Nov 11, 2019 · 15 comments
Closed

How do I create kube config file from rest.Config object? #711

vadasambar opened this issue Nov 11, 2019 · 15 comments
Labels
lifecycle/rotten Denotes an issue or PR that has aged beyond stale and will be auto-closed.

Comments

@vadasambar
Copy link
Member

vadasambar commented Nov 11, 2019

I have rest.Config (https://godoc.org/k8s.io/client-go/rest#Config) object in my code. I want to write it to a kube config file to use it later. How would I go about writing it to a file?

@vadasambar
Copy link
Member Author

I think I will need to convert my rest.Config to api.Config first.

@aayush-rangwala
Copy link

Following. Have similar use case, to convert rest config to kubeconfig file

@fejta-bot
Copy link

Issues go stale after 90d of inactivity.
Mark the issue as fresh with /remove-lifecycle stale.
Stale issues rot after an additional 30d of inactivity and eventually close.

If this issue is safe to close now please do so with /close.

Send feedback to sig-testing, kubernetes/test-infra and/or fejta.
/lifecycle stale

@k8s-ci-robot k8s-ci-robot added the lifecycle/stale Denotes an issue or PR has remained open with no activity and has become stale. label Apr 12, 2020
@vadasambar
Copy link
Member Author

@fejta-bot
Copy link

Stale issues rot after 30d of inactivity.
Mark the issue as fresh with /remove-lifecycle rotten.
Rotten issues close after an additional 30d of inactivity.

If this issue is safe to close now please do so with /close.

Send feedback to sig-testing, kubernetes/test-infra and/or fejta.
/lifecycle rotten

@k8s-ci-robot k8s-ci-robot added lifecycle/rotten Denotes an issue or PR that has aged beyond stale and will be auto-closed. and removed lifecycle/stale Denotes an issue or PR has remained open with no activity and has become stale. labels May 16, 2020
@fejta-bot
Copy link

Rotten issues close after 30d of inactivity.
Reopen the issue with /reopen.
Mark the issue as fresh with /remove-lifecycle rotten.

Send feedback to sig-testing, kubernetes/test-infra and/or fejta.
/close

@k8s-ci-robot
Copy link
Contributor

@fejta-bot: Closing this issue.

In response to this:

Rotten issues close after 30d of inactivity.
Reopen the issue with /reopen.
Mark the issue as fresh with /remove-lifecycle rotten.

Send feedback to sig-testing, kubernetes/test-infra and/or fejta.
/close

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes/test-infra repository.

@daxmc99
Copy link

daxmc99 commented Nov 5, 2020

This works

c, err := clientcmd.NewDefaultClientConfigLoadingRules().Load()
if err != nil {
	os.Exit(1)
}
clientConfig := clientcmd.NewDefaultClientConfig(*c, nil)
config, err = clientConfig.ClientConfig()

@Jordan396
Copy link

In my case, I had a rest.Config from the cluster administrator's kube config file, and I needed to generate a kube config file for a new user using api.Config. Following the bash script approach to generating a kube config file, I formatted the parameters of api.Config using fields extracted from the cluster api with the rest.config.

func (kc *KubeController) GenerateKubeConfiguration(namespace string) (string, error) {
	// Get secret list for namespace
	secretList, err := kc.clientset.CoreV1().Secrets(namespace).List(context.TODO(), metav1.ListOptions{})
	if err != nil {
		return "", err
	}

	// Get secret containing authentication data
	secret := secretList.Items[1]

	clusters := make(map[string]*clientcmdapi.Cluster)
	clusters["default-cluster"] = &clientcmdapi.Cluster{
		Server:                   kc.restconfig.Host,
		CertificateAuthorityData: secret.Data["ca.crt"],
	}

	contexts := make(map[string]*clientcmdapi.Context)
	contexts["default-context"] = &clientcmdapi.Context{
		Cluster:   "default-cluster",
		Namespace: namespace,
		AuthInfo:  namespace,
	}

	authinfos := make(map[string]*clientcmdapi.AuthInfo)
	authinfos[namespace] = &clientcmdapi.AuthInfo{
		Token: string(secret.Data["token"]),
	}

	clientConfig := clientcmdapi.Config{
		Kind:           "Config",
		APIVersion:     "v1",
		Clusters:       clusters,
		Contexts:       contexts,
		CurrentContext: "default-context",
		AuthInfos:      authinfos,
	}
	clientcmd.WriteToFile(clientConfig,  "/var/tmp/" + namespace + ".kubeconfig")
}

@OyutianO
Copy link

OyutianO commented Dec 9, 2020

In my case, I had a rest.Config from the cluster administrator's kube config file, and I needed to generate a kube config file for a new user using api.Config. Following the bash script approach to generating a kube config file, I formatted the parameters of api.Config using fields extracted from the cluster api with the rest.config.

func (kc *KubeController) GenerateKubeConfiguration(namespace string) (string, error) {
	// Get secret list for namespace
	secretList, err := kc.clientset.CoreV1().Secrets(namespace).List(context.TODO(), metav1.ListOptions{})
	if err != nil {
		return "", err
	}

	// Get secret containing authentication data
	secret := secretList.Items[1]

	clusters := make(map[string]*clientcmdapi.Cluster)
	clusters["default-cluster"] = &clientcmdapi.Cluster{
		Server:                   kc.restconfig.Host,
		CertificateAuthorityData: secret.Data["ca.crt"],
	}

	contexts := make(map[string]*clientcmdapi.Context)
	contexts["default-context"] = &clientcmdapi.Context{
		Cluster:   "default-cluster",
		Namespace: namespace,
		AuthInfo:  namespace,
	}

	authinfos := make(map[string]*clientcmdapi.AuthInfo)
	authinfos[namespace] = &clientcmdapi.AuthInfo{
		Token: string(secret.Data["token"]),
	}

	clientConfig := clientcmdapi.Config{
		Kind:           "Config",
		APIVersion:     "v1",
		Clusters:       clusters,
		Contexts:       contexts,
		CurrentContext: "default-context",
		AuthInfos:      authinfos,
	}
	clientcmd.WriteToFile(clientConfig,  "/var/tmp/" + namespace + ".kubeconfig")
}

very useful!!!

@rainbowBPF2
Copy link

This works

c, err := clientcmd.NewDefaultClientConfigLoadingRules().Load()
if err != nil {
	os.Exit(1)
}
clientConfig := clientcmd.NewDefaultClientConfig(*c, nil)
config, err = clientConfig.ClientConfig()

I found a new way. Test ok~
var kubeconfig * string
// update kubeconfig content.

bytesArray := []byte(*kubeconfig)

clientConfig ,err:= clientcmd.NewClientConfigFromBytes(bytesArray)
if err!=nil {
	logs.Error(err.Error())
	return nil
}

restConfig, _ := clientConfig.ClientConfig()
clientSet, err := kubernetes.NewForConfig(restConfig)

@shamhub
Copy link

shamhub commented Aug 6, 2022

#1144

@Jordan396

@shamhub
Copy link

shamhub commented Aug 6, 2022

#1144

@rainbowBPF2

@ekesken
Copy link

ekesken commented Aug 4, 2023

just an easier way to create a kubeconfig file from the rest.Config coming from sigs.k8s.io/controller-runtime/pkg/envtestwhich is used in test suites generated by kubebuilder:

import (
	"os"

	"k8s.io/client-go/rest"
	clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
)


func CreateKubeconfigFileForRestConfig(restConfig rest.Config) string {
	clusters := make(map[string]*clientcmdapi.Cluster)
	clusters["default-cluster"] = &clientcmdapi.Cluster{
		Server:                   restConfig.Host,
		CertificateAuthorityData: restConfig.CAData,
	}
	contexts := make(map[string]*clientcmdapi.Context)
	contexts["default-context"] = &clientcmdapi.Context{
		Cluster:  "default-cluster",
		AuthInfo: "default-user",
	}
	authinfos := make(map[string]*clientcmdapi.AuthInfo)
	authinfos["default-user"] = &clientcmdapi.AuthInfo{
		ClientCertificateData: restConfig.CertData,
		ClientKeyData:         restConfig.KeyData,
	}
	clientConfig := clientcmdapi.Config{
		Kind:           "Config",
		APIVersion:     "v1",
		Clusters:       clusters,
		Contexts:       contexts,
		CurrentContext: "default-context",
		AuthInfos:      authinfos,
	}
	kubeConfigFile, _ := os.CreateTemp("", "kubeconfig")
	_ = clientcmd.WriteToFile(clientConfig, kubeConfigFile.Name())
	return kubeConfigFile.Name()
}

@delthas
Copy link

delthas commented Nov 3, 2023

just an easier way to create a kubeconfig file from the rest.Config coming from sigs.k8s.io/controller-runtime/pkg/envtestwhich is used in test suites generated by kubebuilder:

This will only work on a rest.Config object having a cert and key data. The other way to do it by @Jordan396 above works on any rest.Config object (it just uses the API server host).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
lifecycle/rotten Denotes an issue or PR that has aged beyond stale and will be auto-closed.
Projects
None yet
Development

No branches or pull requests