ashu8912
ashu8912

Reputation: 63

How do i know which pods are covered by a network policy in k8s

I have a use case where I want to check which pods are covered by a network policy, right now my focus is only k8s generated network policies.

What's the easiest way to do this? I know we can go through each network policy and from there filter out pods but a network policy can have multiple ways in which one uses the pod filtering. I am not sure if there is a way to tackle every possible pod filter on the network policy and then get the list of the pods from it.

Upvotes: 2

Views: 1829

Answers (2)

Huu Phuong Vu
Huu Phuong Vu

Reputation: 1074

Change netpolName in the below command and run:

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

Upvotes: 0

Jyothi Kiranmayi
Jyothi Kiranmayi

Reputation: 2496

Using the podSelector field you can check all the pods that are covered by a Network Policy. Using the label mentioned in podSelector you can retrieve the list of pods which are using the NetworkPolicy.

Each NetworkPolicy includes a podSelector which selects the grouping of pods to which the policy applies. Let us consider an example policy which contains a podSelector with the label “role=db”. The example policy selects pods with the label "role=db". An empty podSelector selects all pods in the namespace.

When you run NetworkPolicy, you can check the label used for a podSelector by describing the networkpolicy.

$ kubectl describe networkpolicy <networkpolicy-name>

Pod selector will show you which labels this network policy applied too. Then you can present all the pods with this label by:

$ kubectl get pods -l <podSelector>

Refer NetworkPolicy resource for more information.

Upvotes: 1

Related Questions