DockerイメージをLambda関数のデプロイパッケージとして使用する

# 手順

## Dockerfileの作成

```Dockerfile:Dockerfile
# 使用するベースイメージを指定
FROM public.ecr.aws/lambda/python:3.12

# 必要なパッケージをインストール
COPY requirements.txt ./
RUN pip install -r requirements.txt

# Lambda関数のコードをコピー
COPY app.py ./

# Lambda関数のハンドラを指定
CMD ["app.lambda_handler"]
```

## Lambda関数のコードを作成

```app.py
def lambda_handler(event, context):
    return {
        'statusCode': 200,
        'body': 'Hello from Docker Lambda!'
    }
```

## 必要なパッケージを記載したrequirements.txtの作成

```requirements.txt
# 例：requestsパッケージが必要な場合
requests
```

## Dockerイメージのビルド

```
docker build -t my-lambda-function --platform linux/x86_64 .
```

## Dockerイメージのテスト（オプション）

```
docker run -p 9000:8080 my-lambda-function
```

```
curl -XPOST "http://localhost:9000/2015-03-31/functions/function/invocations" -d '{}'
```

## ECRリポジトリの作成

```
aws ecr create-repository --repository-name my-lambda-function
```

## Dockerイメージのプッシュ

```
aws ecr get-login-password --region ap-northeast-1 | docker login --username AWS --password-stdin 123456789012.dkr.ecr.ap-northeast-1.amazonaws.com

docker tag my-lambda-function:latest 123456789012.dkr.ecr.ap-northeast-1.amazonaws.com/my-lambda-function:latest

docker push 123456789012.dkr.ecr.ap-northeast-1.amazonaws.com/my-lambda-function:latest
```

## IAMロールの作成

```trust-policy.json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "lambda.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
```

```
aws iam create-role --role-name lambda-execution-role --assume-role-policy-document file://trust-policy.json
```

```
aws iam attach-role-policy --role-name lambda-execution-role --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
```

## Lambda関数の作成または更新

```
aws lambda create-function \
  --function-name my-docker-lambda \
  --package-type Image \
  --code ImageUri=123456789012.dkr.ecr.ap-northeast-1.amazonaws.com/my-lambda-function:latest \
  --role arn:aws:iam::123456789012:role/lambda-execution-role \
  --region ap-northeast-1
```

# 動作確認1

```
aws lambda invoke \
  --function-name my-docker-lambda \
  response.json
{
    "StatusCode": 200,
    "ExecutedVersion": "$LATEST"
}
```

# 変更

## requestsライブラリを利用したappに変更

```app.py
import requests

def lambda_handler(event, context):
    url = "https://httpbin.org/get"  
    try:
        response = requests.get(url)
        response.raise_for_status()  
        data = response.json()  

        return {
            'statusCode': 200,
            'body': data
        }

    except requests.exceptions.RequestException as e:
        return {
            'statusCode': 500,
            'body': str(e)
        }
```

## Dockerイメージのビルド

```
docker build -t my-lambda-function --platform linux/x86_64 .
```

## Dockerイメージのプッシュ

```
aws ecr get-login-password --region ap-northeast-1 | docker login --username AWS --password-stdin 123456789012.dkr.ecr.ap-northeast-1.amazonaws.com

docker tag my-lambda-function:latest 123456789012.dkr.ecr.ap-northeast-1.amazonaws.com/my-lambda-function:latest

docker push 123456789012.dkr.ecr.ap-northeast-1.amazonaws.com/my-lambda-function:latest
```

## Lambda関数の更新

```
aws lambda update-function-code \
  --function-name my-docker-lambda \
  --image-uri 123456789012.dkr.ecr.ap-northeast-1.amazonaws.com/my-lambda-function:latest \
  --region ap-northeast-1
```

# 動作確認2

```
aws lambda invoke \
  --function-name my-docker-lambda \
  response.json
{
    "StatusCode": 200,
    "ExecutedVersion": "$LATEST"
}
```
```
cat response.json 
{"statusCode": 200, "body": {"args": {}, "headers": {"Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Host": "httpbin.org", "User-Agent": "python-requests/2.32.3", "X-Amzn-Trace-Id": "Root=1-6697ac09-XXX"}, "origin": "XX.XX.XX.XX", "url": "https://httpbin.org/get"}}% 
```