教程:将 Lambda 配置为在中进行访问 ElastiCache VPC - 亚马逊 ElastiCache

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

教程:将 Lambda 配置为在中进行访问 ElastiCache VPC

在本教程中,您可以学习如何创建 ElastiCache 无服务器缓存,创建 Lambda 函数,然后测试 Lambda 函数,然后选择在之后进行清理。

步骤 1:创建 ElastiCache 无服务器缓存。

要创建无服务器缓存,请按照以下步骤操作。

步骤 1.1:创建无服务器缓存

在此步骤中,您将使用 () 在账户的 us-east-1 区域的默认亚马逊VPC中创建无服务器缓存。 AWS Command Line Interface 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:复制无服务器缓存端点

使用describe-serverless-caches命令验证 ElastiCache (RedisOSS) 是否已完成缓存的创建。

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 函数

在本教程中,我们为您的 Lambda 函数提供了 Python 中的示例代码。

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 分钟。要创建包含 redis-py 和 cachetools 的部署包,请执行以下步骤。

在包含 app.py 源代码文件的项目目录中,创建一个用于将 redis-py 和 cachetools 库安装到的文件夹包。

mkdir package

使用 pip 安装 redis-py、缓存工具。

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

创建一个包含 redis-py 和 cachetools 库的.zip 文件。在 Linux 和 macOS 中,运行以下命令:在 Windows 中,使用你首选的 zip 实用程序创建一个.zip 文件,根目录为 redis-py 和 cachetools 库。

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 函数)

在此步骤中,您将使用创建函数命令创建 Lambda 函数 (AccessValkey)。 AWS CLI

在包含您的部署包.zip 文件的项目目录中,运行以下 CLI create-function Lambda 命令。

对于角色选项,请使用您在上一步中创建的执行角色的。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. 使用调用命令 AWS Lambda 调用 Lambda 函数 (AccessValkey)。

    aws lambda invoke \ --function-name AccessValkey \ --region us-east-1 \ output.txt
  2. 按以下过程验证 Lambda 函数是否已成功执行:

    • 查看 output.txt 文件。

    • 打开 CloudWatch 控制台并选择函数的 CloudWatch 日志组 (/aws/lambda/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"