I need to find out if a container is running in k8s and find the namespace from within the container itself, using PowerShell I was able to find it in C:\var\run\secrets\kubernetes.io\serviceaccount\namespace but my understanding is that this path does not always exist, or does it? Are there other methods of doing this?
0
votes
2 Answers
0
votes
0
votes
If a windows container is running in K8s, then you can assume that
- It will have a few environment variables not otherwise present, such as the Kubernetes default services IP address. Thus, one check you can do is print the environment variables from powershell in your container, by running
kubectl exec -t -i my-pod powershell
and executingGet-ChildItem env
- It will have an IP address that most likely is in the kubernetes pod IP space, that is, by running
ifconfig
you will see that it has an IP address that is NOT the same as the IP address of docker containers that are running. - It will be able to resolve services within the Kubernetes cluster, for example
Resolve-DnsName -Name kubernetes
will return an ip address (often times, something like 10.96.0.1 - It may be able to query the apiserver using any go-client, or even kubectl in the container which can read default container injected service accounts to authenticate to the apiserver. This means you could potentially do
kubectl.exe get pods -A
and grep the namespace of your own pods hostname from this list. - It can also access apiserver info using the downward API, and thats the normal way to do this type of operation. The "downward API", https://kubernetes.io/docs/tasks/inject-data-application/downward-api-volume-expose-pod-information/, is used in two common ways (see other answer as well, which shows a specific way to inject the info you want): injection via env vars, or injection via volume mounts. If these are actively both not allowed for some reason in your containers, then, your right it isn't going to be reliable. But for most clusters, at least some metadata should be exposed to container that are running, so whatever you did in the original answer is probably valid.