Skip to content

Instantly share code, notes, and snippets.

@samos123
Created August 15, 2023 05:51
Show Gist options
  • Save samos123/d6cfd92bd5d0db1c60cdd5b9eb7ae607 to your computer and use it in GitHub Desktop.
Save samos123/d6cfd92bd5d0db1c60cdd5b9eb7ae607 to your computer and use it in GitHub Desktop.
create-k8s-client-in-or-out-ofcluster.go
func CreateKubernetesClient() (*kubernetes.Clientset, error) {
// Try in-cluster config
config, err := rest.InClusterConfig()
if err != nil {
// If there's an error, it means we're not in-cluster, try out-of-cluster config
kubeconfig := os.Getenv("KUBECONFIG") // Path to a kubeconfig. Only required if out-of-cluster
if kubeconfig == "" {
kubeconfig = os.Getenv("HOME") + "/.kube/config"
}
config, err = clientcmd.BuildConfigFromFlags("", kubeconfig)
if err != nil {
return nil, fmt.Errorf("failed to create out-of-cluster config: %v", err)
}
}
return kubernetes.NewForConfig(config)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment