How to dynamically add EC2 ip addresses to Django ALLOWED_HOSTS

前端 未结 2 466
野趣味
野趣味 2021-02-05 14:59

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 sta

相关标签:
2条回答
  • 2021-02-05 15:37

    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/
    

    source

    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 = 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)
    
    0 讨论(0)
  • 2021-02-05 15:46

    The snippets below will find either the Public IP address or the Elastic IP address associated with your EC2 instance and append it to ALLOWED_HOSTS.

    • Install PyCurl

      pip install pycurl
      
    • Python 3

      import pycurl
      from io import BytesIO
      
      # Determine Public IP address of EC2 instance
      buffer = BytesIO()
      c = pycurl.Curl()
      c.setopt(c.URL, 'checkip.amazonaws.com')
      c.setopt(c.WRITEDATA, buffer)
      c.perform()
      c.close()
      # Body is a byte string, encoded. Decode it first.
      ALLOWED_HOSTS.append(buffer.getvalue().decode('iso-8859-1').strip())
      
    • Python 2

      import pycurl
      from StringIO import StringIO
      
      buffer = StringIO()
      c = pycurl.Curl()
      c.setopt(c.URL, 'checkip.amazonaws.com')
      c.setopt(c.WRITEDATA, buffer)
      c.perform()
      c.close()
      # In Python 2, we can cast the return value to
      # string without knowing the exact encoding.
      ALLOWED_HOSTS.append(str(buffer.getvalue()).strip())
      
    0 讨论(0)
提交回复
热议问题