You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在AWS Node.js Lambda中为V3 AWS-SDK提供跨账户凭证

解决方案

要实现用客户的AWS凭证调用describeVpcs,AWS SDK v3要求为每个客户端实例单独配置凭证,而非全局修改配置。以下是修改后的完整代码:

步骤说明

  • 引入DynamoDB客户端(SDK v3版本),从指定表读取客户的访问密钥和秘密密钥
  • 使用读取到的凭证初始化EC2客户端,替代默认的Lambda执行角色凭证
  • 调用EC2的describeVpcs接口获取目标账户的VPC信息
const { EC2 } = require('@aws-sdk/client-ec2');
const { DynamoDBClient, GetItemCommand } = require('@aws-sdk/client-dynamodb');
const { unmarshall } = require('@aws-sdk/util-dynamodb');

// 初始化DynamoDB客户端(依赖Lambda执行角色权限访问DynamoDB)
const ddbClient = new DynamoDBClient({ region: '你的AWS区域' });

const describeVpcs = async () => {
  try {
    // 1. 从DynamoDB读取客户凭证
    const getItemParams = {
      TableName: '你的DynamoDB表名',
      Key: {
        // 替换为表的主键字段和目标客户标识,比如客户ID
        customerId: { S: '目标客户ID' }
      }
    };
    const ddbResponse = await ddbClient.send(new GetItemCommand(getItemParams));
    
    if (!ddbResponse.Item) {
      throw new Error('未找到目标客户的AWS凭证信息');
    }
    
    // 将DynamoDB的Item格式转换为普通JS对象
    const customerCredentials = unmarshall(ddbResponse.Item);
    const { accessKeyId, secretAccessKey } = customerCredentials;

    // 2. 使用客户凭证初始化EC2客户端
    const ec2Client = new EC2({
      credentials: {
        accessKeyId: accessKeyId,
        secretAccessKey: secretAccessKey
      },
      region: '客户VPC所在的AWS区域' // 必须指定目标VPC所在区域
    });

    // 3. 调用describeVpcs接口
    const params = {};
    const data = await ec2Client.describeVpcs(params);
    return data;
  } catch (e) {
    console.error('执行出错:', e);
    throw new Error(`获取VPC信息失败: ${e.message}`);
  }
};

module.exports = { describeVpcs };

关键注意事项

  • 权限配置:确保Lambda执行角色拥有读取目标DynamoDB表的权限
  • 凭证安全:DynamoDB表需开启服务器端加密,同时严格限制表的访问权限,防止凭证泄露
  • 区域匹配:EC2客户端必须指定客户VPC所在的AWS区域,否则会触发区域不匹配的错误
  • 异常处理:增加了凭证不存在的判断,避免因缺少有效凭证导致的无效调用

内容的提问来源于stack exchange,提问作者Alex Johnston

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 05:52:38