本文整理汇总了Golang中k8s/io/kubernetes/pkg/client/restclient.Config.Host方法的典型用法代码示例。如果您正苦于以下问题:Golang Config.Host方法的具体用法?Golang Config.Host怎么用?Golang Config.Host使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类k8s/io/kubernetes/pkg/client/restclient.Config
的用法示例。
在下文中一共展示了Config.Host方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestOAuthDisabled
func TestOAuthDisabled(t *testing.T) {
testutil.RequireEtcd(t)
defer testutil.DumpEtcdOnFailure(t)
// Build master config
masterOptions, err := testserver.DefaultMasterOptions()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
// Disable OAuth
masterOptions.OAuthConfig = nil
// Start server
clusterAdminKubeConfig, err := testserver.StartConfiguredMaster(masterOptions)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
client, err := testutil.GetClusterAdminKubeClient(clusterAdminKubeConfig)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
clientConfig, err := testutil.GetClusterAdminClientConfig(clusterAdminKubeConfig)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
// Make sure cert auth still works
namespaces, err := client.Namespaces().List(kapi.ListOptions{})
if err != nil {
t.Fatalf("Unexpected error %v", err)
}
if len(namespaces.Items) == 0 {
t.Errorf("Expected namespaces, got none")
}
// Use the server and CA info
anonConfig := restclient.Config{}
anonConfig.Host = clientConfig.Host
anonConfig.CAFile = clientConfig.CAFile
anonConfig.CAData = clientConfig.CAData
// Make sure we can't authenticate using OAuth
if _, err := tokencmd.RequestToken(&anonConfig, nil, "username", "password"); err == nil {
t.Error("Expected error, got none")
}
}
示例2: GetKubeClientConfig
// GetKubeClientConfig returns rest client configuration based on the passed url.
func GetKubeClientConfig(uri *url.URL) (*kube_rest.Config, error) {
var (
kubeConfig *kube_rest.Config
err error
)
opts := uri.Query()
configOverrides, err := getConfigOverrides(uri)
if err != nil {
return nil, err
}
inClusterConfig := defaultInClusterConfig
if len(opts["inClusterConfig"]) > 0 {
inClusterConfig, err = strconv.ParseBool(opts["inClusterConfig"][0])
if err != nil {
return nil, err
}
}
if inClusterConfig {
kubeConfig, err = kube_rest.InClusterConfig()
if err != nil {
return nil, err
}
if configOverrides.ClusterInfo.Server != "" {
kubeConfig.Host = configOverrides.ClusterInfo.Server
}
kubeConfig.GroupVersion = &schema.GroupVersion{Version: configOverrides.ClusterInfo.APIVersion}
kubeConfig.Insecure = configOverrides.ClusterInfo.InsecureSkipTLSVerify
if configOverrides.ClusterInfo.InsecureSkipTLSVerify {
kubeConfig.TLSClientConfig.CAFile = ""
}
} else {
authFile := ""
if len(opts["auth"]) > 0 {
authFile = opts["auth"][0]
}
if authFile != "" {
if kubeConfig, err = kube_client_cmd.NewNonInteractiveDeferredLoadingClientConfig(
&kube_client_cmd.ClientConfigLoadingRules{ExplicitPath: authFile},
configOverrides).ClientConfig(); err != nil {
return nil, err
}
} else {
kubeConfig = &kube_rest.Config{
Host: configOverrides.ClusterInfo.Server,
Insecure: configOverrides.ClusterInfo.InsecureSkipTLSVerify,
}
kubeConfig.GroupVersion = &schema.GroupVersion{Version: configOverrides.ClusterInfo.APIVersion}
}
}
if len(kubeConfig.Host) == 0 {
return nil, fmt.Errorf("invalid kubernetes master url specified")
}
if len(kubeConfig.GroupVersion.Version) == 0 {
return nil, fmt.Errorf("invalid kubernetes API version specified")
}
useServiceAccount := defaultUseServiceAccount
if len(opts["useServiceAccount"]) >= 1 {
useServiceAccount, err = strconv.ParseBool(opts["useServiceAccount"][0])
if err != nil {
return nil, err
}
}
if useServiceAccount {
// If a readable service account token exists, then use it
if contents, err := ioutil.ReadFile(defaultServiceAccountFile); err == nil {
kubeConfig.BearerToken = string(contents)
}
}
return kubeConfig, nil
}
示例3: TestOAuthLDAP
//.........这里部分代码省略.........
// serialize to YAML to make sure a complex StringSource survives a round-trip
serializedOptions, err := configapilatest.WriteYAML(masterOptions)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
// read back in
deserializedObject, err := configapilatest.ReadYAML(bytes.NewBuffer(serializedOptions))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
// assert type and proceed, using the deserialized version as our config
if deserializedOptions, ok := deserializedObject.(*configapi.MasterConfig); !ok {
t.Fatalf("unexpected object: %v", deserializedObject)
} else {
masterOptions = deserializedOptions
}
clusterAdminKubeConfig, err := testserver.StartConfiguredMaster(masterOptions)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
clusterAdminClientConfig, err := testutil.GetClusterAdminClientConfig(clusterAdminKubeConfig)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
clusterAdminClient, err := testutil.GetClusterAdminClient(clusterAdminKubeConfig)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
// Use the server and CA info
anonConfig := restclient.Config{}
anonConfig.Host = clusterAdminClientConfig.Host
anonConfig.CAFile = clusterAdminClientConfig.CAFile
anonConfig.CAData = clusterAdminClientConfig.CAData
// Make sure we can't authenticate as a missing user
ldapServer.ResetRequests()
if _, err := tokencmd.RequestToken(&anonConfig, nil, myUserUID, myUserPassword); err == nil {
t.Error("Expected error, got none")
}
if len(ldapServer.BindRequests) != 1 {
t.Errorf("Expected a single bind request for the search phase, got %d:\n%#v", len(ldapServer.BindRequests), ldapServer.BindRequests)
}
if len(ldapServer.SearchRequests) != 1 {
t.Errorf("Expected a single search request, got %d:\n%#v", len(ldapServer.BindRequests), ldapServer.BindRequests)
}
// Add user
ldapServer.SetPassword(myUserDN, myUserPassword)
ldapServer.AddSearchResult(myUserDN, map[string]string{emailAttr2: myUserEmail, nameAttr2: myUserName, loginAttr2: myUserUID})
// Make sure we can't authenticate with a bad password
ldapServer.ResetRequests()
if _, err := tokencmd.RequestToken(&anonConfig, nil, myUserUID, "badpassword"); err == nil {
t.Error("Expected error, got none")
}
if len(ldapServer.BindRequests) != 2 {
t.Errorf("Expected a bind request for the search phase and a failed bind request for the auth phase, got %d:\n%#v", len(ldapServer.BindRequests), ldapServer.BindRequests)
}
if len(ldapServer.SearchRequests) != 1 {
t.Errorf("Expected a single search request, got %d:\n%#v", len(ldapServer.BindRequests), ldapServer.BindRequests)
}
// Make sure we can get a token with a good password
示例4: TestOAuthBasicAuthPassword
//.........这里部分代码省略.........
MaxHeaderBytes: 1 << 20,
TLSConfig: crypto.SecureTLSConfig(&tls.Config{
// RequireAndVerifyClientCert lets us limit requests to ones with a valid client certificate
ClientAuth: tls.RequireAndVerifyClientCert,
ClientCAs: clientCAs,
}),
}
go func() {
if err := remoteServer.ListenAndServeTLS(certNames[basicAuthRemoteServerCert], certNames[basicAuthRemoteServerKey]); err != nil {
t.Fatalf("unexpected error: %v", err)
}
}()
// Build master config
testutil.RequireEtcd(t)
masterOptions, err := testserver.DefaultMasterOptions()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
masterOptions.OAuthConfig.IdentityProviders[0] = configapi.IdentityProvider{
Name: "basicauth",
UseAsChallenger: true,
UseAsLogin: true,
MappingMethod: "claim",
Provider: &configapi.BasicAuthPasswordIdentityProvider{
RemoteConnectionInfo: configapi.RemoteConnectionInfo{
URL: fmt.Sprintf("https://%s", remoteAddr),
CA: certNames[basicAuthRemoteCACert],
ClientCert: configapi.CertInfo{
CertFile: certNames[basicAuthClientCert],
KeyFile: certNames[basicAuthClientKey],
},
},
},
}
// Start server
clusterAdminKubeConfig, err := testserver.StartConfiguredMaster(masterOptions)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
clientConfig, err := testutil.GetClusterAdminClientConfig(clusterAdminKubeConfig)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
// Use the server and CA info
anonConfig := restclient.Config{}
anonConfig.Host = clientConfig.Host
anonConfig.CAFile = clientConfig.CAFile
anonConfig.CAData = clientConfig.CAData
for k, tc := range testcases {
// Specify the remote server's response
remoteStatus = tc.RemoteStatus
remoteHeaders = tc.RemoteHeaders
remoteBody = tc.RemoteBody
// Attempt to obtain a token
accessToken, err := tokencmd.RequestToken(&anonConfig, nil, expectedLogin, expectedPassword)
// Expected error
if !tc.ExpectSuccess {
if err == nil {
t.Errorf("%s: Expected error, got token=%v", k, accessToken)
} else if statusErr, ok := err.(*apierrs.StatusError); !ok {
t.Errorf("%s: expected status error, got %#v", k, err)
} else if statusErr.ErrStatus.Code != tc.ExpectErrStatus {
t.Errorf("%s: expected error status %d, got %#v", k, tc.ExpectErrStatus, statusErr)
}
continue
}
// Expected success
if err != nil {
t.Errorf("%s: Unexpected error: %v", k, err)
continue
}
// Make sure we can use the token, and it represents who we expect
userConfig := anonConfig
userConfig.BearerToken = accessToken
userClient, err := client.New(&userConfig)
if err != nil {
t.Fatalf("%s: Unexpected error: %v", k, err)
}
user, err := userClient.Users().Get("~")
if err != nil {
t.Fatalf("%s: Unexpected error: %v", k, err)
}
if user.Name != tc.ExpectUsername {
t.Fatalf("%s: Expected %v as the user, got %v", k, tc.ExpectUsername, user)
}
}
}
示例5: TestOAuthBasicAuthPassword
//.........这里部分代码省略.........
}
if req.Header.Get("Authorization") != expectedAuthHeader {
w.WriteHeader(http.StatusUnauthorized)
t.Fatalf("Unexpected auth header: %s", req.Header.Get("Authorization"))
}
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(fmt.Sprintf(`{"sub":"%s"}`, expectedUsername)))
})
// Start remote server
remoteAddr, err := testserver.FindAvailableBindAddress(9443, 9999)
if err != nil {
t.Fatalf("Couldn't get free address for test server: %v", err)
}
remoteServer := &http.Server{
Addr: remoteAddr,
Handler: remoteHandler,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
TLSConfig: crypto.SecureTLSConfig(&tls.Config{
// RequireAndVerifyClientCert lets us limit requests to ones with a valid client certificate
ClientAuth: tls.RequireAndVerifyClientCert,
ClientCAs: clientCAs,
}),
}
go func() {
if err := remoteServer.ListenAndServeTLS(certNames[basicAuthRemoteServerCert], certNames[basicAuthRemoteServerKey]); err != nil {
t.Fatalf("unexpected error: %v", err)
}
}()
// Build master config
testutil.RequireEtcd(t)
masterOptions, err := testserver.DefaultMasterOptions()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
masterOptions.OAuthConfig.IdentityProviders[0] = configapi.IdentityProvider{
Name: "basicauth",
UseAsChallenger: true,
UseAsLogin: true,
MappingMethod: "claim",
Provider: &configapi.BasicAuthPasswordIdentityProvider{
RemoteConnectionInfo: configapi.RemoteConnectionInfo{
URL: fmt.Sprintf("https://%s", remoteAddr),
CA: certNames[basicAuthRemoteCACert],
ClientCert: configapi.CertInfo{
CertFile: certNames[basicAuthClientCert],
KeyFile: certNames[basicAuthClientKey],
},
},
},
}
// Start server
clusterAdminKubeConfig, err := testserver.StartConfiguredMaster(masterOptions)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
clientConfig, err := testutil.GetClusterAdminClientConfig(clusterAdminKubeConfig)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
// Use the server and CA info
anonConfig := restclient.Config{}
anonConfig.Host = clientConfig.Host
anonConfig.CAFile = clientConfig.CAFile
anonConfig.CAData = clientConfig.CAData
// Make sure we can get a token
accessToken, err := tokencmd.RequestToken(&anonConfig, nil, expectedLogin, expectedPassword)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if len(accessToken) == 0 {
t.Errorf("Expected access token, got none")
}
// Make sure we can use the token, and it represents who we expect
userConfig := anonConfig
userConfig.BearerToken = accessToken
userClient, err := client.New(&userConfig)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
user, err := userClient.Users().Get("~")
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if user.Name != expectedUsername {
t.Fatalf("Expected username as the user, got %v", user)
}
}
示例6: TestOAuthRequestHeader
// TestOAuthRequestHeader checks the following scenarios:
// * request containing remote user header is ignored if it doesn't have client cert auth
// * request containing remote user header is honored if it has client cert auth
// * unauthenticated requests are redirected to an auth proxy
// * login command succeeds against a request-header identity provider via redirection to an auth proxy
func TestOAuthRequestHeader(t *testing.T) {
// Test data used by auth proxy
users := map[string]string{
"myusername": "mypassword",
}
// Write cert we're going to use to verify OAuth requestheader requests
caFile, err := ioutil.TempFile("", "test.crt")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
defer os.Remove(caFile.Name())
if err := ioutil.WriteFile(caFile.Name(), rootCACert, os.FileMode(0600)); err != nil {
t.Fatalf("unexpected error: %v", err)
}
// Get master config
testutil.RequireEtcd(t)
masterOptions, err := testserver.DefaultMasterOptions()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
masterURL, _ := url.Parse(masterOptions.OAuthConfig.MasterPublicURL)
// Set up an auth proxy
var proxyTransport http.RoundTripper
proxyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Decide whether to challenge
username, password, hasBasicAuth := r.BasicAuth()
if correctPassword, hasUser := users[username]; !hasBasicAuth || !hasUser || password != correctPassword {
w.Header().Set("WWW-Authenticate", "Basic realm=Protected Area")
w.WriteHeader(401)
return
}
// Swap the scheme and host to the master, keeping path and params the same
proxyURL := r.URL
proxyURL.Scheme = masterURL.Scheme
proxyURL.Host = masterURL.Host
// Build a request, copying the original method, body, and headers, overriding the remote user headers
proxyRequest, _ := http.NewRequest(r.Method, proxyURL.String(), r.Body)
proxyRequest.Header = r.Header
proxyRequest.Header.Set("My-Remote-User", username)
proxyRequest.Header.Set("SSO-User", "")
// Round trip to the back end
response, err := proxyTransport.RoundTrip(r)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
defer response.Body.Close()
// Copy response back to originator
for k, v := range response.Header {
w.Header()[k] = v
}
w.WriteHeader(response.StatusCode)
if _, err := io.Copy(w, response.Body); err != nil {
t.Fatalf("Unexpected error: %v", err)
}
}))
defer proxyServer.Close()
masterOptions.OAuthConfig.IdentityProviders[0] = configapi.IdentityProvider{
Name: "requestheader",
UseAsChallenger: true,
UseAsLogin: true,
MappingMethod: "claim",
Provider: &configapi.RequestHeaderIdentityProvider{
ChallengeURL: proxyServer.URL + "/oauth/authorize?${query}",
LoginURL: "http://www.example.com/login?then=${url}",
ClientCA: caFile.Name(),
Headers: []string{"My-Remote-User", "SSO-User"},
},
}
// Start server
clusterAdminKubeConfig, err := testserver.StartConfiguredMaster(masterOptions)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
clientConfig, err := testutil.GetClusterAdminClientConfig(clusterAdminKubeConfig)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
// Use the server and CA info, but no client cert info
anonConfig := restclient.Config{}
anonConfig.Host = clientConfig.Host
anonConfig.CAFile = clientConfig.CAFile
anonConfig.CAData = clientConfig.CAData
anonTransport, err := restclient.TransportFor(&anonConfig)
if err != nil {
//.........这里部分代码省略.........
示例7: TestOAuthHTPasswd
func TestOAuthHTPasswd(t *testing.T) {
htpasswdFile, err := ioutil.TempFile("", "test.htpasswd")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
defer os.Remove(htpasswdFile.Name())
testutil.RequireEtcd(t)
defer testutil.DumpEtcdOnFailure(t)
masterOptions, err := testserver.DefaultMasterOptions()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
masterOptions.OAuthConfig.IdentityProviders[0] = configapi.IdentityProvider{
Name: "htpasswd",
UseAsChallenger: true,
UseAsLogin: true,
MappingMethod: "claim",
Provider: &configapi.HTPasswdPasswordIdentityProvider{
File: htpasswdFile.Name(),
},
}
clusterAdminKubeConfig, err := testserver.StartConfiguredMaster(masterOptions)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
clientConfig, err := testutil.GetClusterAdminClientConfig(clusterAdminKubeConfig)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
// Use the server and CA info
anonConfig := restclient.Config{}
anonConfig.Host = clientConfig.Host
anonConfig.CAFile = clientConfig.CAFile
anonConfig.CAData = clientConfig.CAData
// Make sure we can't authenticate
if _, err := tokencmd.RequestToken(&anonConfig, nil, "username", "password"); err == nil {
t.Error("Expected error, got none")
}
// Update the htpasswd file with output of `htpasswd -n -b username password`
userpass := "username:$apr1$4Ci5I8yc$85R9vc4fOgzAULsldiUuv."
ioutil.WriteFile(htpasswdFile.Name(), []byte(userpass), os.FileMode(0600))
// Make sure we can get a token
accessToken, err := tokencmd.RequestToken(&anonConfig, nil, "username", "password")
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if len(accessToken) == 0 {
t.Errorf("Expected access token, got none")
}
// Make sure we can use the token, and it represents who we expect
userConfig := anonConfig
userConfig.BearerToken = accessToken
userClient, err := client.New(&userConfig)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
user, err := userClient.Users().Get("~")
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if user.Name != "username" {
t.Fatalf("Expected username as the user, got %v", user)
}
}
示例8: TestOAuthRequestHeader
// TestOAuthRequestHeader checks the following scenarios:
// * request containing remote user header is ignored if it doesn't have client cert auth
// * request containing remote user header is honored if it has valid client cert auth matching ClientCommonNames
// * unauthenticated requests are redirected to an auth proxy
// * login command succeeds against a request-header identity provider via redirection to an auth proxy
func TestOAuthRequestHeader(t *testing.T) {
// Test data used by auth proxy
users := map[string]string{
"myusername": "mypassword",
}
// Write cert we're going to use to verify OAuth requestheader requests
caFile, err := ioutil.TempFile("", "test.crt")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
defer os.Remove(caFile.Name())
if err := ioutil.WriteFile(caFile.Name(), rootCACert, os.FileMode(0600)); err != nil {
t.Fatalf("unexpected error: %v", err)
}
// Get master config
testutil.RequireEtcd(t)
defer testutil.DumpEtcdOnFailure(t)
masterOptions, err := testserver.DefaultMasterOptions()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
masterURL, _ := url.Parse(masterOptions.OAuthConfig.MasterPublicURL)
// Set up an auth proxy
var proxyTransport http.RoundTripper
proxyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Decide whether to challenge
username, password, hasBasicAuth := r.BasicAuth()
if correctPassword, hasUser := users[username]; !hasBasicAuth || !hasUser || password != correctPassword {
w.Header().Set("WWW-Authenticate", "Basic realm=Protected Area")
w.WriteHeader(401)
return
}
// Swap the scheme and host to the master, keeping path and params the same
proxyURL := r.URL
proxyURL.Scheme = masterURL.Scheme
proxyURL.Host = masterURL.Host
// Build a request, copying the original method, body, and headers, overriding the remote user headers
proxyRequest, _ := http.NewRequest(r.Method, proxyURL.String(), r.Body)
proxyRequest.Header = r.Header
proxyRequest.Header.Set("My-Remote-User", username)
proxyRequest.Header.Set("SSO-User", "")
// Round trip to the back end
response, err := proxyTransport.RoundTrip(r)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
defer response.Body.Close()
// Copy response back to originator
for k, v := range response.Header {
w.Header()[k] = v
}
w.WriteHeader(response.StatusCode)
if _, err := io.Copy(w, response.Body); err != nil {
t.Fatalf("Unexpected error: %v", err)
}
}))
defer proxyServer.Close()
masterOptions.OAuthConfig.IdentityProviders[0] = configapi.IdentityProvider{
Name: "requestheader",
UseAsChallenger: true,
UseAsLogin: true,
MappingMethod: "claim",
Provider: &configapi.RequestHeaderIdentityProvider{
ChallengeURL: proxyServer.URL + "/oauth/authorize?${query}",
LoginURL: "http://www.example.com/login?then=${url}",
ClientCA: caFile.Name(),
ClientCommonNames: []string{"proxy"},
Headers: []string{"My-Remote-User", "SSO-User"},
},
}
// Start server
clusterAdminKubeConfig, err := testserver.StartConfiguredMaster(masterOptions)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
clientConfig, err := testutil.GetClusterAdminClientConfig(clusterAdminKubeConfig)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
// Use the server and CA info, but no client cert info
anonConfig := restclient.Config{}
anonConfig.Host = clientConfig.Host
anonConfig.CAFile = clientConfig.CAFile
anonConfig.CAData = clientConfig.CAData
//.........这里部分代码省略.........
示例9: GetKubeClientConfig
func GetKubeClientConfig(uri *url.URL) (*kube_client.Config, error) {
var (
kubeConfig *kube_client.Config
err error
)
opts := uri.Query()
configOverrides, err := getConfigOverrides(uri)
if err != nil {
return nil, err
}
inClusterConfig := defaultInClusterConfig
if len(opts["inClusterConfig"]) > 0 {
inClusterConfig, err = strconv.ParseBool(opts["inClusterConfig"][0])
if err != nil {
return nil, err
}
}
if inClusterConfig {
kubeConfig, err = kube_client.InClusterConfig()
if err != nil {
return nil, err
}
if configOverrides.ClusterInfo.Server != "" {
kubeConfig.Host = configOverrides.ClusterInfo.Server
}
kubeConfig.GroupVersion = &unversioned.GroupVersion{Version: configOverrides.ClusterInfo.APIVersion}
kubeConfig.Insecure = configOverrides.ClusterInfo.InsecureSkipTLSVerify
if configOverrides.ClusterInfo.InsecureSkipTLSVerify {
kubeConfig.TLSClientConfig.CAFile = ""
}
} else {
authFile := ""
if len(opts["auth"]) > 0 {
authFile = opts["auth"][0]
}
if authFile != "" {
// Load structured kubeconfig data from the given path.
loader := &kubeClientCmd.ClientConfigLoadingRules{ExplicitPath: authFile}
loadedConfig, err := loader.Load()
if err != nil {
return nil, err
}
// Flatten the loaded data to a particular restclient.Config based on the current context.
if kubeConfig, err = kubeClientCmd.NewNonInteractiveClientConfig(
*loadedConfig,
loadedConfig.CurrentContext,
&kubeClientCmd.ConfigOverrides{},
loader).ClientConfig(); err != nil {
return nil, err
}
} else {
kubeConfig = &kube_client.Config{
Host: configOverrides.ClusterInfo.Server,
Insecure: configOverrides.ClusterInfo.InsecureSkipTLSVerify,
}
kubeConfig.GroupVersion = &unversioned.GroupVersion{Version: configOverrides.ClusterInfo.APIVersion}
}
}
if len(kubeConfig.Host) == 0 {
return nil, fmt.Errorf("invalid kubernetes master url specified")
}
useServiceAccount := defaultUseServiceAccount
if len(opts["useServiceAccount"]) >= 1 {
useServiceAccount, err = strconv.ParseBool(opts["useServiceAccount"][0])
if err != nil {
return nil, err
}
}
if useServiceAccount {
// If a readable service account token exists, then use it
if contents, err := ioutil.ReadFile(defaultServiceAccountFile); err == nil {
kubeConfig.BearerToken = string(contents)
}
}
kubeConfig.ContentType = "application/vnd.kubernetes.protobuf"
return kubeConfig, nil
}