When configuring networks and loadbalancers, sometimes you need the network CIDR block used by Services of a Kubernetes cluster. There are various ways to pull this information from different Kubernetes implementations, but one trick that works across implementations is looking at the error message from kubectl if you attempt to create a service at an invalid IP address.
Steven Dake provided this solution on stackoverflow,
# apply Service with invalid IP, then parse error message for services CIDR block echo '{"apiVersion":"v1","kind":"Service","metadata":{"name":"foo"},"spec":{"clusterIP":"1.1.1.1","ports":[{"port":443}]}}' | kubectl apply -f - 2>&1 | sed 's/.*valid IPs is //'
Pod CIDR block
Unfortunately, there is not an equivalent for pulling the pod CIDR block used by a cluster. The command below will show you the pod range on each individual worker node, but does not provide the global mask.
kubectl get nodes -o jsonpath='{.items[*].spec.podCIDR}'
GKE Clusters
On GCP clusters or GKE Anthos on-prem clusters, you can pull it out of the kube-proxy Daemonset.
kubectl get ds kube-proxy -n kube-system -o=jsonpath="{.spec.template.spec.containers[0].command}" | grep -Po '\-\-cluster\-cidr=[^ ]*' | cut -d'=' -f2 | tr -d '"]'
Or out of the cluster-info dump.
kubectl cluster-info dump | grep -m 1 cluster-cidr | grep -Po '\-\-cluster\-cidr=[^ ]*' | cut -d'=' -f2 | tr -d '"'
Kubernetes Clusters running Flannel
On clusters that run flannel such as k3s or kubeadm, you can ssh into a node and view the subnet configuration.
grep FLANNEL_NETWORK /run/flannel/subnet.env
RESOURCES
github issues, pod CIDR for cluster
stackexchange.com, pod CIDR block for kubeadm and calico
NOTES
another way to get services CIDR block on kubeadm clusters
kubeadm config view | grep servicesSubnet