Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically add EC2 ip addresses to Django ALLOWED_HOSTS

We've recently changed our deployment strategy to use AWS auto scaling group.

One problem we have in production is with the newly created EC2s.
Our Application starts to return:

Invalid HTTP_HOST header: 
    <ip_address>. You may need to add <ip_address> to ALLOWED_HOSTS`

because these EC2s are not in the original Django ALLOWED_HOSTS.

It doesn't make sense for each newly created EC2 to have to redeploy; that contradicts the sense of "auto scale".
Also, we don't want to use wildcards or IP range for security reasons.

What can we do?

like image 520
trailing-slash Avatar asked Nov 14 '17 04:11

trailing-slash


People also ask

Can EC2 instance have multiple IP addresses?

You can use the Instances screen Amazon EC2 console to assign multiple IPv6 addresses to an existing instance. This assigns the IPv6 addresses to the primary network interface (eth0) for the instance.


1 Answers

You can retrieve an EC2 instance Meta data by making an API request to

curl http://169.254.169.254/latest/meta-data/
GET http://169.254.169.254/latest/meta-data/

source

And you can get just the private IP for a specific instance by making an API call:

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

So in your Django settings file add this script to "dynamically" add IPs to your allowed hosts:

import requests
EC2_PRIVATE_IP = None
try:
    EC2_PRIVATE_IP = requests.get(
        'http://169.254.169.254/latest/meta-data/local-ipv4',
        timeout=0.01).text
except requests.exceptions.RequestException:
    pass

if EC2_PRIVATE_IP:
    ALLOWED_HOSTS.append(EC2_PRIVATE_IP)
like image 171
PatDuJour Avatar answered Oct 14 '22 19:10

PatDuJour