背景
Google Cloud FunctionsでIP制限を行いたい。
VPCSCやCloud Load Balancer経由のアクセスにすることによってIP制限を行う方法があるが、少し面倒。
今回はシンプルにpythonコードでIP制御をすることにした。
実装
Google Cloud FuntionsのPythonはFlaskで実装されている。
Flaskのリクエスト元アドレスは request.remote_addr
で取得できる。
import ipaddress
def ip_allowed(ip):
ip = ipaddress.ip_address(ip)
nw = ipaddress.ip_network(ip_range)
return (ip in nw)
def main(request):
if not ip_allowed(request.remote_addr):
raise Exception(f"IP not allowed: {request.remote_addr}")
return 'IP allowed.'