Search code examples
djangoamazon-web-servicesamazon-ecs

DjangoDisallowedHost in AWS ECS


I'm trying to deploy a sample Django application into AWS ECS using AWS Fargate. I don't have a URL yet but I read that you can append your container's public ip to the Django's ALLOWED_HOSTS setting configuration. So I changed my configuration to add it using this link as a guide

ALLOWED_HOSTS = ['localhost', '127.0.0.1', '.example.com']

PUBLIC_IP = None

try:
    response = requests.get('http://169.254.169.254/latest/meta-data/public-ipv4', timeout=3)
    print('Response')
    PUBLIC_IP = response.text
    ALLOWED_HOSTS += [PUBLIC_IP]
except requests.exceptions.RequestException as e:
    print('Exception on getting public ip ', e)

print(ALLOWED_HOSTS)

Unfortunately it doesn't work for me, probably because I'm not using an ec2 instance. Can somebody show me how to add my public ip?

I'm using daphne, with the following command

daphne -b 0.0.0.0 -p 80 my_project.asgi:application

I don't even get these print statements between my logs, in ecs task. But I get the daphne logs


Solution

  • For AWS Fargate, the correct metadata endpoint is http://169.254.170.2/v2/metadata.

    Reference - Task metadata endpoint version 4 – Available for tasks that use the Fargate launch type on platform version v1.1.0 or later and tasks that use the EC2 launch type that also use the awsvpc network mode and are launched on Amazon EC2 infrastructure running at least version 1.17.0 of the Amazon ECS container agent. https://docs.aws.amazon.com/AmazonECS/latest/userguide/task-metadata-endpoint-v4-fargate.html

    However, this endpoint only returns privateIp part of task but not the publicIp. Since you are using python you can use boto3 module to get publicIp by querying with privateIp from above metadata result.

    Here is sample python code I just tested with my own privateIp of the task.

    import boto3
    client = boto3.client('ec2')
    response = client.describe_network_interfaces(
        Filters=[
            {
                'Name': 'addresses.private-ip-address',
                'Values': [
                    '172.31.6.195',
                ]
            },
        ]
    )
    response ['NetworkInterfaces'][0]['Association']['PublicIp']
    //100.x.x.x