AWS Lambda 搭配 Amazon Aurora DSQL 使用 - Amazon Aurora DSQL

Amazon Aurora DSQL 以預覽服務的形式提供。若要進一步了解,請參閱 AWS 服務條款中的 Beta 版和預覽版。

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

AWS Lambda 搭配 Amazon Aurora DSQL 使用

下列各節說明如何將 Lambda 與 Aurora DSQL 搭配使用

先決條件

  • 建立 Lambda 函數的授權。如需詳細資訊,請參閱 Lambda 入門。

  • 建立或修改 Lambda 建立之 IAM 政策的授權。您需要 許可iam:CreatePolicyiam:AttachRolePolicy。如需詳細資訊,請參閱 IAM 的動作、資源和條件索引鍵

  • 您必須已安裝 npm v8.5.3 或更高版本。

  • 您必須已安裝 zip v3.0 或更新版本。

在 中建立新的 函數 AWS Lambda。
  1. 登入 AWS Management Console ,並在 https://https://console.aws.amazon.com/lambda/ 開啟 AWS Lambda 主控台。

  2. 選擇 Create function (建立函數)

  3. 提供名稱,例如 dsql-sample

  4. 請勿編輯預設設定,以確保 Lambda 建立具有基本 Lambda 許可的新角色。

  5. 選擇 Create function (建立函數)

授權您的 Lambda 執行角色連線到您的叢集
  1. 在 Lambda 函數中,選擇組態 > 許可

  2. 選擇角色名稱以在 IAM 主控台中開啟執行角色。

  3. 選擇新增許可 > 建立內嵌政策,然後使用 JSON 編輯器。

  4. 動作中貼上下列動作,以授權您的 IAM 身分使用管理員資料庫角色進行連線。

    "Action": ["dsql:DbConnectAdmin"],
    注意

    我們使用管理員角色,將入門的先決條件步驟降至最低。您不應該為生產應用程式使用管理員資料庫角色。請參閱 以搭配 IAM 角色使用資料庫角色了解如何建立具有最低資料庫許可的授權的自訂資料庫角色。

  5. 資源中,新增叢集的 Amazon Resource Name (ARN)。您也可以使用萬用字元。

    "Resource": ["*"]
  6. 選擇下一步

  7. 輸入政策的名稱,例如 dsql-sample-dbconnect

  8. 選擇建立政策

建立要上傳至 Lambda 的套件。
  1. 建立名為 的資料夾myfunction

  2. 在 資料夾中,package.json使用下列內容建立名為 的新檔案。

    { "dependencies": { "@aws-sdk/core": "^3.587.0", "@aws-sdk/credential-providers": "^3.587.0", "@smithy/protocol-http": "^4.0.0", "@smithy/signature-v4": "^3.0.0", "pg": "^8.11.5" } }
  3. 在 資料夾中,使用下列內容index.mjs在 目錄中建立名為 的檔案。

    import { formatUrl } from "@aws-sdk/util-format-url"; import { HttpRequest } from "@smithy/protocol-http"; import { SignatureV4 } from "@smithy/signature-v4"; import { fromNodeProviderChain } from "@aws-sdk/credential-providers"; import { NODE_REGION_CONFIG_FILE_OPTIONS, NODE_REGION_CONFIG_OPTIONS } from "@smithy/config-resolver"; import { Hash } from "@smithy/hash-node"; import { loadConfig } from "@smithy/node-config-provider"; import pg from "pg"; const { Client } = pg; export const getRuntimeConfig = (config) => { return { runtime: "node", sha256: config?.sha256 ?? Hash.bind(null, "sha256"), credentials: config?.credentials ?? fromNodeProviderChain(), region: config?.region ?? loadConfig(NODE_REGION_CONFIG_OPTIONS, NODE_REGION_CONFIG_FILE_OPTIONS), ...config, }; }; // Aurora DSQL requires IAM authentication // This class generates auth tokens signed using AWS Signature Version 4 export class Signer { constructor(hostname) { const runtimeConfiguration = getRuntimeConfig({}); this.credentials = runtimeConfiguration.credentials; this.hostname = hostname; this.region = runtimeConfiguration.region; this.sha256 = runtimeConfiguration.sha256; this.service = "dsql"; this.protocol = "https:"; } async getAuthToken() { const signer = new SignatureV4({ service: this.service, region: this.region, credentials: this.credentials, sha256: this.sha256, }); // To connect with a custom database role, set Action as "DbConnect" const request = new HttpRequest({ method: "GET", protocol: this.protocol, hostname: this.hostname, query: { Action: "DbConnectAdmin", }, headers: { host: this.hostname, }, }); const presigned = await signer.presign(request, { expiresIn: 3600, }); // RDS requires the scheme to be removed // https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.Connecting.html return formatUrl(presigned).replace(`${this.protocol}//`, ""); } } // To connect with a custom database role, set user as the database role name async function dsql_sample(token, endpoint) { const client = new Client({ user: "admin", database: "postgres", host: endpoint, password: token, ssl: { rejectUnauthorized: false }, }); await client.connect(); console.log("[dsql_sample] connected to Aurora DSQL!"); try { console.log("[dsql_sample] attempting transaction."); await client.query("BEGIN; SELECT txid_current_if_assigned(); COMMIT;"); return 200; } catch (err) { console.log("[dsql_sample] transaction attempt failed!"); console.error(err); return 500; } finally { await client.end(); } } // https://docs.aws.amazon.com/lambda/latest/dg/nodejs-handler.html export const handler = async (event) => { const endpoint = event.endpoint; const s = new Signer(endpoint); const token = await s.getAuthToken(); const responseCode = await dsql_sample(token, endpoint); const response = { statusCode: responseCode, endpoint: endpoint, }; return response; };
  4. 使用下列命令來建立套件。

    npm install zip -r pkg.zip .
上傳程式碼套件並測試您的 Lambda 函數
  1. 在 Lambda 函數的程式碼索引標籤中,選擇從 > .zip 檔案上傳

  2. 上傳pkg.zip您建立的 。如需詳細資訊,請參閱使用 .zip 檔案封存部署 Node.js Lambda 函數。

  3. 在 Lambda 函數的測試索引標籤中,貼上下列 JSON 承載,然後修改它以使用您的叢集 ID。

  4. 在 Lambda 函數的測試索引標籤中,使用以下修改的事件 JSON 來指定叢集的端點。

    {"endpoint": "replace_with_your_cluster_endpoint"}
  5. 輸入事件名稱,例如 dsql-sample-test。選擇儲存

  6. 選擇測試

  7. 選擇詳細資訊以展開執行回應和日誌輸出。

  8. 如果成功,Lambda 函數執行回應應傳回 200 狀態碼:

    {statusCode": 200, "endpoint": "your_cluster_endpoint"}

    如果資料庫傳回錯誤,或資料庫的連線失敗,Lambda 函數執行回應會傳回 500 狀態碼。

    {"statusCode": 500,"endpoint": "your_cluster_endpoint"}