diff --git a/pkg/integration/aws/eks.go b/pkg/integration/aws/eks.go index 21bd6f01..ee9760c3 100644 --- a/pkg/integration/aws/eks.go +++ b/pkg/integration/aws/eks.go @@ -22,12 +22,9 @@ func (e *EKSAnalyzer) Analyze(analysis common.Analyzer) ([]common.Result, error) _ = map[string]common.PreAnalysis{} svc := eks.New(e.session) // Get the name of the current cluster - var kubeconfig string - kubeconfigFromPath := viper.GetString("kubeconfig") - if kubeconfigFromPath != "" { - kubeconfig = kubeconfigFromPath - } else { - kubeconfig = filepath.Join(os.Getenv("HOME"), ".kube", "config") + kubeconfig, err := getKubeconfigPath() + if err != nil { + return cr, err } config, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig( &clientcmd.ClientConfigLoadingRules{ExplicitPath: kubeconfig}, @@ -78,3 +75,21 @@ func (e *EKSAnalyzer) Analyze(analysis common.Analyzer) ([]common.Result, error) } return cr, nil } + +// getKubeconfigPath returns the kubeconfig path to use for EKS cluster +// detection. An explicit --kubeconfig (via viper) takes precedence; otherwise +// it falls back to $HOME/.kube/config, resolving the home directory with +// os.UserHomeDir() so the default works across platforms (on Windows the HOME +// environment variable is typically unset). +func getKubeconfigPath() (string, error) { + if kubeconfig := viper.GetString("kubeconfig"); kubeconfig != "" { + return kubeconfig, nil + } + + home, err := os.UserHomeDir() + if err != nil { + return "", err + } + + return filepath.Join(home, ".kube", "config"), nil +} diff --git a/pkg/integration/aws/eks_test.go b/pkg/integration/aws/eks_test.go new file mode 100644 index 00000000..cc74a1d2 --- /dev/null +++ b/pkg/integration/aws/eks_test.go @@ -0,0 +1,42 @@ +package aws + +import ( + "os" + "path/filepath" + "testing" + + "github.com/spf13/viper" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestGetKubeconfigPath(t *testing.T) { + t.Run("uses explicit kubeconfig from viper when set", func(t *testing.T) { + viper.Reset() + t.Cleanup(viper.Reset) + explicit := filepath.Join("custom", "kubeconfig") + viper.Set("kubeconfig", explicit) + + got, err := getKubeconfigPath() + + require.NoError(t, err) + assert.Equal(t, explicit, got) + }) + + t.Run("falls back to the user home dir kubeconfig", func(t *testing.T) { + viper.Reset() + t.Cleanup(viper.Reset) + + home, err := os.UserHomeDir() + require.NoError(t, err) + + got, err := getKubeconfigPath() + + require.NoError(t, err) + assert.Equal(t, filepath.Join(home, ".kube", "config"), got) + // The fallback must resolve against the user's home directory rather + // than collapsing to a relative ".kube/config", which is what happened + // on Windows where the HOME environment variable is typically unset. + assert.True(t, filepath.IsAbs(got)) + }) +}