Skip to content

Commit bc2958c

Browse files
committed
the pod namespace is now passed using the env var POD_NAMESPACE
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.
1 parent 601b594 commit bc2958c

File tree

2 files changed

+68
-55
lines changed

2 files changed

+68
-55
lines changed

pkg/agent/config.go

Lines changed: 6 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -23,10 +23,6 @@ import (
2323
"github.com/jetstack/preflight/pkg/version"
2424
)
2525

26-
const (
27-
inClusterNamespacePath = "/var/run/secrets/kubernetes.io/serviceaccount/namespace"
28-
)
29-
3026
// Config wraps the options for a run of the agent.
3127
type Config struct {
3228
// Deprecated: Schedule doesn't do anything. Use `period` instead.
@@ -154,9 +150,8 @@ type AgentCmdFlags struct {
154150
// InstallNS (--install-namespace) is the namespace in which the agent is
155151
// running in. Only needed when running the agent outside of Kubernetes.
156152
//
157-
// May be left empty when running in Kubernetes. In this case, the namespace
158-
// is read from the file
159-
// /var/run/secrets/kubernetes.io/serviceaccount/namespace.
153+
// May be left empty when running in Kubernetes. In Kubernetes, the
154+
// namespace is read from the environment variable `POD_NAMESPACE`.
160155
InstallNS string
161156

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

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

739-
namespace, err := os.ReadFile(inClusterNamespacePath)
740-
if err != nil {
741-
return "", fmt.Errorf("error reading namespace file: %w", err)
742-
}
743-
return string(namespace), nil
729+
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.")
744730
}
745731

746732
func reMarshal(rawConfig interface{}, config datagatherer.Config) error {

0 commit comments

Comments
 (0)