首页 > 解决方案 > 如何找到最近的 AWS 区域来部署云应用程序

问题描述

我有一个需要部署在云上的应用程序,但我不确定我最近的 AWS 区域,如何根据我的计算机位置找到我最近的 AWS 区域来进行部署。

在此先感谢 Umesh

标签: pythonamazon-web-servicesterraform

解决方案


Here's how to do it:

  • You need to know the cities/states those regions are in.
  • Get an estimation of their coordinates (longitude/latitude).
  • Calculate the distance between you and all of them
  • Choose the closest region.
aws_regions = {
    "Virginia,US": ("us-east-1", (38.0339, -78.4860)),
    "Ohio,US": ("us-east-2", (40.4167, -82.9167)),
    "California,US": ("us-west-1", (37.7749, -122.4194)),
    "Oregon,US": ("us-west-2", (45.5200, -122.6819)),
    "Canada,CA": ("ca-central-1", (43.6532, -79.3832)),
    "Mumbai,IN": ("ap-south-1", (19.0760, 72.8777)),
    "Seoul,KR": ("ap-northeast-2", (37.5665, 126.9780)),
    "Singapore,SG": ("ap-southeast-1", (1.3521, 103.8198)),
    "Sydney,AU": ("ap-southeast-2", (-33.8688, 151.2093)),
    "Tokyo,JP": ("ap-northeast-1", (35.6895, 139.6917)),
    "Frankfurt,DE": ("eu-central-1", (50.1147, 8.6821)),
    "Ireland,IE": ("eu-west-1", (53.4129, -8.2439)),
    "London,UK": ("eu-west-2", (51.5074, -0.1278)),
    "Paris,FR": ("eu-west-3", (48.8566, 2.3522)),
    "Sao Paulo,BR": ("sa-east-1", (-23.5505, -46.6333)),
}


def get_my_long_lat(ip):
    import requests
    import json

    url = "http://ip-api.com/json/" + ip
    r = requests.get(url)
    data = json.loads(r.text)
    return data["lat"], data["lon"]


def distance_between_two_long_lats(long1, lat1, long2, lat2):
    import math

    R = 6373.0
    dlon = math.radians(long2 - long1)
    dlat = math.radians(lat2 - lat1)
    a = (math.sin(dlat / 2) ** 2) + math.cos(math.radians(lat1)) * math.cos(
        math.radians(lat2)
    ) * (math.sin(dlon / 2) ** 2)
    c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
    return R * c


def get_closest_state_long_lat(ip):
    my_long, my_lat = get_my_long_lat(ip)
    min_distance = 10000000000
    closest_state = ""
    for state in aws_regions:
        state_long, state_lat = aws_regions[state][1]
        distance = distance_between_two_long_lats(
            my_long, my_lat, state_long, state_lat
        )
        if distance < min_distance:
            min_distance = distance
            closest_state = state
    return closest_state


def get_my_ip():
    import requests
    import json

    url = "https://api.ipify.org/?format=json"
    r = requests.get(url)
    data = json.loads(r.text)
    return data["ip"]


if __name__ == "__main__":
    ip = get_my_ip()
    closest_state = get_closest_state_long_lat(ip)
    print(aws_regions[closest_state][0])

Note: you can adjust the values to different long lats based on the precision you want. Regions have availability zones, which means that those values might not be accurate all the time. Availability zones can be in different states than the main advertised ones.


推荐阅读