Skip to content
This repository has been archived by the owner on Jun 29, 2022. It is now read-only.

Commit

Permalink
cli/cmd: add back support for using KUBECONFIG env variable
Browse files Browse the repository at this point in the history
After renaming --kubeconfig flag to --kubeconfig-file, we lost ability
to use kubeconfig file defined by KUBECONFIG environment variable for
installing components. This commit adds back this functionality and
improves the code of getKubeconfig() function a bit.

Closes #595

Signed-off-by: Mateusz Gozdek <mateusz@kinvolk.io>
  • Loading branch information
invidian committed Jun 9, 2020
1 parent 2258902 commit 4133c67
Showing 1 changed file with 20 additions and 7 deletions.
27 changes: 20 additions & 7 deletions cli/cmd/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@ import (
"github.com/kinvolk/lokomotive/pkg/platform"
)

const (
kubeconfigEnvVariable = "KUBECONFIG"
defaultKubeconfigPath = "~/.kube/config"
)

// getConfiguredBackend loads a backend from the given configuration file.
func getConfiguredBackend(lokoConfig *config.Config) (backend.Backend, hcl.Diagnostics) {
if lokoConfig.RootConfig.Backend == nil {
Expand Down Expand Up @@ -101,10 +106,11 @@ func expandKubeconfigPath(path string) string {
return path
}

// getKubeconfig finds the kubeconfig to be used. Precedence takes a specified
// flag or environment variable. Then the asset directory of the cluster is searched
// and finally the global default value is used. This cannot be done in Viper
// because we need the other values from Viper to find the asset directory.
// getKubeconfig finds the kubeconfig to be used. The preference is following:
// - --kubeconfig-file flag OR KUBECONFIG_FILE environent variable
// - asset directory from cluster configuration
// - KUBECONFIG environment variable
// - ~/.kube/config path, which is kubectl default one
func getKubeconfig() (string, error) {
kubeconfig := viper.GetString(kubeconfigFlag)
if kubeconfig != "" {
Expand All @@ -116,11 +122,18 @@ func getKubeconfig() (string, error) {
return "", err
}

if assetDir != "" {
return expandKubeconfigPath(assetsKubeconfig(assetDir)), nil
paths := []string{
assetDir,
os.Getenv(kubeconfigEnvVariable),
}

for _, path := range paths {
if path != "" {
return expandKubeconfigPath(path), nil
}
}

return expandKubeconfigPath("~/.kube/config"), nil
return expandKubeconfigPath(defaultKubeconfigPath), nil
}

func assetsKubeconfig(assetDir string) string {
Expand Down

0 comments on commit 4133c67

Please sign in to comment.