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

如何用Account_A的TypeScript Lambda跨账号查询Account_B的CloudWatch日志?

跨账号通过AWS SDK(TypeScript)用Lambda查询CloudWatch日志

假设你的Lambda已配置好跨账号权限(能扮演Account_B中拥有CloudWatch Logs查询权限的IAM角色),下面是具体实现步骤:

1. 导入AWS SDK依赖并配置STS客户端

在TypeScript代码中导入STS和CloudWatchLogs客户端,用Lambda默认的Account_A角色凭证初始化STS客户端:

import { STS, CloudWatchLogs } from 'aws-sdk';

// 初始化Account_A的STS客户端
const sts = new STS();

2. 获取Account_B的临时凭证

调用STS的assumeRole方法,传入Account_B中允许跨账号访问的角色ARN,获取临时凭证:

async function getAccountBCredentials(): Promise<STS.Credentials> {
  const assumeRoleParams = {
    RoleArn: 'arn:aws:iam::ACCOUNT_B_ID:role/CrossAccountCloudWatchQueryRole', // 替换为Account_B的目标角色ARN
    RoleSessionName: 'CrossAccountCloudWatchQuerySession' // 自定义会话名称
  };

  const response = await sts.assumeRole(assumeRoleParams).promise();
  return response.Credentials as STS.Credentials;
}

3. 用Account_B凭证初始化CloudWatch Logs客户端

拿到临时凭证后,创建指向Account_B的CloudWatch Logs客户端:

async function getAccountBCloudWatchLogsClient(): Promise<CloudWatchLogs> {
  const credentials = await getAccountBCredentials();
  return new CloudWatchLogs({
    credentials: {
      accessKeyId: credentials.AccessKeyId!,
      secretAccessKey: credentials.SecretAccessKey!,
      sessionToken: credentials.SessionToken!
    }
  });
}

4. 执行跨账号日志查询

使用初始化好的Account_B客户端,执行startQuery和getQueryResults,注意logGroupName需传入Account_B的目标日志组:

async function queryAccountBLogs(logGroupName: string, queryString: string, startTime: number, endTime: number) {
  const cloudWatchLogs = await getAccountBCloudWatchLogsClient();

  // 启动查询
  const startQueryParams = {
    logGroupName: logGroupName,
    queryString: queryString,
    startTime: startTime,
    endTime: endTime
  };
  const startQueryResponse = await cloudWatchLogs.startQuery(startQueryParams).promise();
  const queryId = startQueryResponse.queryId;

  if (!queryId) {
    throw new Error('Failed to get query ID');
  }

  // 轮询等待查询完成(CloudWatch查询为异步执行)
  let queryResults;
  do {
    await new Promise(resolve => setTimeout(resolve, 1000)); // 每秒轮询一次,可根据需求调整间隔
    const getQueryResultsParams = { queryId: queryId };
    queryResults = await cloudWatchLogs.getQueryResults(getQueryResultsParams).promise();
  } while (queryResults.status === 'Running' || queryResults.status === 'Scheduled');

  if (queryResults.status === 'Failed') {
    throw new Error(`Query failed: ${queryResults.statusMessage}`);
  }

  return queryResults.results;
}

关键注意事项

  • 确保Account_B中的IAM角色信任策略已允许Account_A的Lambda角色调用sts:AssumeRole
  • STS临时凭证默认有效期1小时,可通过assumeRole参数DurationSeconds调整,最长不超过12小时
  • 轮询间隔可根据日志量和查询复杂度调整,避免过于频繁调用API引发限流

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 02:40:13