教學課程:設定 Lambda 在 ElastiCache 中存取 VPC - Amazon ElastiCache

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

教學課程:設定 Lambda 在 ElastiCache 中存取 VPC

在本教學課程中,您可以了解如何建立無 ElastiCache 伺服器快取、建立 Lambda 函數,然後測試 Lambda 函數,然後選擇性地清除。

步驟 1:建立無 ElastiCache 伺服器快取。

若要建立無伺服器快取,請遵循下列步驟。

步驟 1.1:建立無伺服器快取

在此步驟中,您可以使用 AWS Command Line Interface () 在帳戶中 us-east-1 區域中的預設 Amazon VPC中建立無伺服器快取CLI。如需使用 ElastiCache 主控台或 建立無伺服器快取的資訊API,請參閱 建立 Valkey 無伺服器快取

aws elasticache create-serverless-cache \ --serverless-cache-name cache-01 \ --description "ElastiCache IAM auth application" \ --engine valkey

請注意,「狀態」欄位的值會設定為 CREATING。可能需要一分鐘 ElastiCache 的時間才能完成建立快取。

步驟 1.2:複製無伺服器快取端點

確認 ElastiCache (Redis OSS) 已完成使用 describe-serverless-caches命令建立快取。

aws elasticache describe-serverless-caches \ --serverless-cache-name cache-01

複製輸出中所顯示的端點地址。您為 Lambda 函數建立部署套件時,會需要這個地址。

步驟 1.3:建立IAM角色

  1. 為您的角色建立IAM信任政策文件,允許您的帳戶擔任新角色,如下所示。將政策儲存到名為 trust-policy.json 的檔案。

    { "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::123456789012:root" }, "Action": "sts:AssumeRole" }, { "Effect": "Allow", "Principal": { "Service": "lambda.amazonaws.com" }, "Action": "sts:AssumeRole" }] }
  2. 建立IAM政策文件,如下所示。將政策儲存到名為 policy.json 的檔案。

    { "Version": "2012-10-17", "Statement": [ { "Effect" : "Allow", "Action" : [ "elasticache:Connect" ], "Resource" : [ "arn:aws:elasticache:us-east-1:123456789012:serverlesscache:cache-01", "arn:aws:elasticache:us-east-1:123456789012:user:iam-user-01" ] } ] }
  3. 建立 IAM 角色。

    aws iam create-role \ --role-name "elasticache-iam-auth-app" \ --assume-role-policy-document file://trust-policy.json
  4. 建立IAM政策。

    aws iam create-policy \ --policy-name "elasticache-allow-all" \ --policy-document file://policy.json
  5. 將IAM政策連接至角色。

    aws iam attach-role-policy \ --role-name "elasticache-iam-auth-app" \ --policy-arn "arn:aws:iam::123456789012:policy/elasticache-allow-all"

步驟 1.4:建立無伺服器快取

  1. 建立新的預設使用者。

    aws elasticache create-user \ --user-name default \ --user-id default-user-disabled \ --engine redis \ --authentication-mode Type=no-password-required \ --access-string "off +get ~keys*"
  2. 建立新的IAM啟用 的使用者。

    aws elasticache create-user \ --user-name iam-user-01 \ --user-id iam-user-01 \ --authentication-mode Type=iam \ --engine redis \ --access-string "on ~* +@all"
  3. 建立使用者群組並連接使用者。

    aws elasticache create-user-group \ --user-group-id iam-user-group-01 \ --engine redis \ --user-ids default-user-disabled iam-user-01 aws elasticache modify-serverless-cache \ --serverless-cache-name cache-01 \ --user-group-id iam-user-group-01

步驟 2:為 建立 Lambda 函數 ElastiCache

若要建立 Lambda 函數以存取 ElastiCache 快取,請執行下列步驟。

步驟 2.1:建立 Lambda 函數

在本教學課程中,我們會在 Python 中提供 Lambda 函數的範例程式碼。

Python

下列 Python 程式碼範例會讀取項目並將其寫入 ElastiCache 快取。複製程式碼並將它儲存到名為 app.py 的檔案中。請務必將程式碼中的elasticache_endpoint值取代為您在上一個步驟中複製的端點地址。

from typing import Tuple, Union from urllib.parse import ParseResult, urlencode, urlunparse import botocore.session import redis from botocore.model import ServiceId from botocore.signers import RequestSigner from cachetools import TTLCache, cached import uuid class ElastiCacheIAMProvider(redis.CredentialProvider): def __init__(self, user, cache_name, is_serverless=False, region="us-east-1"): self.user = user self.cache_name = cache_name self.is_serverless = is_serverless self.region = region session = botocore.session.get_session() self.request_signer = RequestSigner( ServiceId("elasticache"), self.region, "elasticache", "v4", session.get_credentials(), session.get_component("event_emitter"), ) # Generated IAM tokens are valid for 15 minutes @cached(cache=TTLCache(maxsize=128, ttl=900)) def get_credentials(self) -> Union[Tuple[str], Tuple[str, str]]: query_params = {"Action": "connect", "User": self.user} if self.is_serverless: query_params["ResourceType"] = "ServerlessCache" url = urlunparse( ParseResult( scheme="https", netloc=self.cache_name, path="/", query=urlencode(query_params), params="", fragment="", ) ) signed_url = self.request_signer.generate_presigned_url( {"method": "GET", "url": url, "body": {}, "headers": {}, "context": {}}, operation_name="connect", expires_in=900, region_name=self.region, ) # RequestSigner only seems to work if the URL has a protocol, but # Elasticache only accepts the URL without a protocol # So strip it off the signed URL before returning return (self.user, signed_url.removeprefix("https://")) def lambda_handler(event, context): username = "iam-user-01" # replace with your user id cache_name = "cache-01" # replace with your cache name elasticache_endpoint = "cache-01-xxxxx.serverless.use1.cache.amazonaws.com" # replace with your cache endpoint creds_provider = ElastiCacheIAMProvider(user=username, cache_name=cache_name, is_serverless=True) redis_client = redis.Redis(host=elasticache_endpoint, port=6379, credential_provider=creds_provider, ssl=True, ssl_cert_reqs="none") key='uuid' # create a random UUID - this will be the sample element we add to the cache uuid_in = uuid.uuid4().hex redis_client.set(key, uuid_in) result = redis_client.get(key) decoded_result = result.decode("utf-8") # check the retrieved item matches the item added to the cache and print # the results if decoded_result == uuid_in: print(f"Success: Inserted {uuid_in}. Fetched {decoded_result} from Valkey.") else: raise Exception(f"Bad value retrieved. Expected {uuid_in}, got {decoded_result}") return "Fetched value from Valkey"

