如何配置权限让AWS Lambda访问OpenSearch Serverless集合?
解决AWS Lambda访问OpenSearch Serverless(AOSS)的权限拒绝问题
1. 给Lambda执行角色添加身份权限策略
Lambda的执行角色缺少AOSS访问权限,需为该角色附加IAM策略:
- 登录AWS IAM控制台,找到该Lambda对应的执行角色
- 点击「添加权限」→「创建内联策略」
- 选择「JSON」模式,粘贴以下策略(可根据需求缩小权限范围,比如指定特定AOSS集合ARN):
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "aoss:APIAccessAll", "Resource": "arn:aws:aoss:eu-central-1:xxxxxxxx:collection/your-collection-name" } ] }
- 完成策略创建并附加到角色
2. 配置AOSS的资源访问策略
仅给Lambda角色加权限还不够,需在AOSS控制台配置资源策略,允许该角色访问:
- 进入OpenSearch Serverless控制台,找到目标集合
- 点击「访问策略」→「编辑」
- 添加以下规则到资源策略中:
{ "Rules": [ { "Resource": ["index/your-collection-name/*"], "Permission": ["aoss:CreateIndex", "aoss:WriteDocument"], "ResourceType": "index", "Principal": ["arn:aws:iam::xxxxxxxx:role/your-lambda-execution-role-name"] } ], "Principal": ["arn:aws:iam::xxxxxxxx:role/your-lambda-execution-role-name"], "Action": ["aoss:APIAccessAll"], "Resource": ["collection/your-collection-name"] }
- 保存策略
3. 修正Lambda代码的配置和异步问题
原代码存在两个关键问题:缺少AWS SigV4签名配置(AOSS要求必须签名),以及异步操作未正确await,修正后的代码如下:
import { Client } from '@opensearch-project/opensearch'; import { awsAuthConnector } from '@opensearch-project/opensearch/aws'; import { defaultProvider } from '@aws-sdk/credential-provider-node'; const REGION = 'eu-central-1'; const SEARCH_ENDPOINT = 'https://some-endpoint.eu-central-1.aoss.amazonaws.com'; // 注意AOSS端点格式为aoss.amazonaws.com // 配置带AWS签名的客户端 const client = new Client({ node: SEARCH_ENDPOINT, Connection: awsAuthConnector({ region: REGION, credentials: defaultProvider() }) }); export const handler = async (event, context) => { try { // 等待索引创建完成 await client.indices.create({ index: 'restaurants' }); console.log(`Index restaurants created`); // 确保bulk的body格式符合要求(示例) const bulkBody = [ { index: { _index: 'restaurants' } }, { name: 'Test Restaurant', location: 'Berlin' } ]; await client.bulk({ body: bulkBody }); return { statusCode: 200, body: 'Data inserted into OpenSearch successfully.' }; } catch (error) { console.error('Error accessing OpenSearch:', error); return { statusCode: 500, body: JSON.stringify({ error: error.message }) }; } };
注意:需确保Lambda层或部署包中包含@opensearch-project/opensearch、@opensearch-project/opensearch/aws和@aws-sdk/credential-provider-node依赖包。
内容的提问来源于stack exchange,提问作者L_Cleo
相关产品推荐
相关产品推荐

