SeattleOrBayArea
SeattleOrBayArea

Reputation: 3118

Find running container's user ID in Kubernetes for all pods in a cluster

I am trying to find out in which user's context do the containers run and looking for a way to get this data without exec into each container. Since I am working on a cluster with many pods, it is nearly impossible to go inside each container and get the user.

Is there a command that I can use for this?

Upvotes: 1

Views: 3242

Answers (2)

papanito
papanito

Reputation: 2584

I did not find an alternative way, so I exec into the pods

for ns in $(kubectl get ns --no-headers); do
    for pod in $(kubectl get pods -n $ns --no-headers -o custom-columns=NAME:metadata.name); do
        userid=$(kubectl exec $pod -n $ns -- /bin/sh -c "id -u \$(whoami)")
        groupid=$(kubectl exec $pod -n $ns -- /bin/sh -c "id -g \$(whoami)")
        echo pod "$pod" in ns "$ns": "$userid/$groupid"
    done;
done;

However, this is not ideal cause exec may not work on all pods and the script will throw errors.

Upvotes: 1

Arghya Sadhu
Arghya Sadhu

Reputation: 44707

You can use Falco for this.Falco communicates with the provided K8s API server to decorate events with the K8s pod/namespace/deployment/etc. associated with the event. Below is an example of Falco alerts from here. You can see user=root

output: "Namespace change (setns) by unexpected program (user=%user.name command=%proc.cmdline parent=%proc.pname %container.info)"

$ falco
15:42:35.347416068: Warning Namespace change (setns) by unexpected program (user=root command=test_program parent=hyperkube k8s-kubelet (id=4a4021c50439))

$ falco -pk -k <k8s api server url>
15:42:35.347416068: Warning Namespace change (setns) by unexpected program (user=root command=test_program parent=hyperkube k8s.pod=jclient-3160134038-qqaaz container=4a4021c50439)

$ falco -p "This is Some Extra" -k <k8s api server url>
15:42:35.347416068: Warning Namespace change (setns) by unexpected program (user=root command=test_program parent=hyperkube k8s-kubelet (id=4a4021c50439)) This is Some Extra

Upvotes: 2

Related Questions