5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Lambda functions URL】IP制限をかける方法(Python)

Last updated at Posted at 2022-11-30

はじめに

Lambda functions URL を使っていて IP 制限をかけたいと思って IAM ポリシーで色々試してみたもののできませんでした。

無理くり Lambda 内で実装したので、その方法を共有したいと思います。

環境変数

環境変数にIP_RANGE='['111.111.111.111', '222.222.222.222']'を設定する。

ソースコード

import json
import os
import ast

# IPアドレスチェック
def check_ip(IP_ADDRESS, IP_RANGE):
    valid_ip = False
    if not valid_ip and IP_ADDRESS in IP_RANGE:
        valid_ip = True

    return valid_ip


def lambda_handler(event, context):
    IP_ADDRESS = event["requestContext"]["http"]["sourceIp"]
    IP_RANGE = ast.literal_eval(os.environ.get("IP_RANGE", "[]"))

    valid_ip = check_ip(IP_ADDRESS, IP_RANGE)

    if not valid_ip:
        return {
            'statusCode': 500,
            'body': json.dumps('500 Unauthorized')
        }

    return {
        'statusCode': 200,
        'body': json.dumps('200 Success!')
    }

あとがき

参考までに、、API Gateway では 以下の記事のように IAM ポリシー で IP 制限をかけることができます。

参考


会社紹介

株式会社 Mosaica
最先端テクノロジーで社会課題を解決し、持続可能な未来を創造する IT カンパニー。
AI ソリューション、クラウド統合、DX 推進、経営コンサルティングなど包括的なサービスでビジネス変革を支援しています。

詳しくは 公式サイト までお気軽にご相談ください。
公式サイト: https://mosaica.co.jp/

5
5
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
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?