AWS Lambda に Python のコードを追加して API Gateway 経由で呼び出してみる

AWS Lambda の Deploy から実行までの手順を記載。


## ロール作成

```role.json
{
    "Role": {
        "Path": "/",
        "RoleName": "lambda-role",
        "RoleId": "AROAXIZI44MCTVD3GM5TU",
        "Arn": "arn:aws:iam::XXXX:role/lambda-role",
        "CreateDate": "2023-04-10T18:50:45+00:00",
        "AssumeRolePolicyDocument": {
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Effect": "Allow",
                    "Principal": {
                        "Service": [
                            "lambda.amazonaws.com"
                        ]
                    },
                    "Action": "sts:AssumeRole"
                }
            ]
        }
    }
}
```

下記のコマンドを実行してロールを追加する。

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

## デプロイ準備
下記のシェルスクリプトを作成してデプロイしやすいようにする。

```deploy.sh
#!/bin/sh

if [ -z ${1} ]; then
        echo "sh deploy [function name}"
        exit
fi

AWS_ROLE=arn:aws:iam::XXXX:role/lambda-role
RUNTIME='python3.8'
HANDLER='lambda_function.lambda_handler'

if [ -e ${1} ]; then
        rm -f ${1}
fi

cd ${1}
zip -r ../${1}.zip .
cd ..

COUNT=$(aws lambda list-functions | grep FunctionName | grep ${1} | wc -l )

if [ ${COUNT} -eq 0 ]; then
        aws lambda create-function --role ${AWS_ROLE} --runtime ${RUNTIME} --function-name ${1} --handler ${HANDLER} --zip-file fileb://${1}.zip
else
        aws lambda update-function-code --function-name ${1} --zip-file fileb://${1}.zip
fi
```

## プログラム作成
下記のPythonファイルを作成する。

```lambda-test-02/lambda_function.py
import json

def lambda_handler(event, context):
    # TODO implement

    print( "event:" , event )
    print( "context:", context )

    return {
        'statusCode': 200,
        'body': json.dumps('ok')
    }
```


下記のコマンドでデプロイする。

```
$ ls
deploy.sh  lambda-test-01  lambda-test-02  lambda-test-02.zip  role.json
$ sh deploy.sh lambda-test-02
```

AWSコンソールから確認するとFunctionsが作成されている。
![キャプチャ.PNG](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/514807/2a1d0107-b6cb-fa59-1214-c7d8a004ea5e.png)

API Gateway はAWSコンソールから追加する。
![キャプチャ.PNG](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/514807/d102170e-1c79-41d7-c99a-3a86fea92564.png)

## HTTP経由で実行
下記のスクリプトを作成して実行結果を確認する。
```run.sh
#!/bin/sh

TARGET=https://XXXXXXXXXX.execute-api.ap-northeast-1.amazonaws.com/default/lambda-test-02

API_KEY="XXXXXXXXXXXXX"

curl -o - ${TARGET} --header "x-api-key:${API_KEY}"
```

CloudWatch に print の結果が出力される。(JSON Formatterで整形)
```
"event":{
   "resource":"/lambda-test-02",
   "path":"/lambda-test-02",
   "httpMethod":"GET",
   "headers":{
      "Accept":"*/*",
      "Host":"XXXX.execute-api.ap-northeast-1.amazonaws.com",
      "User-Agent":"curl/7.29.0",
      "X-Amzn-Trace-Id":"Root=1-643465ca-1845828804df7d67487661e2",
      "x-api-key":"XXXXXXXX",
      "X-Forwarded-For":"000.000.000.000",
      "X-Forwarded-Port":"443",
      "X-Forwarded-Proto":"https"
   },
   "multiValueHeaders":{
      "Accept":[
         "*/*"
      ],
      "Host":[
         "XXXX.execute-api.ap-northeast-1.amazonaws.com"
      ],
      "User-Agent":[
         "curl/7.29.0"
      ],
      "X-Amzn-Trace-Id":[
         "Root=1-643465ca-1845828804df7d67487661e2"
      ],
      "x-api-key":[
         "XXXXXXXX"
      ],
      "X-Forwarded-For":[
         "000.000.000.000"
      ],
      "X-Forwarded-Port":[
         "443"
      ],
      "X-Forwarded-Proto":[
         "https"
      ]
   },
   "queryStringParameters":"None",
   "multiValueQueryStringParameters":"None",
   "pathParameters":"None",
   "stageVariables":"None",
   "requestContext":{
      "resourceId":"zz4v8w",
      "resourcePath":"/lambda-test-02",
      "httpMethod":"GET",
      "extendedRequestId":"DLTXoEovNjMFgmQ=",
      "requestTime":"10/Apr/2023:19:38:50 +0000",
      "path":"/default/lambda-test-02",
      "accountId":"XXXX",
      "protocol":"HTTP/1.1",
      "stage":"default",
      "domainPrefix":"XXXX",
      "requestTimeEpoch":1681155530128,
      "requestId":"5bfbf189-9044-4c34-8c60-2ae7e0bff8b1",
      "identity":{
         "cognitoIdentityPoolId":"None",
         "cognitoIdentityId":"None",
         "apiKey":"XXXXXXXX",
         "principalOrgId":"None",
         "cognitoAuthenticationType":"None",
         "userArn":"None",
         "apiKeyId":"XXXXXXXX",
         "userAgent":"curl/7.29.0",
         "accountId":"None",
         "caller":"None",
         "sourceIp":"000.000.000.000",
         "accessKey":"None",
         "cognitoAuthenticationProvider":"None",
         "user":"None"
      },
      "domainName":"XXXX.execute-api.ap-northeast-1.amazonaws.com",
      "apiId":"XXXX"
   },
   "body":"None",
   "isBase64Encoded":false
}
```