Skip to content

Commit

Permalink
fix: allow access to cluster when scrapers don't have custom kubeconfig
Browse files Browse the repository at this point in the history
  • Loading branch information
adityathebe committed Jan 22, 2025
1 parent 5be4477 commit 47619a2
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions connection/environment.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"os"
osExec "os/exec"
"path/filepath"
"strings"

"github.com/flanksource/commons/logger"
"github.com/flanksource/duty/context"
Expand All @@ -18,6 +19,20 @@ import (
textTemplate "text/template"
)

// kubeEnvVars holds a list of environment variables that are commonly used
// to configure access to the default Kubernetes cluster
var kubeEnvVars = []string{
"KUBECONFIG",
"KUBERNETES_SERVICE_HOST",
"KUBERNETES_SERVICE_PORT",
"KUBERNETES_PORT_443_TCP",
"KUBERNETES_SERVICE_PORT_HTTPS",
"KUBERNETES_PORT_443_TCP_PROTO",
"KUBERNETES_PORT_443_TCP_ADDR",
"KUBERNETES_PORT",
"KUBERNETES_PORT_443_TCP_PORT",
}

// +kubebuilder:object:generate=true
type ExecConnections struct {
FromConfigItem *string `yaml:"fromConfigItem,omitempty" json:"fromConfigItem,omitempty" template:"true"`
Expand Down Expand Up @@ -102,10 +117,14 @@ func SetupConnection(ctx context.Context, connections ExecConnections, cmd *osEx
if kubernetesScrapers, found, err := unstructured.NestedSlice(scraperSpec, "kubernetes"); err != nil {
return nil, err
} else if found {
var kubeconfigFound bool

for _, kscraper := range kubernetesScrapers {
if kubeconfig, found, err := unstructured.NestedMap(kscraper.(map[string]any), "kubeconfig"); err != nil {
return nil, err
} else if found {
kubeconfigFound = true

connections.Kubernetes = &KubernetesConnection{}
if err := runtime.DefaultUnstructuredConverter.FromUnstructured(kubeconfig, &connections.Kubernetes.KubeConfig); err != nil {
return nil, err
Expand All @@ -118,6 +137,18 @@ func SetupConnection(ctx context.Context, connections ExecConnections, cmd *osEx
break
}
}

if !kubeconfigFound {
// If none of the kubernetes scrapers had kubeconfig setup,
// the scraper is using the default cluster.
// We allow these set of env vars that allow access to the default cluster.
for _, env := range os.Environ() {
key, _, ok := strings.Cut(env, "=")
if ok && lo.Contains(kubeEnvVars, key) {
cmd.Env = append(cmd.Env, env)
}
}
}
}
}

Expand Down

0 comments on commit 47619a2

Please sign in to comment.