Golang client API: clientset inside cluster vs outside of cluster

What is the best way to detect whether a golang app is running inside a cluster or outside of one?

	if _, inCluster := os.LookupEnv("KUBERNETES_SERVICE_HOST"); inCluster == true {

Moreover, I need a clientset, which in the cluster I think I can get like so:

		config, err := restClient.InClusterConfig()
		client.RestConfig = config
		if err != nil {
			return nil, err
		}
		client.Clientset, err = coreClient.NewForConfig(config)
		if err != nil {
			return nil, err
		}

But outside of the cluster, I think I can get it like this:

	var kubeconfig *string
	if home := homeDir(); home != "" {
		kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")
	} else {
		kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
	}
	flag.Parse()
	config, err := cmdClient.BuildConfigFromFlags("", *kubeconfig)
	client.RestConfig = config
	if err != nil {
		return nil, err
	}
	client.Clientset, err = coreClient.NewForConfig(config)
	if err != nil {
		return nil, err
	}

But maybe there is some better way, or a universal config/discovery thing that would be better. Looking for any guidance, criticism or heckling you may provide.
:grinning:
Thanks!

Best,
Steve

I’m pretty lazy. With the python client, I do this:

try:
    config.load_kube_config()
except:
    # load_kube_config throws if there is no config, but does not document what it throws, so I can't rely on any particular type here
    config.load_incluster_config()

Looking at the in cluster client and CRUD examples, I feel like you should be able to build some similar logic and make the --kubeconfig flag override all other behavior.

1 Like

From Lars Ekman:

func getClientset() (*kubernetes.Clientset, error) {
        config, err := rest.InClusterConfig()
        if err != nil {
                kubeconfig :=
                        clientcmd.NewDefaultClientConfigLoadingRules().GetDefaultFilename()
                config, err = clientcmd.BuildConfigFromFlags("", kubeconfig)
                if err != nil {
                        return nil, err
                }
        }
        return kubernetes.NewForConfig(config)
}