2 Copyright 2017 The Kubernetes Authors.
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
8 http://www.apache.org/licenses/LICENSE-2.0
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.
26 "k8s.io/client-go/rest"
27 "k8s.io/client-go/tools/clientcmd"
28 logf "sigs.k8s.io/controller-runtime/pkg/runtime/log"
32 kubeconfig, masterURL string
33 log = logf.KBLog.WithName("client").WithName("config")
37 // TODO: Fix this to allow double vendoring this library but still register flags on behalf of users
38 flag.StringVar(&kubeconfig, "kubeconfig", "",
39 "Paths to a kubeconfig. Only required if out-of-cluster.")
41 flag.StringVar(&masterURL, "master", "",
42 "The address of the Kubernetes API server. Overrides any value in kubeconfig. "+
43 "Only required if out-of-cluster.")
46 // GetConfig creates a *rest.Config for talking to a Kubernetes apiserver.
47 // If --kubeconfig is set, will use the kubeconfig file at that location. Otherwise will assume running
48 // in cluster and use the cluster provided kubeconfig.
52 // * --kubeconfig flag pointing at a file
54 // * KUBECONFIG environment variable pointing at a file
56 // * In-cluster config if running in cluster
58 // * $HOME/.kube/config if exists
59 func GetConfig() (*rest.Config, error) {
60 // If a flag is specified with the config location, use that
61 if len(kubeconfig) > 0 {
62 return clientcmd.BuildConfigFromFlags(masterURL, kubeconfig)
64 // If an env variable is specified with the config locaiton, use that
65 if len(os.Getenv("KUBECONFIG")) > 0 {
66 return clientcmd.BuildConfigFromFlags(masterURL, os.Getenv("KUBECONFIG"))
68 // If no explicit location, try the in-cluster config
69 if c, err := rest.InClusterConfig(); err == nil {
72 // If no in-cluster config, try the default location in the user's home directory
73 if usr, err := user.Current(); err == nil {
74 if c, err := clientcmd.BuildConfigFromFlags(
75 "", filepath.Join(usr.HomeDir, ".kube", "config")); err == nil {
80 return nil, fmt.Errorf("could not locate a kubeconfig")
83 // GetConfigOrDie creates a *rest.Config for talking to a Kubernetes apiserver.
84 // If --kubeconfig is set, will use the kubeconfig file at that location. Otherwise will assume running
85 // in cluster and use the cluster provided kubeconfig.
87 // Will log an error and exit if there is an error creating the rest.Config.
88 func GetConfigOrDie() *rest.Config {
89 config, err := GetConfig()
91 log.Error(err, "unable to get kubeconfig")