Zaco
Zaco

Reputation: 5

How does KrakenD CE redirect requests to different backend hosts based on different request IPs?

Assuming there are two source IPs, namely 192.168.1.1 and 192.168.2.2, both simultaneously sending requests to the same KrakenD service and JSON file (as shown below), how can one redirect to different backend hosts based on different source IPs when the URL of the "endpoint" is the same?

{
  "version": 3,
  "endpoints": [
    {
      "endpoint": "/api",
      "method": "POST",
      "backend": [
        {
          "host": "{{ if eq .Request.RemoteAddr \"192.168.1.1\" }}backend1{{ else }}backend2{{ end }}",
          "url_pattern": "/api",
          "encoding": "json",
          "timeout": "3000ms"
        }
      ]
    }
  ]
}

Thanks

Upvotes: 0

Views: 241

Answers (1)

Albert Garcia
Albert Garcia

Reputation: 187

While you cannot use templating expressions like that directly inside the host field, you could use Lua to dynamically change the hostname in a similar way that is described in this article: https://www.krakend.io/blog/canary-releases/

The idea is to have something like this in your endpoint configuration:

    {
      "endpoint": "/test",
      "backend": [
        {
          "host": ["http://main_host:8080"],
          "url_pattern": "/url-pattern/",
          "allow": ["req_uri"],
          "extra_config": {
            "modifier/lua-backend": {
              "sources": ["alternativeBackend.lua"],
              "pre": "loadAlternative(request.load(), 'http://alternative_host:8080/url-pattern/')",
              "allow_open_libs": true
            }
          }
        }
      ]
    }

and the following script in your alternativeBackend.lua script:

function loadAlternative( req, alternative_url )
  if [YOUR CONDITION HERE]
  then
    req:url(alternative_url)
  end
end

Instead of choosing it randomly, like in this example, you could implement your own custom logic based on the client IP.

Hope it helps.

Upvotes: 0

Related Questions