📝

非 VPC Lambda からプライベートな RDS に接続してみた

2025/01/19に公開

以下の構成で接続してみました。

手順概要

  1. RDS の作成
  2. RDS プロキシの作成
  3. VPC Lambda の作成
  4. API Gateway の作成
  5. 非 VPC Lambda の作成

前提

  • Lambda 関数の実行ロール用の IAM ロールを作成済みであること
    • AdministratorAccess 権限を付与
  • Cloud9 を使用可能であること

1. RDS の作成 ~ 3. VPC Lambda の作成

RDS-Proxy-AWS-Lambda/RDS Proxy.pdf at main · harunobukameda/RDS-Proxy-AWS-Lambda
上記ハンズオンの手順で作成しました。

VPC Lambda のコードは以下のように変更しました。

index.js
const mysql = require('mysql');

exports.handler = async (event, context) => {
    const connection = mysql.createConnection({
        host: 'database-1-instance-1.cezfqx1ilrp8.ap-northeast-1.rds.amazonaws.com', // RDS プロキシのエンドポイント
        user: 'admin', // MySQLのユーザ名
        password: 'password', // MySQLのパスワード
        database: 'test'
    });

    const query = (sql) => {
        return new Promise((resolve, reject) => {
            connection.query(sql, (err, results) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(results);
                }
            });
        });
    };

    try {
        connection.connect();

        const rows = await query('SELECT * FROM sample');
        console.log(rows);

        return rows;
    } catch (error) {
        console.error('Error:', error);
        throw error;
    } finally {
        connection.end();
    }
};

4. API Gateway の作成

3 で作成した VPC Lambda をバックエンドに設定しました。

  • API タイプ: REST API
  • API エンドポイントタイプ: リージョン
  • メソッド: ANY
  • 統合タイプ: Lambda
  • Lambda プロキシ統合: True
  • Lambda 関数: 3 で作成した VPC Lambda

5. 非 VPC Lambda の作成

以下の設定で作成しました。

  • ランタイム: Node.js 22.x
  • レイヤー: axios をインストールしたレイヤー
  • IAM ロール: AdministratorAccess 権限を付与した IAM ロール
  • コード
index.js
const axios = require('axios');

exports.handler = async (event) => {
    const res = await axios.get("https://{my-api-id}.execute-api.ap-northeast-1.amazonaws.com/{api-stage-name}");
    console.log(res.data)
    return res.data;
};

実行結果

非 VPC Lambda で以下の結果を取得できれば成功です。

[
  {
    "id": 1,
    "value": "test"
  }
]

まとめ

今回は 非 VPC Lambda からプライベートな RDS に接続してみました。
どなたかの参考になれば幸いです。

参考資料

Discussion