AWS Lambda(Python3.9.10)からRDS(PostgreSQL)に接続する

AWS Lambda(Python3.9.10)からRDS(PostgreSQL)に接続する

AWS Lambda(Python3.9.10)からRDSに接続してデータ取得してみます。データを取得するにはaws-psycopg2モジュールを使用します。

requirements.txt

依存モジュールです。

aws-psycopg2

app.py

Pythonのソースです。

import psycopg2

def lambda_handler(event, context):
    conn = psycopg2.connect(
        dbname='SampleDB',
        user='postgres',
        password='postgres1234',
        host='dbinstance.xxxxxxxxxxxx.ap-northeast-1.rds.amazonaws.com'
    )
    cur = conn.cursor()
    cur.execute('SELECT * FROM information_schema.tables;')
    records = cur.fetchall()
    cur.close()
    conn.close()

    return {
        'statusCode': 200,
        'body': records
    }

デプロイ

ビルドしてデプロイします。

C:\>sam build
C:\>sam deploy

テスト

マネジメントコンソールからテストします。

RDSに接続してSQLが発行できました。

タイトルとURLをコピーしました