LoginSignup
1
2

More than 1 year has passed since last update.

python の関数を AWS Lambda で使用する

Last updated at Posted at 2017-10-18

次の python の関数を、aws の Lambda にアップロードします。

evening_function.py
# -*- coding: utf-8 -*-
#
#   evening_function.py
#
#                   Nov/03/2017
#
# --------------------------------------------------------------------
import sys
import json

# --------------------------------------------------------------------
def evening_handler(event, context):
    sys.stderr.write("*** evening_handler *** start ***\n")
    print("Received event: " + json.dumps(event, indent=2))
    print("name = " + event['name'])
    print("AAA value1 = " + event['key1'])
    print("BBB value2 = " + event['key2'])
    print("CCC value3 = " + event['key3'])
    sys.stderr.write("*** evening_handler *** end ***\n")
#
    return event['name']  # Echo back the first key value
    #raise Exception('Something went wrong')
# --------------------------------------------------------------------

1) zip で、固めます。

zip -r evening.zip evening_function.py

2) aws にアップロードします。
 morning_exec_role というロールが作られているとします。 ロールの作り方は、
aws cli でラムダを使う

function_create.sh
aws lambda create-function \
    --function-name evening_function \
    --runtime python3.9 \
    --role arn:aws:iam::123456789012:role/morning_exec_role \
    --handler evening_function.evening_handler \
    --zip-file fileb://evening.zip \
    --region ap-northeast-1

3) CLIからイベントを発火

cli_exec.sh
aws lambda invoke --invocation-type Event \
    --function-name evening_function \
    --region ap-northeast-1 \
    --payload  '{"name": "夏目漱石","key1":" こんにちは", "key2":"おはよう", "key3":"さようなら"}' \
    outputfile.txt

4) CloudWatchLogsにログが出力されているか確認

CloudWatch -> ログ -> ロググループ

Node.js のサンプルはこちら
aws cli で Lambda を使う

1
2
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
2