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: I
Solution 1:
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/
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 = Nonetry:
EC2_PRIVATE_IP = requests.get(
'http://169.254.169.254/latest/meta-data/local-ipv4',
timeout=0.01).text
except requests.exceptions.RequestException:
passif EC2_PRIVATE_IP:
ALLOWED_HOSTS.append(EC2_PRIVATE_IP)
Post a Comment for "How To Dynamically Add Ec2 Ip Addresses To Django Allowed_hosts"