Skip to content

Instantly share code, notes, and snippets.

@KevinWang15
Created February 12, 2025 04:36
Show Gist options
  • Save KevinWang15/a6764c588806d021da149e2e3e139b96 to your computer and use it in GitHub Desktop.
Save KevinWang15/a6764c588806d021da149e2e3e139b96 to your computer and use it in GitHub Desktop.
GetKubeConfig
package utils
import (
"fmt"
"os"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
)
// GetKubeConfig attempts to get a Kubernetes client configuration using either:
// 1. In-cluster config (when running inside a pod)
// 2. KUBECONFIG environment variable (or default kubeconfig locations)
// and respects KUBECONTEXT if set.
func GetKubeConfig() (*rest.Config, error) {
// First try in-cluster config.
config, err := rest.InClusterConfig()
if err == nil {
return config, nil
}
// Retrieve kubeconfig path and context from the environment.
kubeconfigPath := os.Getenv("KUBECONFIG")
kubeContext := os.Getenv("KUBECONTEXT")
// Set up the client config loading rules.
// If KUBECONFIG is set, explicitly use that file.
rules := clientcmd.NewDefaultClientConfigLoadingRules()
if kubeconfigPath != "" {
rules.ExplicitPath = kubeconfigPath
}
// Prepare configuration overrides.
// If KUBECONTEXT is set, use it to override the current context.
overrides := clientcmd.ConfigOverrides{}
if kubeContext != "" {
overrides.CurrentContext = kubeContext
}
// Load the configuration using deferred loading.
config, err = clientcmd.NewNonInteractiveDeferredLoadingClientConfig(rules, &overrides).ClientConfig()
if err != nil {
if kubeconfigPath != "" {
return nil, fmt.Errorf("failed to load kubeconfig from %s: %w", kubeconfigPath, err)
}
return nil, fmt.Errorf("failed to load kubeconfig: %w", err)
}
return config, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment