{Aurora}Aurora PostgreSQL DB クラスターから AWS Lambda 関数を呼び出す


(1) Lambda関数作成

-- 1. Lambda用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


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

 

-- 3. Lambda関数作成

vim test.py

#!/usr/bin/python
def lambda_handler(event, context):
    print(event)
    return 'OK'


chmod 755 test.py
zip -r test.zip test.py

aws lambda create-function \
--region ap-northeast-1 \
--function-name test  \
--zip-file fileb://test.zip \
--role arn:aws:iam::999999999999:role/role01 \
--handler test.lambda_handler \
--runtime python3.8 \
--timeout 60 \
--vpc-config SubnetIds="subnet-11111111111111111,subnet-22222222222222222,subnet-33333333333333333",SecurityGroupIds="sg-xxxxxxxxxxxxxxxxx"


aws lambda list-functions
aws lambda list-functions | jq -c '.Functions | [ .FunctionName ]'

aws lambda get-function --function-name test

"State"がactiveになるまで待つ


-- 4. Lambda関数の実行テスト

aws lambda invoke \
--function-name test \
--region ap-northeast-1 \
--payload '{ "key1": "val1" }' \
output.txt

(2) DB作成


-- 5. IAMポリシー作成
vim policy02.json

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AllowAuroraToExampleFunction",
            "Effect": "Allow",
            "Action": "lambda:InvokeFunction",
            "Resource": "arn:aws:lambda:ap-northeast-1:999999999999:function:test"
        }
    ]
}

aws iam create-policy \
--policy-name policy02 \
--policy-document file://policy02.json

-- 6. IAMロール作成
vim role02.json

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

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


-- 7. ポリシーをロールにアタッチ
aws iam attach-role-policy \
--policy-arn arn:aws:iam::999999999999:policy/policy02 \
--role-name role02


-- 8. クラスタの作成

aws rds create-db-cluster \
--db-cluster-identifier cluster01 \
--engine aurora-postgresql \
--engine-version 13.3 \
--master-username postgres \
--master-user-password 'password'

aws rds create-db-instance \
--db-instance-identifier cluster01-instance01 \
--db-cluster-identifier cluster01 \
--db-instance-class db.t3.medium \
--engine aurora-postgresql \
--no-auto-minor-version-upgrade


-- 9. IAMロールをクラスターに関連付ける

aws rds add-role-to-db-cluster \
--db-cluster-identifier cluster01 \
--feature-name Lambda \
--role-arn arn:aws:iam::999999999999:role/role02

 

(3) Lambda 関数の呼び出し

-- 10. 必要な PostgreSQL 拡張機能をインストール

psql -h cluster01.cluster-xxxxxxxxxxxx.ap-northeast-1.rds.amazonaws.com -p 5432 -U postgres

CREATE EXTENSION IF NOT EXISTS aws_lambda CASCADE;


-- 11. lambdaインタフェースエンドポイント作成


aws ec2 create-vpc-endpoint \
--vpc-endpoint-type Interface \
--vpc-id vpc-xxxxxxxxxxxxxxxxx \
--service-name com.amazonaws.ap-northeast-1.lambda \
--subnet-ids "subnet-11111111111111111" "subnet-22222222222222222" "subnet-33333333333333333" \
--security-group-ids "sg-xxxxxxxxxxxxxxxxx" \
--private-dns-enabled

エンドポイントが使用できるようになるまでしばらく時間がかかる


-- 12. lambda関数呼び出し

-- 同期呼び出し
SELECT * FROM aws_lambda.invoke(aws_commons.create_lambda_function_arn('test', 'ap-northeast-1'), '{"key1": "val1"}'::json );

SELECT * FROM aws_lambda.invoke(aws_commons.create_lambda_function_arn('arn:aws:lambda:ap-northeast-1:999999999999:function:test'), '{"key1": "val1"}'::json );


-- 非同期呼び出し
SELECT * FROM aws_lambda.invoke(aws_commons.create_lambda_function_arn('test', 'ap-northeast-1'), '{"key2": "val2"}'::json, 'Event');

SELECT * FROM aws_lambda.invoke(aws_commons.create_lambda_function_arn('arn:aws:lambda:ap-northeast-1:999999999999:function:test'), '{"key2": "val2"}'::json, 'Event');

 

-- 13. クリーンアップ

-- ロールの一覧
aws iam list-roles | grep role01
aws iam list-roles | grep role02

-- ロールの削除

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


aws iam detach-role-policy \
--role-name role02 \
--policy-arn arn:aws:iam::999999999999:policy/policy02

aws iam delete-role --role-name role01
aws iam delete-role --role-name role02

-- ポリシーの一覧
aws iam list-policies | grep policy02

-- ポリシーの削除
aws iam delete-policy \
--policy-arn arn:aws:iam::999999999999:policy/policy02


-- lambda関数の一覧
aws lambda list-functions | jq -c '.Functions | [ .FunctionName ]'

-- lambda関数の削除
aws lambda delete-function --function-name test


-- クラスタ削除
aws rds delete-db-instance \
--db-instance-identifier cluster01-instance01 \
--skip-final-snapshot

aws rds delete-db-cluster \
--db-cluster-identifier cluster01 \
--skip-final-snapshot

 

-- lambdaインタフェースエンドポイントの削除

aws ec2 describe-vpc-endpoints

aws ec2 delete-vpc-endpoints \
--vpc-endpoint-ids vpce-xxxxxxxxxxxxxxxxx