【新機能】AWS LambdaがPythonに対応しました #reinvent
はじめに
藤本です。駆け出しのPythonistaです。
Pythonistaのみなさま、ついに来ましたね。AWS Lambdaの対応言語にPythonが追加されました。ということで、早速、触ってみました。
まずはHello world
まずは設定方法を確認してみます。
LambdaのDashboardからLambda Functionを作成します。
Pythonのblueprintを確認すると、早速7つ用意されています。
今回はhello-world-pythonを選択します。
Pythonで利用可能なバージョンは現在、2.7系のみです。
コードはcodeエディタにインラインで記載しても、ローカル、S3にあるZIPファイルをアップロードするでもOKです。インラインで記載する場合、標準ライブラリしか利用できないので、外部ライブラリ(boto3やbotocore等)を利用したい場合、ZIPファイルアップロードを選択する必要があります。
Hello Worldのコードはlambda_handlerで受け取ったdict型から値を取り出すだけです。
設定内容を確認します。
テスト実行します。パラメータはJSON形式で与えます。
Execution resultにreturnで指定した値、printの表示はLog outputに記載されています。
外部ライブラリの利用
次は外部ライブラリの利用方法です。ZIPファイルアップロードで外部ライブラリを利用します。
virtualenvと組み合わせることで準備しやすくなっています。
まずは新規virtualenvを作成します。
# pyenv virtualenv 2.7.10 awslambda New python executable in /Users/fujimoto.shinji/.pyenv/versions/awslambda/bin/python2.7 Also creating executable in /Users/fujimoto.shinji/.pyenv/versions/awslambda/bin/python Installing setuptools, pip, wheel...done. Ignoring indexes: https://pypi.python.org/simple Requirement already satisfied (use --upgrade to upgrade): setuptools in /Users/fujimoto.shinji/.pyenv/versions/awslambda/lib/python2.7/site-packages Requirement already satisfied (use --upgrade to upgrade): pip in /Users/fujimoto.shinji/.pyenv/versions/awslambda/lib/python2.7/site-packages # pyenv local awslambda
次に必要なライブラリをインストールします。
# pip install boto3 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 boto3 Using cached boto3-1.1.4-py2.py3-none-any.whl Collecting jmespath<1.0.0,>=0.7.1 (from boto3) Using cached jmespath-0.9.0-py2.py3-none-any.whl Collecting futures==2.2.0 (from boto3) Using cached futures-2.2.0-py2.py3-none-any.whl Collecting botocore<1.3.0,>=1.2.0 (from boto3) Downloading botocore-1.2.10-py2.py3-none-any.whl (2.0MB) 100% |████████████████████████████████| 2.0MB 233kB/s Collecting python-dateutil<3.0.0,>=2.1 (from botocore<1.3.0,>=1.2.0->boto3) Using cached python_dateutil-2.4.2-py2.py3-none-any.whl Collecting docutils>=0.10 (from botocore<1.3.0,>=1.2.0->boto3) Collecting six>=1.5 (from python-dateutil<3.0.0,>=2.1->botocore<1.3.0,>=1.2.0->boto3) Downloading six-1.10.0-py2.py3-none-any.whl Installing collected packages: jmespath, futures, six, python-dateutil, docutils, botocore, boto3 Successfully installed boto3-1.1.4 botocore-1.2.10 docutils-0.12 futures-2.2.0 jmespath-0.9.0 python-dateutil-2.4.2 six-1.10.0 # pip list 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. boto3 (1.1.4) botocore (1.2.10) docutils (0.12) futures (2.2.0) jmespath (0.9.0) pip (7.1.0) python-dateutil (2.4.2) setuptools (18.0.1) six (1.10.0) wheel (0.24.0)
virtualenvのディレクトリにLambda Functionを作成します。
# cd ~/.pyenv/versions/awslambda # vi function.py --- import boto3 def handler(event, context): client = boto3.client("s3") return client.list_buckets()["Buckets"][0]["Name"] --- # zip -r ~/lambda_function.zip ../awslambda (略)
ZIPファイルをアップロードし、Save and Testで実行します。
Execution resultにS3バケット名が表示されました。
中身をちょっと覗く
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発表の中でも嬉しいリリースでした。