Verifying Django and Elastic Beanstalk URLs

I have a Django webapp. It works inside Docker on an elastic beanstalk.

I would like to specify a health check URL for a more advanced health check than "can the ELB establish a TCP connection."

Quite sensibly, ELB does this by connecting to the instance via HTTP, using the instance host name (e.g. ec2-127-0-0-1.compute-1.amazonaws.com) as the header Host.

Django has ALLOWED_HOSTSthat checks the header of Hostincoming requests. I set this for an external application application through an environment variable.

Unsurprisingly and perfectly reasonable, therefore, Django rejects ELB URL health checks for lack of compliance Host.

We do not want to disconnect ALLOWED_HOSTS, because we would like to trust get_host().

The solutions so far look like this:

  • Somehow convincing Django not to worry about ALLOWED_HOSTSfor certain specific paths (i.e. the health check URL)
  • Do something funky like calling the EC2 API at startup to get the fully qualified domain name of the host and add it to ALLOWED_HOSTS

None of them seem particularly pleasant. Can anyone recommend a better / existing solution?

( , , " ALLOWED_HOSTS, HTTPD, " - , Django, HTTPD)/p >

+4
2

ELB , beanstalk (*.elasticbeanstalk.com EC2 *.amazonaws.com), ALLOWED_HOSTS '.amazonaws.com' '.elasticbeanstalk.com'.

ipv4- , . , , , , , .

Apache Django. , , . beanstalk Apache, .ebextensions, . .ebextensions .config.

files:
  "/etc/httpd/conf.d/eb_healthcheck.conf":
    mode: "000644"
    owner: root
    group: root
    content: |
        <If "req('User-Agent') == 'ELB-HealthChecker/1.0' && %{REQUEST_URI} == '/status/'">
            RequestHeader set Host "example.com"
        </If>

/status/ URL example.com . Apache, , URL .

Apache, . Django CommonMiddleware, HttpRequest get_host(), . -

from django.middleware.common import CommonMiddleware


class CommonOverrideMiddleware(CommonMiddleware):
    def process_request(self, request):
        if not('HTTP_USER_AGENT' in request.META and request.META['HTTP_USER_AGENT'] == 'ELB-HealthChecker/1.0' and request.get_full_path() == '/status/'):
            return super().process_request(request)

. django.middleware.common.CommonMiddleware path.CommonOverrideMiddleware settings.py.

Apache, - Django .

+6

, , :

import socket
local_ip = str(socket.gethostbyname(socket.gethostname()))
ALLOWED_HOSTS=[local_ip, '.mydomain.com', 'mydomain.elasticbeanstalk.com' ]

mydomain mydomain.elasticbeanstalk.com .

+3

All Articles