{Lambda}チュートリアル: Amazon VPC の Amazon ElastiCache にアクセスする Lambda 関数の設定

https://docs.aws.amazon.com/ja_jp/lambda/latest/dg/services-elasticache-tutorial.html

 

-- 1. コマンド等のインストール

-- 1.1 aws cli version 2 インストール

curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install

aws --version


-- 2. IAMロール作成
vim role01.json

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "lambda.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

aws iam create-role \
--role-name role01 \
--assume-role-policy-document file://role01.json


-- 3. ポリシーをロールにアタッチ
aws iam attach-role-policy \
--policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole \
--role-name role01

-- 4. ElastiCache クラスターを作成する

aws elasticache create-cache-cluster \
--cache-cluster-id memcached01 \
--cache-node-type cache.t3.micro \
--engine memcached \
--engine-version 1.6.6 \
--cache-parameter-group default.memcached1.6 \
--num-cache-nodes 1 \
--cache-subnet-group-name subnetgroup01

 


aws elasticache describe-cache-clusters --cache-cluster-id memcached01
aws elasticache describe-cache-clusters --cache-cluster-id memcached01 --show-cache-node-info


-- 5. デプロイパッケージを作成する

mkdir package
pip3 install pymemcache elasticache-auto-discovery --target ./package
ll package

vim test.py

from __future__ import print_function
import time
import uuid
import sys
import socket
import elasticache_auto_discovery
from pymemcache.client.hash import HashClient

#elasticache settings
elasticache_config_endpoint = "memcached01.xxxxxx.cfg.apne1.cache.amazonaws.com:11211"
nodes = elasticache_auto_discovery.discover(elasticache_config_endpoint)
nodes = map(lambda x: (x[1], int(x[2])), nodes)
memcache_client = HashClient(nodes)

def handler(event, context):
    """
    This function puts into memcache and get from it.
    Memcache is hosted using elasticache
    """

    #Create a random UUID... this will be the sample element we add to the cache.
    uuid_inserted = uuid.uuid4().hex
    #Put the UUID to the cache.
    memcache_client.set('uuid', uuid_inserted)
    #Get item (UUID) from the cache.
    uuid_obtained = memcache_client.get('uuid')
    if uuid_obtained.decode("utf-8") == uuid_inserted:
        # this print should go to the CloudWatch Logs and Lambda console.
        print ("Success: Fetched value %s from memcache" %(uuid_inserted))
    else:
        raise Exception("Value is not the same as we put :(. Expected %s got %s" %(uuid_inserted, uuid_obtained))

    return "Fetched value from memcache: " + uuid_obtained.decode("utf-8")

 

chmod 755 test.py
chmod -R 755 package

cd package
zip -r ../test.zip .
cd ..
zip -g test.zip test.py

-- 6. Lambda 関数を作成する


aws lambda create-function \
--function-name func01  \
--zip-file fileb://test.zip \
--role arn:aws:iam::999999999999:role/role01 \
--handler test.handler \
--runtime python3.8 \
--timeout 30 \
--memory-size 1024 \
--vpc-config SubnetIds=subnet-11111111111111111,subnet-22222222222222222,subnet-33333333333333333,SecurityGroupIds=sg-44444444444444444

 

aws lambda list-functions | grep func01
aws lambda get-function --function-name func01


-- 7. Lambda 関数をテストする


aws lambda invoke \
--function-name func01 \
output.txt \
--cli-binary-format raw-in-base64-out

cat output.txt


sudo yum -y install telnet

telnet memcached01.xxxxxx.cfg.apne1.cache.amazonaws.com 11211

stats
get uuid

 

-- 8. クリーンアップ

-- Lambda関数の削除
aws lambda get-function --function-name func01
aws lambda delete-function --function-name func01


-- ElastiCacheクラスターの削除

aws elasticache delete-cache-cluster \
--cache-cluster-id memcached01

aws elasticache describe-cache-clusters --cache-cluster-id memcached01

-- ロールの削除
aws iam list-roles | grep role01

aws iam detach-role-policy \
--role-name role01 \
--policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole

aws iam delete-role --role-name role01