Skip to content

Commit

Permalink
the pod namespace is now passed using the env var POD_NAMESPACE
Browse files Browse the repository at this point in the history
Before, the namespace used to be guessed by looking up the service
account's `namespace` file at

  /var/run/secrets/kubernetes.io/serviceaccount/namespace

Although this way is "OK" since the agent will always have a service
account token mounted to the pod, we decided that passing the namespace
to the pod using an explicit env var would be better.
  • Loading branch information
maelvls committed Oct 14, 2024
1 parent 601b594 commit bc2958c
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 55 deletions.
26 changes: 6 additions & 20 deletions pkg/agent/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,6 @@ import (
"github.com/jetstack/preflight/pkg/version"
)

const (
inClusterNamespacePath = "/var/run/secrets/kubernetes.io/serviceaccount/namespace"
)

// Config wraps the options for a run of the agent.
type Config struct {
// Deprecated: Schedule doesn't do anything. Use `period` instead.
Expand Down Expand Up @@ -154,9 +150,8 @@ type AgentCmdFlags struct {
// InstallNS (--install-namespace) is the namespace in which the agent is
// running in. Only needed when running the agent outside of Kubernetes.
//
// May be left empty when running in Kubernetes. In this case, the namespace
// is read from the file
// /var/run/secrets/kubernetes.io/serviceaccount/namespace.
// May be left empty when running in Kubernetes. In Kubernetes, the
// namespace is read from the environment variable `POD_NAMESPACE`.
InstallNS string

// Profiling (--enable-pprof) enables the pprof server.
Expand Down Expand Up @@ -726,21 +721,12 @@ func createCredentialClient(log *log.Logger, credentials client.Credentials, cfg

// Inspired by the controller-runtime project.
func getInClusterNamespace() (string, error) {
// Check whether the namespace file exists.
// If not, we are not running in cluster so can't guess the namespace.
_, err := os.Stat(inClusterNamespacePath)
if os.IsNotExist(err) {
return "", fmt.Errorf("not running in cluster, please use --install-namespace to specify the namespace in which the agent is running")
}
if err != nil {
return "", fmt.Errorf("error checking namespace file: %w", err)
ns := os.Getenv("POD_NAMESPACE")
if ns != "" {
return ns, nil
}

namespace, err := os.ReadFile(inClusterNamespacePath)
if err != nil {
return "", fmt.Errorf("error reading namespace file: %w", err)
}
return string(namespace), nil
return "", fmt.Errorf("POD_NAMESPACE env var not set, meaning that you are probably not running in cluster. Please use --install-namespace or POD_NAMESPACE to specify the namespace in which the agent is running.")
}

func reMarshal(rawConfig interface{}, config datagatherer.Config) error {
Expand Down
Loading

0 comments on commit bc2958c

Please sign in to comment.