k8s.io/test-infra@v0.0.0-20240520184403-27c6b4c223d8/gencred/pkg/kubeconfig/kubeconfig.go (about) 1 /* 2 Copyright 2019 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package kubeconfig 18 19 import ( 20 "fmt" 21 22 "k8s.io/client-go/kubernetes" 23 clientcmdapi "k8s.io/client-go/tools/clientcmd/api/v1" 24 "sigs.k8s.io/yaml" 25 ) 26 27 // getServerAddress gets the address of the kubernetes cluster. 28 func getServerAddress(clientset kubernetes.Interface) string { 29 url := clientset.Discovery().RESTClient().Get().URL() 30 return fmt.Sprintf("%s://%s", url.Scheme, url.Host) 31 } 32 33 // CreateKubeConfig creates a standard kube config. 34 func CreateKubeConfig(clientset kubernetes.Interface, name string, caPEM []byte, authInfo clientcmdapi.AuthInfo) ([]byte, error) { 35 config := clientcmdapi.Config{ 36 APIVersion: "v1", 37 Kind: "Config", 38 Clusters: []clientcmdapi.NamedCluster{ 39 { 40 Name: name, 41 Cluster: clientcmdapi.Cluster{ 42 Server: getServerAddress(clientset), 43 CertificateAuthorityData: caPEM, 44 }, 45 }, 46 }, 47 AuthInfos: []clientcmdapi.NamedAuthInfo{ 48 { 49 Name: name, 50 AuthInfo: authInfo, 51 }, 52 }, 53 Contexts: []clientcmdapi.NamedContext{ 54 { 55 Name: name, 56 Context: clientcmdapi.Context{ 57 Cluster: name, 58 AuthInfo: name, 59 }, 60 }, 61 }, 62 CurrentContext: name, 63 } 64 65 configYaml, err := yaml.Marshal(config) 66 if err != nil { 67 return nil, err 68 } 69 70 return configYaml, nil 71 }