From 895fee3bb5fcf268dfd05ba8fa9c0ab091f779d9 Mon Sep 17 00:00:00 2001 From: Thibault VINCENT Date: Thu, 13 Oct 2022 12:43:34 +0200 Subject: [PATCH] feat(exporter): load kubeconfig from a new argument, or env variable --- cmd/x509-certificate-exporter/main.go | 27 ++++++++++++++++----------- internal/kubernetes.go | 4 ++-- 2 files changed, 18 insertions(+), 13 deletions(-) diff --git a/cmd/x509-certificate-exporter/main.go b/cmd/x509-certificate-exporter/main.go index 96c32e1..2f206b2 100644 --- a/cmd/x509-certificate-exporter/main.go +++ b/cmd/x509-certificate-exporter/main.go @@ -40,6 +40,8 @@ func main() { kubeEnabled := getopt.BoolLong("watch-kube-secrets", 0, "scrape kubernetes secrets and monitor them") + kubeConfig := getopt.StringLong("kubeconfig", 0, "", "Path to the kubeconfig file to use for requests. Takes precedence over the KUBECONFIG environment variable, and default path (~/.kube/config).", "path") + kubeSecretTypes := stringArrayFlag{} getopt.FlagLong(&kubeSecretTypes, "secret-type", 's', "one or more kubernetes secret type & key to watch (e.g. \"kubernetes.io/tls:tls.crt\"") @@ -105,18 +107,21 @@ func main() { } if *kubeEnabled { - err := exporter.ConnectToKubernetesCluster("") - if err != nil { - log.Warn(err) + defaultKubeConfig := path.Join(os.Getenv("HOME"), ".kube", "config") + kubeConfigEnv := os.Getenv("KUBECONFIG") - configpath := os.Getenv("KUBECONFIG") - if len(configpath) == 0 { - configpath = path.Join(os.Getenv("HOME"), ".kube/config") - } - err = exporter.ConnectToKubernetesCluster(configpath) - if err != nil { - log.Fatal(err) - } + configpath := "" + if len(*kubeConfig) > 0 { + configpath = *kubeConfig + } else if len(kubeConfigEnv) > 0 { + configpath = kubeConfigEnv + } else if _, err := os.Stat(defaultKubeConfig); err == nil { + configpath = defaultKubeConfig + } + + err := exporter.ConnectToKubernetesCluster(configpath) + if err != nil { + log.Fatal(err) } } diff --git a/internal/kubernetes.go b/internal/kubernetes.go index 18ed791..d242b26 100644 --- a/internal/kubernetes.go +++ b/internal/kubernetes.go @@ -251,10 +251,10 @@ func parseKubeConfig(kubeconfigPath string) (*rest.Config, error) { var err error if len(kubeconfigPath) > 0 { - log.Infof("reading config from %s", kubeconfigPath) + log.Infof("using kubeconfig file: %s", kubeconfigPath) config, err = clientcmd.BuildConfigFromFlags("", kubeconfigPath) } else { - log.Info("fetching configuration from within the cluster") + log.Info("no kubeconfig file provided, attempting to load in-cluster configuration") config, err = rest.InClusterConfig() }