How to add blocking IP rules on each nginx-ingress host

2/12/2020

I have searched a lot and I didn't find the solution. I want to block/allow ip's into each host definition in the nginx-ingress, not per locations.

This is the ingress.yaml:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: ingress-nginx
  annotations:
    kubernetes.io/ingress.class: "nginx"
spec:
  rules:
  - host: test1.test.com
    #Blocking rules here, only affecting test1.test.com domain
    http:
      paths:
      - path: /
        backend:
          serviceName: wordpressA
          servicePort: 80
  - host: test2.test.com
    #Blocking rules here, only affecting test2.test.com domain
    http:
      paths:
      - path: /
        backend:
          serviceName: wordpressB
          servicePort: 80 

Many thanks for your time

-- Arnau Coll
kubernetes-ingress
nginx
nginx-ingress

1 Answer

2/12/2020

You need to split those host definitions into separate ingress rules.

Then you can use annotation to whitelist source range using following annotation : nginx.ingress.kubernetes.io/whitelist-source-range

Something like this:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: app1-ingress
  annotations:
    kubernetes.io/ingress.class: "nginx"
    nginx.ingress.kubernetes.io/whitelist-source-range: "10.0.0.0/24"
spec:
  rules:
  - host: app1.com
    http:
      paths:
      - path: /
        backend:
          serviceName: app1-service
          servicePort: http
---
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: app2-ingress
  annotations:
    kubernetes.io/ingress.class: "nginx"
    nginx.ingress.kubernetes.io/whitelist-source-range: "10.0.0.0/24"
spec:
  rules:
  - host: app2.com
    http:
      paths:
      - path: /
        backend:
          serviceName: app2-service
          servicePort: http

You can also use server snipper and add nginx config to the yaml.

Something like this:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    nginx.ingress.kubernetes.io/server-snippet:
location / {
  # block one workstation
  deny    192.168.1.1;
  # allow anyone in 192.168.1.0/24
  allow   192.168.1.0/24;
  # drop rest of the world 
  deny    all;
}
-- Crou
Source: StackOverflow