AWS IP アドレスの範囲


はじめに

セキュリティグループのInBound、OutBoundにてAWSのサービス(API Gateway、S3など)を許可するように設定したい場合は、AWS IP アドレスの範囲を見て設定可能です。

AWS IP アドレスの範囲

AWS の IP アドレス範囲の変更通知

AWS の IP アドレス範囲に変更がある際に、SNS通知設定をし、受信したら差分をメンテする。

設定方法:https://docs.aws.amazon.com/ja_jp/general/latest/gr/aws-ip-ranges.html#subscribe-notifications

PythonであるサービスのIPを取り出す例

import urllib.request
import json

def get_ip_groups_json(url):

    response = urllib.request.urlopen(url)
    ip_json = response.read()

    return ip_json

def get_ranges_for_service(ip_range_url, service, subset):

    ip_ranges_json = json.loads(get_ip_groups_json(ip_range_url))

    service_ranges = list()

    for prefix in ip_ranges_json['prefixes']:
        if prefix['service'] == service and subset == prefix['region']:
            service_ranges.append(prefix['ip_prefix'])

    return service_ranges


ip_ranges = get_ranges_for_service('https://ip-ranges.amazonaws.com/ip-ranges.json', 'S3', 'ap-southeast-1')

for ip in ip_ranges: print(str(ip))

結果:

Lambdaで自動更新

メンテ作業を自動化にしたい場合は、Lambdaでセキュリティグループを更新することも可能です。
サンプル:update-security-groups

参考Doc:AWS IP アドレスの範囲

以上