Detect whether the current process is running on host, Docker, or Kubernetes.
(
environ: dict[str, str] | None = None,
)
| 40 | |
| 41 | |
| 42 | def detect_runtime_environment( |
| 43 | environ: dict[str, str] | None = None, |
| 44 | ) -> RuntimeEnvironment: |
| 45 | """Detect whether the current process is running on host, Docker, or Kubernetes.""" |
| 46 | |
| 47 | environ = environ or os.environ |
| 48 | cgroup_content = _read_cgroup_content().lower() |
| 49 | |
| 50 | in_kubernetes = bool( |
| 51 | environ.get("KUBERNETES_SERVICE_HOST") |
| 52 | or Path("/var/run/secrets/kubernetes.io/serviceaccount").exists() |
| 53 | or "kubepods" in cgroup_content |
| 54 | or "kubernetes" in cgroup_content |
| 55 | ) |
| 56 | in_docker = bool( |
| 57 | Path("/.dockerenv").exists() |
| 58 | or Path("/run/.containerenv").exists() |
| 59 | or any( |
| 60 | marker in cgroup_content |
| 61 | for marker in ("docker", "containerd", "libpod", "podman") |
| 62 | ) |
| 63 | ) |
| 64 | |
| 65 | return RuntimeEnvironment( |
| 66 | in_container=in_kubernetes or in_docker, |
| 67 | in_docker=in_docker, |
| 68 | in_kubernetes=in_kubernetes, |
| 69 | ) |
| 70 | |
| 71 | |
| 72 | def load_runtime_target_from_env_file(env_path: str | Path = ".env") -> str | None: |
no test coverage detected