如何将EC2 IP地址动态添加到Django ALLOWED_HOSTS [英] How to dynamically add EC2 ip addresses to Django ALLOWED_HOSTS

查看:135
本文介绍了如何将EC2 IP地址动态添加到Django ALLOWED_HOSTS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们最近更改了部署策略,以使用AWS自动扩展组。

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

我们在生产中遇到的一个问题是新创建的EC2。

我们的应用程序开始返回:

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`

,因为这些EC2不在原始Django ALLOWED_HOSTS

because these EC2s are not in the original Django ALLOWED_HOSTS.

每个新创建的EC2都不必重新部署;这与自动缩放的感觉相矛盾。

另外,出于安全原因,我们不想使用通配符或IP范围。

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.

我们能做什么?

推荐答案

您可以通过向以下API发出API请求来获取EC2实例元数据

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/

您可以通过调用API来获取特定实例的专用IP:

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

因此,在您的Django设置文件中,将此脚本添加为动态将IP添加到允许的主机中:

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)

这篇关于如何将EC2 IP地址动态添加到Django ALLOWED_HOSTS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