LoginSignup
10
15

More than 5 years have passed since last update.

LambdaでRDSチュートリアル

Last updated at Posted at 2017-04-27

AWSのAPI GatewayとLambdaとRDSを用いて、RDSに保存されているデータを外部に公開するAPIを作成することを想定して、まずは、LambdaからRDSに接続する

想定するテーブル構造

# テーブル名: link_clicks
| カラム名   | description       | 
| path      | urlのパス         |
| clicks    | リンクのクリック数   |
| stat_date | 集計日             |

1. Lambda関数を作成する

lambdaを用いて、RDS(mysql)に接続して、クエリパラメータ(path)に応じた情報を引き出して返すものプログラムをpythonで作成する

1.1 pythonパッケージ(api)を作る

mkdir api

1.2 pythonの依存パッケージをインストールする

mysqlへの接続のためにPyMySQLをインストールする

pip install PyMySQL -t api

1.3 メイン関数を記載する

メイン関数(handler)記載ファイルと設定ファイルを用意する
(YOUR_XXXは置換する)

api/api.py
# -*- coding: utf-8 -*-
import sys
import logging
import rds_config
import pymysql
import datetime as DT
import json

#rds settings
rds_host  = rds_config.db_host
name = rds_config.db_username
password = rds_config.db_password
db_name = rds_config.db_name


logger = logging.getLogger()
logger.setLevel(logging.INFO)

try:
    mysql_client = pymysql.connect(rds_host, user=name, passwd=password, db=db_name, connect_timeout=5)
except:
    logger.error("ERROR: Unexpected error: Could not connect to MySql instance.")
    sys.exit()

logger.info("SUCCESS: Connection to RDS mysql instance succeeded")

def handler(event, context):
    """
    This function fetches content from mysql RDS instance
    """

    path = event["path"]

    query = "select sum(clicks) from link_clicks where path = '%(path)s' group by path" % dict(path=path)
    logger.info(query)

    results = []
    with mysql_client.cursor() as cur:
        cur.execute(query)
        for row in cur:
            clicks = int(row[0])
            results.append({"clicks": clicks})

    return json.dumps(results)
api/rds_config.py
db_host = "YOUR_HOST"
db_username = "YOUR_USERNAME"
db_password = "YOUR_PASSWORD"
db_name = "YOUR_DB_NAME"

1.4 lambdaにプログラムをアップロード

deploy.sh
# zip作成
(cd api && zip -r - *) > api.zip

# create lambda function
## YOUR_ROLEにはlambda-vpc-execution-roleを指定すること
aws lambda create-function \
--region YOUR_REGION \
--function-name api  \
--zip-file fileb://api.zip \
--role YOUR_ROLE \
--handler api.handler \
--runtime python2.7 \
--vpc-config SubnetIds=YOUR_SUBNET_IDS,SecurityGroupIds=YOUR_SECURITY_GROUP_ID

# update lambda function
aws lambda update-function-code \
--region YOUR_REGION \
--function-name  api  \
--zip-file fileb://api.zip

2. Lambda関数を確認する

2.1 Lambda関数がアップロードされたことを確認する

以下にアクセスして、apiファンクションが追加されたことを確認する
https://ap-northeast-1.console.aws.amazon.com/lambda/home?region=ap-northeast-1#/functions?display=list

apiファンクションが追加されてる.png

2.2 テストイベントを設定する

actions > configure test event からテストイベントを登録する
設定したものは以下の通り

{
  "path": "/11111"
}

testイベント設定.png
テストイベントとしてpathを設定.png

2.3 テストする

上記画像の save&test をクリックしてテストする
テスト結果が表示される.png

最後に

以上の手順で、lambda => RDSに接続して、データを参照できるようになりました
詳細はawsのドキュメントにも書いてあるので、そちらを参考にしてください
http://docs.aws.amazon.com/ja_jp/lambda/latest/dg/vpc-rds-create-lambda-function.html

10
15
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
10
15