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

https://docs.aws.amazon.com/ja_jp/lambda/latest/dg/services-rds-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. RDS データベースインスタンスの作成


aws rds create-db-instance \
--db-instance-identifier mysql01 \
--db-name testdb \
--allocated-storage 5 \
--db-instance-class db.t3.micro \
--engine mysql \
--master-username root \
--master-user-password 'password' \
--no-multi-az \
--engine-version 8.0.25 \
--storage-type gp2 \
--no-publicly-accessible \
--no-enable-performance-insights \
--no-auto-minor-version-upgrade \
--backup-retention-period 1

 

aws rds describe-db-instances

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

vim test.py

import sys
import logging
import rds_config
import pymysql
#rds settings
rds_host  = rds_config.db_hostname
name = rds_config.db_username
password = rds_config.db_password
db_name = rds_config.db_name

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

try:
    conn = pymysql.connect(host=rds_host, user=name, passwd=password, db=db_name, connect_timeout=5)
except pymysql.MySQLError as e:
    logger.error("ERROR: Unexpected error: Could not connect to MySQL instance.")
    logger.error(e)
    sys.exit()

logger.info("SUCCESS: Connection to RDS MySQL instance succeeded")
def handler(event, context):
    """
    This function fetches content from MySQL RDS instance
    """

    item_count = 0

    with conn.cursor() as cur:
        cur.execute("create table Employee ( EmpID  int NOT NULL, Name varchar(255) NOT NULL, PRIMARY KEY (EmpID))")
        cur.execute('insert into Employee (EmpID, Name) values(1, "Joe")')
        cur.execute('insert into Employee (EmpID, Name) values(2, "Bob")')
        cur.execute('insert into Employee (EmpID, Name) values(3, "Mary")')
        conn.commit()
        cur.execute("select * from Employee")
        for row in cur:
            item_count += 1
            logger.info(row)
            #print(row)
    conn.commit()

    return "Added %d items from RDS MySQL table" %(item_count)


vim rds_config.py
#config file containing credentials for RDS MySQL instance
db_hostname = "mysql01.xxxxxxxxxxxx.ap-northeast-1.rds.amazonaws.com"
db_username = "root"
db_password = "password"
db_name = "testdb" 


mkdir package
pip3 install pymysql --target ./package
ll package

chmod 755 test.py rds_config.py
chmod -R 755 package

cd package
zip -r ../test.zip .
cd ..
zip -g test.zip test.py rds_config.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 install mysql -y
mysql -h mysql01.xxxxxxxxxxxx.ap-northeast-1.rds.amazonaws.com -P 3306 -u root -p testdb -e "select * from Employee"

 

-- 8. クリーンアップ
-- Lambda関数の削除
aws lambda get-function --function-name func01
aws lambda delete-function --function-name func01


--  RDS データベースインスタンス削除
aws rds describe-db-instances

aws rds delete-db-instance \
--db-instance-identifier mysql01 \
--skip-final-snapshot


-- ロールの削除
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