fix: strip trailing newline in get_default_target_namespace when reading in-cluster serviceaccount namespace
- Dominant language
- Python
- Stars
- 148
- Forks
- 262
- Avg merge
- 1d 2h
- Merged PRs (30d)
- 1
Description
### What happened?
When running the SDK inside a Kubernetes pod (where `is_running_in_k8s()` evaluates to `True`), [`get_default_target_namespace()`](file:///c:/Users/Vishal/Code_File/Repo%20Folder/sdk/kubeflow/common/utils.py#L25-L39) in [`kubeflow/common/utils.py`](file:///c:/Users/Vishal/Code_File/Repo%20Folder/sdk/kubeflow/common/utils.py#L38-L39) reads the default namespace from `/var/run/secrets/kubernetes.io/serviceaccount/namespace` using `f.readline()`:
```python
with open("/var/run/secrets/kubernetes.io/serviceaccount/namespace") as f:
return f.readline()
```
In Kubernetes pods, the mounted service account file contains the namespace string followed by a newline character (`\n`). Because `f.readline()` returns the line with the trailing newline character intact without calling `.strip()`, `get_default_target_namespace()` returns a string containing a trailing newline (e.g., `'default\n'` or `'kubeflow\n'`).
When this namespace value is used by backend initialization (such as `KubernetesBackendConfig`), downstream Kubernetes API calls (e.g. `list_namespaced_custom_object` or `read_namespaced_config_map`) and custom resource metadata incorporate the trailing newline (`"default\n"`), causing Kubernetes API validation errors or HTTP request failures due to invalid RFC 1123 DNS label formatting.
### What did you expect to happen?
`get_default_target_namespace()` should return a clean namespace string without trailing whitespace or newline characters (e.g., `'default'`), enabling in-cluster SDK operations and Kubernetes API calls to succeed seamlessly.
### Environment
Kubernetes version:
```bash
$ kubectl version
Client Version: v1.30.0
```
Kubeflow Trainer version:
```bash
$ kubectl get pods -n kubeflow -l app.kubernetes.io/name=trainer -o jsonpath="{.items[*].spec.containers[*].image}"
```
Kubeflow Python SDK version:
```bash
$ pip show kubeflow
Name: kubeflow
Version: 0.4.1
```
### Impacted by this bug?
Give it a 👍 We prioritize the issues with most 👍
Contributor guide
Assessment
This issue has not been assessed yet.