kubectl get nodes from pod (NetworkPolicy)

2/9/2021

I try to run using Python kubectl to get nodes inside the POD. How I should set up a Network Policy for this pod?

I tried to connect my namespace to the kube-system namespace, but it was not working.

Thanks.

-- MarcinW
kubectl
kubernetes
kubernetes-networkpolicy
kubernetes-pod

1 Answer

3/29/2021

As per Accessing the API from a Pod:

The recommended way to locate the apiserver within the pod is with the kubernetes.default.svc DNS name, which resolves to a Service IP which in turn will be routed to an apiserver.

The recommended way to authenticate to the apiserver is with a service account credential. By kube-system, a pod is associated with a service account, and a credential (token) for that service account is placed into the filesystem tree of each container in that pod, at /var/run/secrets/kubernetes.io/serviceaccount/token.

All you need is a service account with enough privileges, and use the API server DNS name as stated above. Example:

# Export the token value
export TOKEN=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)

# Use kubectl to talk internally with the API server
kubectl --insecure-skip-tls-verify=true  \
--server="https://kubernetes.default.svc:443" \
--token="${TOKEN}"                \
get nodes

The Network Policy may be restrictive and prevent this type of call, however, by default, the above should work.

-- Eduardo Baitello
Source: StackOverflow