Created
August 15, 2023 05:51
-
-
Save samos123/d6cfd92bd5d0db1c60cdd5b9eb7ae607 to your computer and use it in GitHub Desktop.
create-k8s-client-in-or-out-ofcluster.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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