How to dynamically add EC2 ip addresses to Django ALLOWED_HOSTS

Viewed 4015

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?

2 Answers

Accepted answer was working fine with IMDSv1. In 2019 AWS launched IMDSv2 which requires session token authentication. Therefore, before requesting instance meta data we first need to fetch the token:

import requests

try:
    IMDSv2_TOKEN = requests.put('http://169.254.169.254/latest/api/token', headers={
        'X-aws-ec2-metadata-token-ttl-seconds': '3600'
    }).text
    EC2_PRIVATE_IP = requests.get('http://169.254.169.254/latest/meta-data/local-ipv4', timeout=0.01, headers={
        'X-aws-ec2-metadata-token': IMDSv2_TOKEN
    }).text
except requests.exceptions.RequestException:
    EC2_PRIVATE_IP = None


ALLOWED_HOSTS = [
    'my-app-test.eu-central-1.elasticbeanstalk.com'
]

if EC2_PRIVATE_IP:
    ALLOWED_HOSTS.append(EC2_PRIVATE_IP)

References:

https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/configuring-instance-metadata-service.html https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instancedata-data-retrieval.html

Related