

# Lambda を使用した Application Load Balancer リクエストの処理
<a name="services-alb"></a>

Lambda 関数を使用すると、Application Load Balancer のリクエストを処理することができます。Elastic Load Balancing は、Application Load Balancer のターゲットとして Lambda 関数をサポートしています。パス、またはその他のヘッダー値に基づき、ロードバランサールールを使用して、HTTP リクエストを関数にルーティングします。リクエストを処理して、Lambda 関数の HTTP レスポンスを返します。

Elastic Load Balancing は、リクエストボディおよびメタデータを含むイベントを使用して、Lambda 関数を同期的に呼び出します。

**Example Application Load Balancer リクエストイベント**  

```
{
    "requestContext": {
        "elb": {
            "targetGroupArn": "arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/lambda-279XGJDqGZ5rsrHC2Fjr/49e9d65c45c6791a"
        }
    },
    "httpMethod": "GET",
    "path": "/lambda",
    "queryStringParameters": {
        "query": "1234ABCD"
    },
    "headers": {
        "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
        "accept-encoding": "gzip",
        "accept-language": "en-US,en;q=0.9",
        "connection": "keep-alive",
        "host": "lambda-alb-123578498.us-east-1.elb.amazonaws.com",
        "upgrade-insecure-requests": "1",
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36",
        "x-amzn-trace-id": "Root=1-5c536348-3d683b8b04734faae651f476",
        "x-forwarded-for": "72.12.164.125",
        "x-forwarded-port": "80",
        "x-forwarded-proto": "http",
        "x-imforwards": "20"
    },
    "body": "",
    "isBase64Encoded": False
}
```

関数は、イベントを処理し、応答ドキュメントを JSON でロードバランサーに返します。Elastic Load Balancing は、このドキュメントを HTTP 成功またはエラーの応答に変換し、ユーザーに返します。

**Example レスポンスドキュメントの形式**  

```
{
    "statusCode": 200,
    "statusDescription": "200 OK",
    "isBase64Encoded": False,
    "headers": {
        "Content-Type": "text/html"
    },
    "body": "<h1>Hello from Lambda!</h1>"
}
```

Application Load Balancer を関数トリガーとして設定するには、まず、関数を実行するアクセス許可を Elastic Load Balancing に付与します。次に、リクエストを関数にルーティングするターゲットグループを作成し、リクエストをターゲットグループに送信するルールをロードバランサーに追加します。

`add-permission` コマンドを使用して、アクセス許可ステートメントを関数のリソースベースのポリシーに追加します。

```
aws lambda add-permission --function-name alb-function \
--statement-id load-balancer --action "lambda:InvokeFunction" \
--principal elasticloadbalancing.amazonaws.com
```

次のような出力が表示されます。

```
{
    "Statement": "{\"Sid\":\"load-balancer\",\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"elasticloadbalancing.amazonaws.com\"},\"Action\":\"lambda:InvokeFunction\",\"Resource\":\"arn:aws:lambda:us-west-2:123456789012:function:alb-function\"}"
}
```

Application Load Balancer のリスナーおよびターゲットグループの設定手順については、*Application Load Balancer ユーザーガイド*の[ターゲットとしての Lambda 関数](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/lambda-functions.html)を参照してください。

## Powertools for AWS Lambda のイベントハンドラー
<a name="services-alb-powertools"></a>

Powertools for AWS Lambda ツールキットのイベントハンドラーは、Application Load Balancer によって呼び出される Lambda 関数を記述する際に、ルーティング、ミドルウェア、CORS 設定、OpenAPI 仕様生成、リクエスト検証、エラー処理、その他の便利な機能を提供します。イベントハンドラーユーティリティは Python で使用可能です。詳細については、Powertools for AWS Lambda (Python) ドキュメントの「[イベントハンドラー REST API](https://docs.powertools.aws.dev/lambda/python/latest/core/event_handler/api_gateway/)」を参照してください。**

### Python
<a name="services-alb-powertools-python"></a>

```
import requests
from requests import Response

from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.event_handler import ALBResolver
from aws_lambda_powertools.logging import correlation_paths
from aws_lambda_powertools.utilities.typing import LambdaContext

tracer = Tracer()
logger = Logger()
app = ALBResolver()


@app.get("/todos")
@tracer.capture_method
def get_todos():
    todos: Response = requests.get("https://jsonplaceholder.typicode.com/todos")
    todos.raise_for_status()

    # for brevity, we'll limit to the first 10 only
    return {"todos": todos.json()[:10]}


# You can continue to use other utilities just as before
@logger.inject_lambda_context(correlation_id_path=correlation_paths.APPLICATION_LOAD_BALANCER)
@tracer.capture_lambda_handler
def lambda_handler(event: dict, context: LambdaContext) -> dict:
    return app.resolve(event, context)
```