Setting service name dynamically based on path in Kubernetes Ingress

9/30/2021

In a Kubernetes ingress, I'd like to dynamically change the service name to a match on a certain part of the path in an ingress. Something like this:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: example
spec:
  rules:
  - host: example.com
    http:
      paths:
      - path: /api/(^/+)/(.*)
        backend:
          serviceName: api-(&1)
          servicePort: 80

Where &1 in the example above would resolve to the first regular expression match in the string /api/(^/+)/(.*)

So basically if a path is something like this /api/asset/fetch/anything-at-all, then it would direct the call to a service named api-asset

I know that this can potentially lead to some security issues, but if I force the prefix 'api-' to the service name then only services with the prefix 'api-' would technically be exposed to the internet. And all other services would still be protected inside the Kubernetes cluster. I can even change the prefix to be 'public-' for simplicity's sake.

Is this something that is possible? And what is the correct syntax to set it up?

-- Steven
kubernetes
kubernetes-ingress
kubernetes-service

0 Answers