• AWS
  •  

プライベートサブネットのRedshiftにLambdaから接続する

コンテンツ

結論

Redshift Data APIを使うことでプライベートサブネットのRedshiftに接続できます。

解説

実装方法

例として、LambdaからData API経由でSELECT文を発行します。
コードは以下の記事から利用しました。

Lambdaサンプルコード

import json
import time
import boto3

# Redshift接続情報
CLUSTER_NAME='somecluster'
DATABASE_NAME='somedb'
DB_USER='someuser'

# 実行するSQLを設定
sql = '''
    select * from targetdb.targettable limit 1;
'''
def lambda_handler(event, context):
    # Redshiftにクエリを投げる。非同期なのですぐ返ってくる
    data_client = boto3.client('redshift-data')
    result = data_client.execute_statement(
        ClusterIdentifier=CLUSTER_NAME,
        Database=DATABASE_NAME,
        DbUser=DB_USER,
        Sql=sql,
    )
    # 実行IDを取得
    id = result['Id']
    # print('id = {}'.format(id))
    # クエリが終わるのを待つ
    statement = ''
    status = ''
    while status != 'FINISHED' and status != 'FAILED' and status != 'ABORTED':
        statement = data_client.describe_statement(Id=id)
        # print(statement)
        status = statement['Status']
        time.sleep(1)
    # 結果の表示
    if status == 'FINISHED':
        if int(statement['ResultSize']) > 0:
            # select文等なら戻り値を表示
            statement = data_client.get_statement_result(Id=id)
            print(json.dumps(statement['Records']))
        else:
            # 戻り値がないものはFINISHだけ出力して終わり
            print('QUERY FINSHED')
    elif status == 'FAILED':
        # 失敗時
        print('QUERY FAILED\n{}'.format(statement))
    elif status == 'ABORTED':
        # ユーザによる停止時
        print('QUERY ABORTED: The query run was stopped by the user.')

IAM設定

  • Lambda実行ロールに以下の権限が必要です。
    • AmazonRedshiftFullAccess
    • AmazonRedshiftDataFullAccess

実行結果

SELECT文の結果を取得できました。

Function Logs
START RequestId: 83ceb7be-7640-475e-88aa-c75b4d09beeb Version: $LATEST
[[{"stringValue": "aaa}, {"stringValue": "2021-01-01"}]]
END RequestId: 83ceb7be-7640-475e-88aa-c75b4d09beeb
REPORT RequestId: 83ceb7be-7640-475e-88aa-c75b4d09beeb  Duration: 5712.04 ms    Billed Duration: 5713 ms    Memory Size: 128 MB Max Memory Used: 73 MB  Init Duration: 266.20 ms

備考

Redshiftのインスタンスタイプによって利用できない場合があります。

Data API は、次のノードタイプの単一ノードおよび複数ノードクラスターのクエリに使用できます。
dc2.large
dc2.8xlarge
ds2.xlarge
ds2.8xlarge
ra3.xlplus
ra3.4xlarge
ra3.16xlarge

参考

関連記事

  1. IAMポリシーでIP制限をかける方法

  2. Amazon Linux 2でのEBSボリュームサイズのオンライン拡張…

  3. WordPressのサイトURLをDBから確認、変更する

  4. Amazon Redshiftでユーザを作成する方法

  5. Amazon S3暗号化の仕様について確認してみた

  6. AWS LambdaのPython用Layerは有志の提供物を使えば自…

カテゴリ

アーカイブ