0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

LambdaからPostgresqlに接続する

Posted at

はじめに

以下の様な事をやってみたいと思います。
Trraform1.drawio (1).png

前提

VPC,Subnet,Routetableが既に作成されていること。
以下の記事で作成しております。
https://qiita.com/Snooze1229/items/13db9d701b91665baa4e

タスク

・Aurora(Postgresql)の作成
・SecretsManager用のVPCエンドポイントの作成
・psycopg2用のLambdaレイヤーの作成
・Lambda関数の作成

今回Lambda関数はDBでアクティブに実行されているプロセスの詳細をセレクトしてみます。

SELECT pid, usename, datname, query
FROM pg_stat_activity
WHERE state = 'active'
  AND usename <> 'rdsadmin';

構築

実際の構築内容は以下で公開しています。
https://github.com/Snooze2929/db-connection-lambda

Lambdaコンソールのテスト機能から実行し、以下の結果が得られれば、DB接続・クエリの実行は成功です。

START RequestId: 748ea7d0-468a-4c98-abf0-982fb047216e Version: $LATEST
[INFO]	2025-08-03T10:12:42.346Z	748ea7d0-468a-4c98-abf0-982fb047216e	Found credentials in environment variables.
Connecting to DB: host=クラスター識別子.cluster-インスタンス識別子.ap-northeast-1.rds.amazonaws.com, dbname=接続したDB名

### クエリ取得部分
[(19566, 'ユーザ名', 'DB名', "SELECT pid, usename, datname, query FROM pg_stat_activity WHERE state = 'active' AND usename <> 'rdsadmin';")]
### クエリ取得部分

END RequestId: 748ea7d0-468a-4c98-abf0-982fb047216e
REPORT RequestId: 748ea7d0-468a-4c98-abf0-982fb047216e	Duration: 2553.30 ms	Billed Duration: 2554 ms	Memory Size: 128 MB	Max Memory Used: 92 MB	Init Duration: 364.70 ms
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?