Vishwanath Joshi
Vishwanath Joshi

Reputation: 129

Kubernetes NetworkPolicy - Is there a way to identify which NetworkPolicies are applied to Pods

We have 3-4 different NetworkPolicy in our Namespace and they are applied based on Pod Selector. Want to know is there any way from Pod side to know which NetworkPolicy is applied on it?

Upvotes: -1

Views: 425

Answers (2)

Harsh Manvar
Harsh Manvar

Reputation: 30160

If POD selector used you can use the simple way

kubectl get pod -l \
  $( \
        kubectl get netpolicies <netpolicy-name> \
        -o jsonpath="{.spec.podSelector.matchLabels}"| \
        jq -r 'to_entries|map("\(.key)=\(.value)")[]' \
  )

This will get the policy selector and use it as input and list the pods

Any way from Pod side

There is no POD side you can check, however I read somewhere kubectl describe pod-name could show Network Policies I tested not showing at least in minikube

enter image description here

So you can use the above command or describe the networkpolicy itself to get POD selector and get an idea.

kubectl describe networkpolicies <name of policy> 

Upvotes: 1

akathimi
akathimi

Reputation: 1581

The output of kubectl get network policy should display the pod-selector. After that you can use kubectl get pod -l key=value to list the pods affected.

you can automate this using a bash script/function.

I would also recommend checking "kubectl np-viewer" which is a kubectl plugin, can be found here. This plugin has what you are asking for out of box.

kubectl np-viewer -p pod-name prints network policies rules affecting a specific pod in the current namespace

Upvotes: 1

Related Questions