跳至內容

如何建立在 Amazon Redshift 執行查詢的 AWS Lambda 函式?

2 分的閱讀內容
0

我想建立在 Amazon Redshift 執行查詢的 AWS Lambda 函式。

解決方法

先決條件: 若要設定 Amazon Virtual Private Cloud 端點,請完成下列步驟。

  1. 建立具有私有子網路的 VPC。
  2. 建立子網路群組。新增您剛才建立的 VPC 和子網路。
  3. 建立私有 Amazon Redshift 叢集。選取您剛才建立的 VPC 和子網路群組。
  4. 使用 AWS Secrets Manager 為 Amazon Redshift 建立新的密碼。密碼名稱請輸入 redshift。

建立您的 Lambda 函式

若要建立 Lambda 函式以查詢您的 Amazon Redshift 叢集,請完成下列步驟:

  1. 開啟 Lambda 主控台。
  2. 選擇 Create function (建立函式)。
  3. 選擇 Author from Scratch (從頭撰寫) 選項。
  4. 更新下列欄位:
    在 Function name (函式名稱) 輸入自訂名稱。
    在 Runtime (執行時期) 輸入您的程式碼環境。
    注意: 此解決方法中的範例與 Python 3.9 相容。
    在 Architecture (架構) 輸入您的系統架構。
    注意: 此解決方法中的範例與 x86_64 相容。
    針對 Permissions (權限),請選擇 Create a new role with basic Lambda permissions (建立具有基本 Lambda 許可的新角色)。
  5. 選擇 Create function (建立函式)。

為您的 Lambda 函式設定許可

請完成下列步驟:

  1. 開啟 Lambda 主控台。
  2. 選擇 Configuration (組態)。
  3. 選擇 Permissions (許可)。
  4. 選擇為您的 Lambda 函式建立的角色。
  5. 選擇 Add permissions (新增許可)。
  6. 選擇 Attach policies (連接政策)。
  7. 將 AmazonRedshiftDataFullAccess 和 SecretsManagerReadWrite 政策新增至您的 Lambda 執行角色。
    注意: 落實授予最低權限原則,僅允許完成任務所需的許可,是最佳實務。

將 Python 程式碼新增到您的 Lambda 函式

在下列範例中,Lambda 連線至 Amazon Redshift 資料庫,並在公有結構描述建立 lambda_func 資料表。

請完成下列步驟:

  1. 開啟 Lambda 主控台。

  2. 選擇 Code (程式碼)。

  3. 在 Code (程式碼) 方塊中輸入下列程式碼:

    import os
    import json
    import boto3
    import botocore  
    import botocore.session as bc
    from botocore.client import Config
    
    print('Loading function')
    
    secret_name=os.environ['SecretId'] # getting SecretId from Environment varibales
    session = boto3.session.Session()
    region = session.region_name
    
    # Initializing Secret Manager's client     
    client = session.client(
        service_name='secretsmanager',
            region_name=region
        )
    
    get_secret_value_response = client.get_secret_value(
            SecretId=secret_name
        )
    secret_arn=get_secret_value_response['ARN']
    
    secret = get_secret_value_response['SecretString']
    
    secret_json = json.loads(secret)
    
    cluster_id=secret_json['dbClusterIdentifier']
    
    # Initializing Botocore client
    bc_session = bc.get_session()
    
    session = boto3.Session(
            botocore_session=bc_session,
            region_name=region
        )
    
    # Initializing Redshift's client    
    config = Config(connect_timeout=5, read_timeout=5)
    client_redshift = session.client("redshift-data", config = config)
    
    def lambda_handler(event, context):
        print("Entered lambda_handler")
    
        query_str = "create table public.lambda_func (id int);"
        try:
            result = client_redshift.execute_statement(Database= 'dev', SecretArn= secret_arn, Sql= query_str, ClusterIdentifier= cluster_id)
            print("API successfully executed")
    
        except botocore.exceptions.ConnectionError as e:
            client_redshift_1 = session.client("redshift-data", config = config)
            result = client_redshift_1.execute_statement(Database= 'dev', SecretArn= secret_arn, Sql= query_str, ClusterIdentifier= cluster_id)
            print("API executed after reestablishing the connection")
            return str(result)
    
        except Exception as e:
            raise Exception(e)
    
        return str(result)

    注意: 請將 dev 替換為您的資料庫名稱。

  4. 在 Lambda 函式組態區段為索引鍵 SecretId 和 secret_name 新增環境變數。

AWS 官方已更新 6 個月前