How can I achieve that when obviously you can not use spec.namespaceSelector
in the netpol?
kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
name: allow-from-ns-netpol
namespace: special-ns
spec:
namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: app
ingress:
- from:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: cka-exam
So, this doesn't work.
CodePudding user response:
The API resource definition you've provided does not appear to be schema compliant. The NetworkPolicySpec in Kubernetes v1.26 shows that the following fields are allowed: [policyTypes, podSelector, egress, ingress]
.
I recommend taking a look at the Network Policy documentation.
When you define a Network Policy, you assign it to a Namespace. You can then narrow that Network Policy to only apply to select Pods (in that Namespace) using the .spec.podSelector
property. As the documentation states, "An empty podSelector
selects all pods in the namespace."
This means if you want block all ingress traffic to the Pods in Namespace special-ns
, you would assign the Network Policy to the special-ns
Namespace and leave the .spec.podSelector
property empty so it selects all of the Pods in special-ns
. Without any ingress
rules defined, the resource would be the Default deny all ingress traffic definition.
You then use the ingress
property to define the restrictions, or rules, on where that incoming traffic can come from. It looks like your existing definition is correct, so ingress traffic will only be allowed from Pods that exist in the Namespace cka-exam
.
kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
name: allow-from-ns-netpol
namespace: special-ns
spec:
ingress:
- from:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: cka-exam