I set up the following in my settings.py to dynamically construct ALLOWED_HOSTS when the server comes up. you can just set the instance name based on elastic beanstalk environment. this felt pretty secure since only the correct iam permissions on the backend can access the private ip addresses of the ELB cluster.
```
def get_ec2_private_ip(instance_name):
command = f"""aws ec2 describe-instances --filters "Name=tag:Name,Values={instance_name}" --query "Reservations[*].Instances[*].PrivateIpAddress" --output json"""
result = subprocess.run(command, shell=True, capture_output=True, text=True)
return result.stdout
```
make sure to give the service the following permissions, of course limiting the resources to whatever names make sense.
```
{
"Sid": "VisualEditor2",
"Effect": "Allow",
"Action": "ec2:DescribeInstances",
"Resource": "*"
}
```
alternatively you can try this: <https://pypi.org/project/django-allow-cidr/> but it allows an entire range so it didn't feel as secure.
if this isn't secure for any reason would appreciate any feedback.
I set up the following in my settings.py to dynamically construct ALLOWED_HOSTS when the server comes up. you can just set the instance name based on elastic beanstalk environment. this felt pretty secure since only the correct iam permissions on the backend can access the private ip addresses of the ELB cluster.
```
def get_ec2_private_ip(instance_name):
command = f"""aws ec2 describe-instances --filters "Name=tag:Name,Values={instance_name}" --query "Reservations[*].Instances[*].PrivateIpAddress" --output json"""
result = subprocess.run(command, shell=True, capture_output=True, text=True)
return result.stdout
```
make sure to give the service the following permissions, of course limiting the resources to whatever names make sense.
```
{
"Sid": "VisualEditor2",
"Effect": "Allow",
"Action": "ec2:DescribeInstances",
"Resource": "*"
}
```
alternatively you can try this: <https://pypi.org/project/django-allow-cidr/> but it allows an entire range so it didn't feel as secure.
if this isn't secure for any reason would appreciate any feedback.