How can I apply pod selector and namespace selector, both, in the same ingress rule?

9/5/2018

Kubernetes documentation example here shows how a network policy can be applied for a source specified by either a pod selector OR a namespace selector. Can I specify a source the fulfills both constraints at the same time.

e.g. Can a source be a pod with label "tier=web" which is deployed in namespace "ingress".

P.S. For now, I have it working by adding namespace name as pod-labels.

-- user6317694
kubernetes
kubernetes-ingress

1 Answer

10/27/2018

Yes, this is possible, but not immediately intuitive. If you look at the section below the chunk you linked, it gives a pretty good explanation (this appears to have been added after you asked your question). The NetworkPolicy API documentation here is generally helpful as well.

Basically, if you put each selector as two separate items in the list like the example does, it is using a logical OR. If you put them as two items in the same array element in the list (no dash in front of the second item) like the example below to AND the podSelector and namespaceSelector, it will work. It may help to see these in a yaml to json converter.

Here's an ingress chunk from their policy, modified to AND the conditions

      ingress:
      - from:
        - namespaceSelector:
            matchLabels:
              project: myproject
          podSelector:
            matchLabels:
              role: frontend

This same sort of logic applies to using the ports rule if you use that alongside of the to or from statements. You'll notice in the example that they do not have a dash in front of ports under the ingress rule. If they had put a dash in front, it would OR the conditions of ingress and ports.

Here are some GitHub links from when they were discussing how to implement combining selectors:

  1. This comment may give a little more background. The API already supported the OR, so doing it otherwise would've broken some functionality for people with that implemented: https://github.com/kubernetes/kubernetes/issues/50451#issuecomment-336305625
  2. https://github.com/kubernetes/kubernetes/pull/60452
-- arg0nik_
Source: StackOverflow