1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

LambdaでAmazonのIPを取得してSGアウトバウンドに投入する

Last updated at Posted at 2021-07-12

前提

IPの取得とSGの書き換え

  url = 'https://ip-ranges.amazonaws.com/ip-ranges.json'
  req = urllib.request.Request(url)
  with urllib.request.urlopen(req) as res:
    ipranges = json.load(res)
  prefixes = ipranges['prefixes']
  ips = []
  for ip in prefixes:
        if ip["region"] == "取得したいリージョン" and ip["service"] == "取得したいサービス名":
            ips.append(ip["ip_prefix"])
  for add_ip in ips:
        DESC = '自由記載'
        security_group = ec2.SecurityGroup(変更したいSGのID)
        security_group.authorize_egress(
            DryRun=False,
            IpPermissions=[
                {
                    'IpProtocol': 'tcp',
                    'FromPort': 443,
                    'ToPort': 443,
                    'IpRanges': [
                      {
                      'CidrIp': add_ip,
                        'Description': DESC
                      },
                    ]
                }
            ]
        )

その他

  • 上記に加え、既存IPの削除処理と下記IPアドレス範囲の変更通知を組み合わせればIP変更毎に自動的にSG書き換えも可能
    AWS IP アドレスの範囲 - AWS 全般のリファレンス

  • 一度に結構な数のIPを投入するので、場合によってはセキュリティグループルール数の上限緩和が必要

以上

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?