9 DB_PATH = "<%= node[:geoipupdate][:directory] %>/GeoLite2-Country.mmdb"
11 # Default region when continent doesn't match any in the dictionary
12 DEFAULT_REGION = "eu-central-1"
14 # Mapping of continents to AWS regions
15 CONTINENT_TO_AWS_REGION = {
16 "NA": "us-west-2", # North America
17 "OC": "us-west-2", # Oceania
18 "SA": "us-west-2", # South America
21 # Global to store last known modification time and database reader
25 def is_valid_ip(ip_str):
26 """Check if a string is a valid IPv4 or IPv6 address."""
28 ipaddress.ip_address(ip_str)
34 """Get the geoip2 database reader. Reload if the DB file has changed."""
38 if not os.path.exists(DB_PATH):
39 return None # Database file missing
41 current_mod_time = os.path.getmtime(DB_PATH)
43 # If file has changed or reader isn't initialized, reload it
44 if reader is None or current_mod_time != last_mod_time:
46 reader.close() # Close the existing reader before reinitializing
47 reader = geoip2.database.Reader(DB_PATH)
48 last_mod_time = current_mod_time
52 def get_continent_from_ip(ip_address):
53 """Return the continent for a given IP address."""
54 if not is_valid_ip(ip_address):
58 return None # No continent as DB is missing
60 response = reader.country(ip_address)
61 return response.continent.code
63 return None # Indicates invalid IP address or other issues
65 def determine_aws_region(continent_code):
66 """Determine AWS region based on the continent code using a dictionary."""
67 return CONTINENT_TO_AWS_REGION.get(continent_code, DEFAULT_REGION)
70 """Main function to process IP addresses from stdin and return AWS regions."""
71 for line in sys.stdin:
72 ip_address = line.strip()
74 continent_code = get_continent_from_ip(ip_address)
75 aws_region = determine_aws_region(continent_code)
77 sys.stdout.write(f"{aws_region}\n")
80 if __name__ == "__main__":