diff --git a/pkg/envtest/envtest_test.go b/pkg/envtest/envtest_test.go index 7214697e9d..ae30a8405a 100644 --- a/pkg/envtest/envtest_test.go +++ b/pkg/envtest/envtest_test.go @@ -28,7 +28,7 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/kubernetes/scheme" - + "k8s.io/client-go/tools/clientcmd" "sigs.k8s.io/controller-runtime/pkg/client" ) @@ -682,6 +682,14 @@ var _ = Describe("Test", func() { }) }) + It("should set a working KubeConfig", func() { + kubeconfigRESTConfig, err := clientcmd.RESTConfigFromKubeConfig(env.KubeConfig) + Expect(err).ToNot(HaveOccurred()) + kubeconfigClient, err := client.New(kubeconfigRESTConfig, client.Options{Scheme: s}) + Expect(err).NotTo(HaveOccurred()) + Expect(kubeconfigClient.List(context.Background(), &apiextensionsv1.CustomResourceDefinitionList{})).To(Succeed()) + }) + It("should update CRDs if already present in the cluster", func() { // Install only the CRDv1 multi-version example diff --git a/pkg/envtest/server.go b/pkg/envtest/server.go index 25eaa51879..9bb81ed2ab 100644 --- a/pkg/envtest/server.go +++ b/pkg/envtest/server.go @@ -126,6 +126,10 @@ type Environment struct { // loading. Config *rest.Config + // KubeConfig provides []byte of a kubeconfig file to talk to the apiserver + // It's automatically populated if not set based on the `Config` + KubeConfig []byte + // CRDInstallOptions are the options for installing CRDs. CRDInstallOptions CRDInstallOptions @@ -291,6 +295,14 @@ func (te *Environment) Start() (*rest.Config, error) { te.Config = adminUser.Config() } + if len(te.KubeConfig) == 0 { + var err error + te.KubeConfig, err = controlplane.KubeConfigFromREST(te.Config) + if err != nil { + return nil, fmt.Errorf("unable to set KubeConfig field: %w", err) + } + } + // Set the default scheme if nil. if te.Scheme == nil { te.Scheme = scheme.Scheme