此程式碼使用 Python redis-py 程式庫,將項目放入快取並擷取它們。此程式碼使用 cachetools IAM 將產生的身分驗證權杖快取 15 分鐘。若要建立包含重新解散和 cachetool 的部署套件,請執行下列步驟。

在包含 app.py 原始程式碼檔案的專案目錄中,建立資料夾套件以安裝 redis-py 和 cachetools 程式庫。

mkdir package

使用 pip 安裝 redis-py、Cachetools。

pip install --target ./package redis pip install --target ./package cachetools

建立包含 redis-py 和 cachetools 程式庫的 .zip 檔案。在 Linux 和 macOS 中,執行下列命令。在 Windows 中,使用您偏好的 zip 公用程式,在根目錄建立具有 redis-py 和 cachetools 程式庫的 .zip 檔案。

cd package zip -r ../my_deployment_package.zip .

將您的函數程式碼新增至 .zip 檔案。在 Linux 和 macOS 中,執行下列命令。在 Windows 中,使用您偏好的 zip 公用程式,將 app.py 新增至 .zip 檔案的根目錄。

cd .. zip my_deployment_package.zip app.py

步驟 2.2:建立IAM角色 (執行角色)

將名為 的 AWS 受管政策AWSLambdaVPCAccessExecutionRole連接至 角色。

aws iam attach-role-policy \ --role-name "elasticache-iam-auth-app" \ --policy-arn "arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole"

步驟 2.3:上傳部署套件 (建立 Lambda 函數)

在此步驟中,您可以使用 create-function AWS CLI 命令建立 Lambda 函數 (AccessValkey)。

從包含部署套件 .zip 檔案的專案目錄中,執行下列 Lambda CLIcreate-function命令。

對於角色選項,請使用您在上一個步驟中建立ARN的執行角色的 。針對 vpc-config,輸入預設 VPC子網路的逗號分隔清單,以及預設 VPC的安全群組 ID。您可以在 Amazon VPC主控台中找到這些值。若要尋找預設VPC的 子網路,請選擇您的 VPCs,然後選擇您 AWS 帳戶的預設 VPC。若要尋找此 的安全群組VPC,請前往安全並選擇安全群組 。確認已選取 us-east-1 區域。

aws lambda create-function \ --function-name AccessValkey \ --region us-east-1 \ --zip-file fileb://my_deployment_package.zip \ --role arn:aws:iam::123456789012:role/elasticache-iam-auth-app \ --handler app.lambda_handler \ --runtime python3.12 \ --timeout 30 \ --vpc-config SubnetIds=comma-separated-vpc-subnet-ids,SecurityGroupIds=default-security-group-id

步驟 3:使用 測試 Lambda 函數 ElastiCache

在此步驟中,您可以使用叫用命令手動叫用 Lambda 函數。當 Lambda 函數執行時,它會產生 ,UUID並將其寫入您在 Lambda 程式碼中指定的 ElastiCache 快取。然後 Lambda 函數從快取中取回項目。

  1. 使用叫用命令叫用 Lambda 函數 AWS Lambda (AccessValkey)。

    aws lambda invoke \ --function-name AccessValkey \ --region us-east-1 \ output.txt
  2. 確認 Lambda 函數是否成功執行,如下:

    • 檢視 output.txt 檔案。

    • 開啟 CloudWatch 主控台並選擇函數的日誌群組 (/aws/lambda/),以驗證 CloudWatch 日誌中的結果AccessValkey。日誌串流應包含類似以下的輸出內容:

      Success: Inserted 826e70c5f4d2478c8c18027125a3e01e. Fetched 826e70c5f4d2478c8c18027125a3e01e from Valkey.
    • 在 AWS Lambda 主控台中檢閱結果。

步驟 4:清除 (選用)

若要清除,請執行下列步驟。

步驟 4.1:刪除 Lambda 函數

aws lambda delete-function \ --function-name AccessValkey

步驟 4.2:刪除無伺服器快取

刪除快取。

aws elasticache delete-serverless-cache \ --serverless-cache-name cache-01

移除使用者和使用者群組。

aws elasticache delete-user \ --user-id default-user-disabled aws elasticache delete-user \ --user-id iam-user-01 aws elasticache delete-user-group \ --user-group-id iam-user-group-01

步驟 4.3:移除IAM角色和政策

aws iam detach-role-policy \ --role-name "elasticache-iam-auth-app" \ --policy-arn "arn:aws:iam::123456789012:policy/elasticache-allow-all" aws iam detach-role-policy \ --role-name "elasticache-iam-auth-app" \ --policy-arn "arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole" aws iam delete-role \ --role-name "elasticache-iam-auth-app" aws iam delete-policy \ --policy-arn "arn:aws:iam::123456789012:policy/elasticache-allow-all"