...

Source file src/k8s.io/kubernetes/test/utils/kubeconfig/kubeconfig.go

Documentation: k8s.io/kubernetes/test/utils/kubeconfig

     1  /*
     2  Copyright 2022 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  	"k8s.io/client-go/rest"
    21  	clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
    22  )
    23  
    24  // CreateKubeConfig converts a [rest.Config] into a [clientcmdapi.Config]
    25  // which then can be written to a file with [clientcmd.WriteToFile].
    26  func CreateKubeConfig(clientCfg *rest.Config) *clientcmdapi.Config {
    27  	clusterNick := "cluster"
    28  	userNick := "user"
    29  	contextNick := "context"
    30  
    31  	config := clientcmdapi.NewConfig()
    32  
    33  	credentials := clientcmdapi.NewAuthInfo()
    34  	credentials.Token = clientCfg.BearerToken
    35  	credentials.TokenFile = clientCfg.BearerTokenFile
    36  	credentials.ClientCertificate = clientCfg.TLSClientConfig.CertFile
    37  	if len(credentials.ClientCertificate) == 0 {
    38  		credentials.ClientCertificateData = clientCfg.TLSClientConfig.CertData
    39  	}
    40  	credentials.ClientKey = clientCfg.TLSClientConfig.KeyFile
    41  	if len(credentials.ClientKey) == 0 {
    42  		credentials.ClientKeyData = clientCfg.TLSClientConfig.KeyData
    43  	}
    44  	config.AuthInfos[userNick] = credentials
    45  
    46  	cluster := clientcmdapi.NewCluster()
    47  	cluster.Server = clientCfg.Host
    48  	cluster.CertificateAuthority = clientCfg.CAFile
    49  	if len(cluster.CertificateAuthority) == 0 {
    50  		cluster.CertificateAuthorityData = clientCfg.CAData
    51  	}
    52  	cluster.InsecureSkipTLSVerify = clientCfg.Insecure
    53  	config.Clusters[clusterNick] = cluster
    54  
    55  	context := clientcmdapi.NewContext()
    56  	context.Cluster = clusterNick
    57  	context.AuthInfo = userNick
    58  	config.Contexts[contextNick] = context
    59  	config.CurrentContext = contextNick
    60  
    61  	return config
    62  }
    63  

View as plain text