Context
I have a Google Kubernetes Engine (GKE) cluster with Workload Identity enabled. As part of Workload Identity, a k8s-metadata-proxy DaemonSet runs on the cluster. I have a namespace my-namespace
and want to deny all egress traffic of pods in the namespace except egress to the k8s-metadata-proxy DaemonSet. As such I have the following NetworkPolicy:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: test-network-policy
namespace: my-namespace
spec:
# Apply to all pods.
podSelector: {}
policyTypes:
- Egress
egress:
- ports:
# This is needed to whitelist k8s-metadata-proxy. See https://github.com/GoogleCloudPlatform/k8s-metadata-proxy
- protocol: TCP
port: 988
Problem
The NetworkPolicy is too broad because it allows egress TCP traffic to any host on port 988 instead of just egress to the k8s-metadata-proxy DaemonSet, but I can't seem to find a way to specify the .spec.egress[0].to
to achieve the granularity I want.
I have tried the following to
s:
egress:
- to:
- namespaceSelector:
matchLabels:
namespace: kube-system
ports:
- protocol: TCP
port: 988
- to:
- ipBlock:
cidr: <cidr of pod IP range>
- ipBlock:
cidr: <cidr of services IP range>
ports:
- protocol: TCP
port: 988
but these rules result in traffic to the k8s-metadata-proxy being blocked.
Question
How can I select the k8s-metadata-proxy DaemonSet in the to
part of an egress rule in a networking.k8s.io/v1/NetworkPolicy
?
As I said in the comment:
This comment could be misleading as the communication with
gke-metadata-server
is described in the official documentation:Focusing on the part of above documentation:
The rule to allow traffic only to
GKE Metadata server
is described in the last paragraph of above citation. TheYAML
definition should look like below:Assuming that:
Network Policy
enabledWorkload Identity
enabledPods
are trying to communicate fromrestricted-namespace
namespaceThe output for describing needed
NetworkPolicy
:$ kubectl describe networkpolicy -n restricted-namespace egress-rule
You can create and
exec
into the pod with a labelapp=nginx
by:Example of communicating with
GKE Metadata Server
:$ curl 169.254.169.254/computeMetadata/v1/instance/ -H 'Metadata-Flavor: Google'
Additional resources:
To allow specific pods to send traffic only to the specific pods on specific ports you can use following policy: