Home > Software design >  How do i know which pods are covered by a network policy in k8s
How do i know which pods are covered by a network policy in k8s

Time:04-05

I have a usecase where i want to check which all the 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 mulitple ways in which one uses the pod filtering I am not sure if there is a way to tackle every possible case of pod filter that is there on the network policy and then get the list of the pods from it.

CodePudding user response:

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.

CodePudding user response:

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)")[]' \
  )
  • Related