【新機能】AWS LambdaがPythonに対応しました #reinvent

2015.10.09

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

2015/10/11 下記内容を修正しました

  • boto3パッケージは含まれていた
  • 外部ライブラリはzipの直下にある必要があった
  • Handlerの設定手順漏れ

はじめに

藤本です。駆け出しのPythonistaです。

Pythonistaのみなさま、ついに来ましたね。AWS Lambdaの対応言語にPythonが追加されました。ということで、早速、触ってみました。

まずはHello world

まずは設定方法を確認してみます。 LambdaのDashboardからLambda Functionを作成します。

AWS_Lambda

Pythonのblueprintを確認すると、早速7つ用意されています。 今回はhello-world-pythonを選択します。

AWS_Lambda

Pythonで利用可能なバージョンは現在、2.7系のみです。 コードはcodeエディタにインラインで記載しても、ローカル、S3にあるZIPファイルをアップロードするでもOKです。インラインで記載する場合、標準ライブラリ、およびAWS SDK for Pythonしか利用できないので、外部ライブラリを利用したい場合、ZIPファイルアップロードを選択する必要があります。 Hello Worldのコードはlambda_handlerで受け取ったdict型から値を取り出すだけです。

AWS_Lambda AWS_Lambda

設定内容を確認します。

AWS_Lambda

テスト実行します。パラメータはJSON形式で与えます。

AWS_Lambda AWS_Lambda

Execution resultにreturnで指定した値、printの表示はLog outputに記載されています。

AWS_Lambda

外部ライブラリの利用

次は外部ライブラリの利用方法です。ZIPファイルアップロードで外部ライブラリを利用します。 必要なライブラリをインストールします。

# pip install requests -t ./
You are using pip version 7.1.0, however version 7.1.2 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
Collecting requests
Using cached requests-2.8.0-py2.py3-none-any.whl
Installing collected packages: requests
Successfully installed requests-2.8.0

Lambda Functionを作成します。

# vi function.py
---
import requests

def handler(event, context):
return requests.get("https://dev.classmethod.jp/").text
---

Lambda Function、パッケージをまとめて、zip化します。

# ls -l
total 8
-rw-r--r--   1 fujimoto.shinji  staff   102 10 11 10:04 function.py
drwxr-xr-x  32 fujimoto.shinji  staff  1088 10 11 09:55 requests
drwxr-xr-x   8 fujimoto.shinji  staff   272 10 11 09:55 requests-2.8.0.dist-info

# zip -r ~/lambda_function.zip .

ZIPファイルをアップロードします。

AWS_Lambda

今回、Lambda Functionとmethod名を変更したので合わせてConfigurationからHandlerをfunction.handlerに変更し、Save and Testを実行します。

AWS_Lambda

Execution resultにDevelopers.IOのHTMLが表示されました。

AWS_Lambda

中身をちょっと覗く

Pythonのバージョン

詳細なバージョンが気になったので覗いてみました。

import sys

def lambda_handler(event, context):
print(sys.version)
return "ok"

ーーー
START RequestId: adc61606-6e2a-11e5-85ee-8f3417071175 Version: $LATEST
2.7.9 (default, Apr 1 2015, 18:18:03)
[GCC 4.8.2 20140120 (Red Hat 4.8.2-16)]
END RequestId: adc61606-6e2a-11e5-85ee-8f3417071175
REPORT RequestId: adc61606-6e2a-11e5-85ee-8f3417071175 Duration: 0.27 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 8 MB

今現在のPythonのバージョンは2.7.9のようです。 Red Hat?RHEL上で動作しているのでしょうか。

利用可能モジュール

def lambda_handler(event, context):
help("modules")
return "ok"

ーーー
mmap struct
_codecs_iso2022 curl modulefinder subprocess
_codecs_jp curses multifile sunau
_codecs_kr datetime multiprocessing sunaudio
_codecs_tw dateutil mutex symbol
_collections dbhash netrc symtable
_crypt dbm new sys
_csv decimal nis sysconfig
_ctypes difflib nntplib syslog
_curses dircache ntpath tabnanny
_curses_panel dis nturl2path tarfile
_elementtree distutils numbers telnetlib
_functools dl opcode tempfile
_hashlib doctest operator termios
_heapq docutils optparse test
_hotshot dumbdbm os textwrap
_io dummy_thread os2emxpath this
_json dummy_threading ossaudiodev thread
_locale email parser threading
_lsprof encodings pdb time
_multibytecodec ensurepip pickle timeit
_multiprocessing errno pickletools timing
_osx_support exceptions pipes toaiff
_pyio fcntl pkgutil token
_random filecmp platform tokenize
_socket fileinput plistlib trace
_sqlite3 fnmatch popen2 traceback
_sqlitecache formatter poplib tty
_sre fpformat posix types
_ssl fractions posixfile unicodedata
_strptime ftplib posixpath unittest
_struct functools pprint urlgrabber
_symtable future_builtins profile urllib
_sysconfigdata futures pstats urllib2
_threading_local gc pty urlparse
_warnings gdbm pwd user
_weakref genericpath py_compile uu
_weakrefset getopt pyclbr uuid
abc getpass pycurl warnings
aifc gettext pydoc wave
antigravity glob pydoc_data weakref
anydbm gpgme pyexpat webbrowser
argparse grp quopri whichdb
array gzip random wsgi
ast hashlib re wsgiref
asynchat heapq readline xattr
asyncore hmac repr xdrlib
atexit hotshot resource xml
audiodev htmlentitydefs rexec xmllib
audioop htmllib rfc822 xmlrpclib
awslambda httplib rlcompleter xxsubtype
base64 ihooks robotparser yum
bdb imageop rpm zipfile
binascii imaplib rpmUtils zipimport
binhex imghdr runpy zlib

Enter any module name to get more help. Or, type "modules spam" to search
for modules whose descriptions contain the word "spam".

END RequestId: 3257ba11-6e2a-11e5-9beb-bd6914058220
REPORT RequestId: 3257ba11-6e2a-11e5-9beb-bd6914058220 Duration: 8358.14 ms Billed Duration: 8400 ms Memory Size: 128 MB Max Memory Used: 33 MB

なんか、ログがちゃんと表示されていない。うん、標準ライブラリですね。awslambdaってなんだろう。

まとめ

いかがでしたでしょうか? 今まではJava、Javascriptとインフラ担当者には敷居が高い言語がLambdaの対応言語となっていました。私自身、Javaからプログラミングに入りましたが、インフラ担当になってPythonを触り始めてから、簡単なスクリプトや自動化のプログラムは手軽なPythonで実装してきました。そして、魅力に取り憑かれました。なので今回のPython対応は非常に待ち望んでいましたし、今回のre:Invent発表の中でも嬉しいリリースでした。