Django ALLOWED_HOSTS with ELB HealthCheck

I have a django app deployed on Elastic Beanstalk. HealthCheck is not working for my application because ELB HealthCheck IP is not included in my settings variable ALLOWED_HOSTS

.

How do I change ALLOWED_HOSTS

to pass HealthCheck? I would just pass in an explicit IP, but I believe this changes, so whenever the IP changes change, validation will fail until I add a new IP.

+3
django amazon-web-services amazon-ec2 amazon-elb amazon-elastic-beanstalk


source to share


2 answers


Your EC2 instance can request metadata about itself, including its IP address, which is available at http://169.254.169.254/latest/meta-data/local-ipv4 .

You can check this by ssh-in into your EC2 instance and running:

curl http://169.254.169.254/latest/meta-data/local-ipv4

      



So, in your configuration, you can do something like:

import requests

ALLOWED_HOSTS = ['.yourdomain.com', ]
try:
    EC2_IP = requests.get('http://169.254.169.254/latest/meta-data/local-ipv4').text
    ALLOWED_HOSTS.append(EC2_IP)
except requests.exceptions.RequestException:
    pass

      

Obviously you can replace requests

with urllib

if you don't need the dependency.

+5


source to share


The other solution doesn't answer the question because it doesn't account for all the various AWS tools (ELB, etc.). What we are done with (since we are using nginx

+ uwsgi

), we are setting the header to something valid when the user makes a request.

As described on this page:

https://opbeat.com/blog/posts/the-new-django-allowed_hosts-with-elb-uwsgi-and-nginx/

We'll post our config nginx

as shown below:



set $my_host $host;
if ($host ~ "\d+\.\d+\.\d+\.\d+") {
  set $my_host "example.com";
}

location / {
  uwsgi_pass unix:///tmp/mysite.com.sock;
  uwsgi_param HTTP_HOST $my_host;
  include uwsgi_params;
}

      

The key here is to put a valid value for $my_host

according to yours ALLOWED_HOSTS

.

Unfortunately, there is no β€œperfect” solution without increasing overhead. In some configurations, you will need to constantly add IPs to ALLOWED_HOSTS

, but this solution usually works with the smallest head.

0


source to share







All Articles
Loading...
X
Show
Funny
Dev
Pics