Using a ConfigMap to specify list of whitelisted CIDR blocks

9/25/2018

What I want to do

I'd like to apply an IP whitelist defined in a ConfigMap. I'd like to keep the list external because it's easier to have it in one file rather than putting the blocks inline. The whitelist will be used by many services in different namespaces.

What I Have

A lot has been removed from the following spec files but hopefully enough has been retained.

I define the whitelist in a ConfigMap as:

apiVersion: v1
kind: ConfigMap
data:
  whitelist:
    # example
    - 127.0.0.1/32
    # etc.
metadata:
  name: whitelist

My Service, for this example, is:

apiVersion: v1
kind: Service
metadata:
  name: example
  labels:
    label: example

Note that the Service type is the default, as I rely on the Ingress to expose it. This cannot change.

The service sits behind an Ingress definition:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: example
  rules:
  - host: example.com
#... ports, etc

What I've Tried

Changing Service type

Defining the service as type: LoadBalancer. This does exactly what I want as it's easy to consume the ConfigMap, then I realized I cannot change the service type for business reasons.

Using Ingress Annotations

apiVersion: extensions/v1beta1
kind: Ingress
# ...
metadata:
  name: whitelist
  annotations:
    nginx.ingress.kubernetes.io/whitelist-source-range: "blockA", "blockB"

This kinda works but I couldn't figure out how to use the ConfigMap instead of the comma-separated list. I should note here that any solution that lets me use an externally-defined list is acceptable, and it doesn't have to be a ConfigMap just because.

Using a NetworkPolicy

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: example-network-policy
spec:
  policyTypes:
  - Ingress
  ingress:
  - from:
    - ipBlock:
      cidr: # hmm... can I add the ConfigMap here?
    - namespaceSelector:
      # ...etc

So far this looks the most promising, but the ipBlock selector seems to only accept one block...?

-- rath
kubernetes
kubernetes-ingress
kubernetes-networkpolicy
whitelist

1 Answer

9/25/2018

Using Ingress Annotations

ConfigMaps are not supported in annotations.

Using a NetworkPolicy

ingress and egress are array structures so you can try this, not sure if it works for you:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: example-network-policy
spec:
  policyTypes:
  - Ingress
  ingress:
  - from:
    - ipBlock:
      cidr: <cidr1>
    - namespaceSelector:
      # ...etc
  - from:
    - ipBlock:
      cidr: <cidr2>
    - namespaceSelector:
      # ...etc
  - from:
    - ipBlock:
      cidr: <cidr3>
    - namespaceSelector:
      # ...etc
-- Rico
Source: StackOverflow