【AWS Lambda】VPC内のElastiCacheへの接続のコツ

はじめに

AWS LambdaがVPC内リソースへのアクセスが出来るようになりました。

この機能によりセキュアにAWS Lambdaを利用する事が出来るようになり、VPC内にあるRDSやElastiCacheなどとの連携が考えられますね!

今回はAWS LambdaをVPCにあるElastiCacheへ接続を試してみたいと思います。

RDSの記事を参照したい方は、こちらから!

AWS Lambda編~VPCにあるRDSへ接続を試してみる~

本記事の概要

  • AWS LambdaをVPCにあるElastiCacheへ接続するハンズオンを行います
  • ゴールはLambda 関数でUUID を生成し、ElastiCache クラスターに UUID を書き込むまでとします
  • AWSのほかにpipを使用します

ハンズオン

1. ElastiCacheの準備

VPC内にElastiCacheを立ち上げておきます。

image.png

2.Lambdaの作成

次にLambdaをElastiCacheに接続するためにデプロイパッケージで作成します。

今回はAWSのサンプルを利用します。

301 Moved Permanently

1from __future__ import print_function2import time3import uuid4import sys5import socket6import elasticache_auto_discovery7from pymemcache.client.hash import HashClient89#elasticache settings10elasticache_config_endpoint = "your-elasticache-cluster-endpoint:port"11nodes = elasticache_auto_discovery.discover(elasticache_config_endpoint)12nodes = map(lambda x: (x[1], int(x[2])), nodes)13memcache_client = HashClient(nodes)1415def handler(event, context):16    """17    This function puts into memcache and get from it.18    Memcache is hosted using elasticache19    """2021    #Create a random UUID... this will the sample element we add to the cache.22    uuid_inserted = uuid.uuid4().hex23    #Put the UUID to the cache.24    memcache_client.set('uuid', uuid_inserted)25    #Get item (UUID) from the cache.26    uuid_obtained = memcache_client.get('uuid')27    if uuid_obtained == uuid_inserted:2829# this print should go to the CloudWatch Logs and Lambda console.3031        print("Success: Fetched value %s from memcache" % (uuid_inserted))32    else:3334        raise Exception("Value is not the same as we put :(. Expected %s got %s" %(uuid_inserted, uuid_obtained))3536    return "Fetched value from memcache: " + uuid_obtained

続いて以下の依存ライブラリをpipでインストールします。

・pymemcache

・elasticache-auto-discovery

1$ pip install pymemcache -t ./2$ pip install elasticache-auto-discovery -t ./3$ zip –r app.zip *

Lambda Functionを作成します。

その際にIAM Role をlambdabasicvpc_executionで作成します。

image.png

先ほど作成したapp.zipをアップロードして設定します。

Handler はapp.handlerを設定します。

image.png

VPCで実行するように設定を行います。

image.png

3.確認してみる

invokeコマンドを手動で実行して確認してみます。

今回のサンプルでは実行された Lambda 関数は UUID を生成し、Lambda コードで指定された ElastiCache クラスターに、その UUID を書き込みます。次に、Lambda 関数はキャッシュから項目を取得します。

1$ aws lambda invoke --function-name testFunction --region us-east-1 --profile profile_name output.txt2{3    "StatusCode": 2004}5$ cat output.txt6"Fetched value from memcache: d823df2d797047f991b804524c012012

おわりに

今回はAWS LambdaをVPC内のElastiCacheへの接続のハンズオンを行いました。

作業数はそれほど多くの無いので、サクッと終わらせることが出来ました。

本記事とはずれてしまいますが、LambdaとElastiCachにSNSを挟むことでフェイルオーバや再起動が発生した場合もメール等で通知を行うことができるようです。

次回もお楽しみに!!!

この記事を書いた人

aws-recipe-user