本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
教程:配置 Lambda 以进行访问 ElastiCache 在 VPC 中
在本教程中,你可以学习如何创建 ElastiCache 无服务器缓存,创建 Lambda 函数,然后测试 Lambda 函数,之后可以选择清理。
主题
步骤 1:创建 ElastiCache 无服务器缓存。
要创建无服务器缓存,请按照以下步骤操作。
步骤 1.1:创建无服务器缓存
在此步骤中,您使用以下命令在账户的 us-east-1 区域的默认 Amazon VPC 中创建无服务器缓存 Amazon 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:复制无服务器缓存端点
验证一下 ElastiCache 已完成使用缓存的创建 describe-serverless-caches 命令。
aws elasticache describe-serverless-caches \ --serverless-cache-name cache-01
复制输出中显示的端点地址。在为 Lambda 函数创建部署包时,您将需要此地址。
步骤 1.3:创建 IAM 角色
为您的角色创建 IAM 信任策略文档,如下所示,以允许 Lambda 服务代入新角色。将策略保存到名为 trust-policy.json 的文件中。
{ "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Principal": {"Service": "lambda.amazonaws.com"}, "Action": "sts:AssumeRole" }] }创建 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" ] } ] }创建 IAM 角色。
aws iam create-role \ --role-name "elasticache-iam-auth-app" \ --assume-role-policy-document file://trust-policy.json创建 IAM 策略。
aws iam create-policy \ --policy-name "elasticache-allow-all" \ --policy-document file://policy.json向角色附加 IAM 策略。
aws iam attach-role-policy \ --role-name "elasticache-iam-auth-app" \ --policy-arn "arn:aws:iam::123456789012:policy/elasticache-allow-all"
步骤 1.4:配置 IAM 身份验证
重要
这个步骤为必填项。您的 Lambda 函数经过身份验证 ElastiCache 使用 IAM。要使它起作用,你必须创建一个 IAM-enabled ElastiCache 用户,将其添加到用户组,然后将该用户组与您的缓存关联起来。如果没有此配置,来自 Lambda 的连接尝试将失败。
创建一个 IAM-enabled 用户。这是您的 Lambda 函数将作为其进行身份验证的用户身份。
aws elasticache create-user \ --user-name iam-user-01 \ --user-id iam-user-01 \ --authentication-mode Type=iam \ --engine valkey \ --access-string "on ~* +@all"创建用户组,将该用户添加到该组中,并将该组与您的缓存关联。
aws elasticache create-user-group \ --user-group-id iam-user-group-01 \ --engine valkey \ --user-ids 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 valkey from botocore.model import ServiceId from botocore.signers import RequestSigner from cachetools import TTLCache, cached import uuid class ElastiCacheIAMProvider(valkey.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) valkey_client = valkey.Valkey(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 valkey_client.set(key, uuid_in) result = valkey_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 valkey-py 库将项目放入缓存中并检索它们。此代码使用 cachetools 将生成的 IAM 身份验证令牌缓存 15 分钟。要创建包含 valkey-py 和 cachetools 的部署包,请执行以下步骤。
在包含 app.py 源代码文件的项目目录中,创建一个用于安装 valkey-py 和 cachetools 库的文件夹包。
mkdir package
使用 pip 安装 valkey-py,缓存工具。
pip install --target ./package valkey pip install --target ./package cachetools
创建一个包含 valkey-py 和 cachetools 库的 .zip 文件。在 Linux 和 macOS 中,运行以下命令:在 Windows 中,使用你首选的压缩工具创建一个 .zip 文件,其根目录为 valkey-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 角色(执行角色)
附上 Amazon 名为的托管策略 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) 使用 create-function Amazon CLI 命令。
在包含您的部署包 .zip 文件的项目目录中,运行以下 Lambda CLI create-function 命令。
对于角色选项,请使用您在上一步中创建的执行角色的 ARN。对于 vpc-config,请输入默认 VPC 子网的列表和默认 VPC 安全组 ID 的列表,以逗号分隔。您还可以在 Amazon VPC 控制台中找到这些值。要查找您的默认 VPC 的子网,请选择 你的 VPC,然后选择你的 Amazon 账户的默认 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 并将其写入 ElastiCache 您在 Lambda 代码中指定的缓存。然后,Lambda 函数将从缓存中检索项目。
调用 Lambda 函数 (AccessValkey) 使用 Amazon Lambda 调用命令。
aws lambda invoke \ --function-name AccessValkey \ --region us-east-1 \ output.txt按以下过程验证 Lambda 函数是否已成功执行:
查看 output.txt 文件。
在中验证结果 CloudWatch 通过打开来记录日志 CloudWatch 控制台并为您的函数选择日志组 (/aws/lambda/AccessValkey)。日志流应包含类似于以下内容的输出:
Success: Inserted 826e70c5f4d2478c8c18027125a3e01e. Fetched 826e70c5f4d2478c8c18027125a3e01e from Valkey.在 “查看” 中的结果 Amazon 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"