<p>So let's say I have 5 namespaces - prod, preprod, uat, dev, and test. Each namespace have a different label - ns=prod, ns=preprod, ns=uat, ns=dev, and ns=test.</p>

<p>Question:
So I want to create a network policy where, I don't want to send traffic (egress) from ns=test to a particular namespace whose label is ns=prod. But ns=test should able to do egress to all other namespace.</p>

<p>Documentation:
<a href="https://kubernetes.io/docs/concepts/services-networking/network-policies/" rel="nofollow noreferrer">https://kubernetes.io/docs/concepts/services-networking/network-policies/</a>
<a href="https://kubernetes.io/docs/tasks/administer-cluster/declare-network-policy/" rel="nofollow noreferrer">https://kubernetes.io/docs/tasks/administer-cluster/declare-network-policy/</a></p>

<p>I tried to create a manifest file from the above documentation but had no luck. I'm able to do this using podSelector (labels of pods, but not using only namespaces as a whole).</p>

<p>It would be easier if you could add the code snippet. However, it's not that tough to figure out what is going wrong.</p>

<p>I am thinking something like this might be the issue with your network policy. Your pods might be requiring world wide web connection, so you cannot stop comms from test to prod through <code>egress</code> rule as you might be adding <code>0.0.0.0/0</code> to let your pods on any env to communicate to outer world to download external libraries or whatever stuff associated with your application. </p>

<p>Due to this it is slightly difficult to add the <code>egress</code> rule to stop comms to any env. But on the contrary you can add <code>igress</code> rule to prod ns to not let communications from <code>test</code> or <code>dev</code>. Something like this might work, but again, we can change it based on needs.</p>

<pre><code>apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: prod-network-policy
  namespace: prod
spec:
  podSelector:
    matchLabels:
      ns: prod
  policyTypes:
  - Ingress
  - Egress
  ingress:
  - from:
    - namespaceSelector:
        matchLabels:
          ns: prod
          ns: dev
          ns: uat
    - podSelector:
        matchLabels:
          ns: prod
          ns: dev
          ns: uat
    - ipBlock:
        cidr: 10.0.1.101/32 #Assuming allow incoming request from ingress controller
  egress:
  - to: []
</code></pre>

<p>There are several ways one can achieve this. But, I also sometimes refers to these example recipes on <a href="https://github.com/ahmetb/kubernetes-network-policy-recipes" rel="nofollow noreferrer">Github</a>. </p>

<p><strong>Edit based on comment</strong>
Addition of other namespaces to ingress rule to allow traffic from other namespaces except test.</p>

<p>Hope this is helpful.</p>
