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

AWS CDK-IAM:如何通过CDK/CFN获取组织现有用户ID列表?

获取AWS组织内IAM用户列表的CDK实现方案
  • CDK/CloudFormation的核心定位是部署/管理基础设施资源,本身不提供直接查询现有资源的能力——它们是声明式的基础设施编排工具,而非命令式资源查询工具。

  • 要实现该需求,你可以在CDK代码中嵌入AWS SDK for JavaScript/TypeScript的调用,在部署阶段或单独脚本中执行查询:

    1. 确保CDK执行环境拥有足够IAM权限:单账号查询需iam:ListUsers;跨组织账号查询需额外添加organizations:ListAccounts,以及跨账号角色切换的权限。
    2. 示例代码:
      import { IAMClient, ListUsersCommand } from "@aws-sdk/client-iam";
      import { OrganizationsClient, ListAccountsCommand } from "@aws-sdk/client-organizations";
      
      // 查询当前账号下的IAM用户
      const fetchCurrentAccountUsers = async () => {
        const iamClient = new IAMClient({});
        const res = await iamClient.send(new ListUsersCommand({}));
        return res.Users?.map(user => user.UserName) || [];
      };
      
      // 遍历AWS组织内所有账号,查询IAM用户
      const fetchOrgWideUsers = async () => {
        const orgClient = new OrganizationsClient({});
        const orgAccounts = await orgClient.send(new ListAccountsCommand({}));
        const allUsers: string[] = [];
      
        for (const account of orgAccounts.Accounts || []) {
          // 若跨账号查询,需配置角色切换的凭证或使用STS AssumeRole
          const iamClient = new IAMClient({ 
            region: "us-east-1" // 替换为你的目标区域
          });
          const accountUsers = await iamClient.send(new ListUsersCommand({}));
          allUsers.push(...(accountUsers.Users?.map(u => `${account.AccountName}/${u.UserName}`) || []));
        }
      
        return allUsers;
      };
      
      // 在CDK构造函数中调用(执行时机为cdk synth/deploy阶段)
      fetchCurrentAccountUsers().then(users => {
        console.log("当前账号IAM用户列表:", users);
      });
      
    3. 关键注意事项:
      • 这类查询在CDK的合成/部署阶段执行,而非云资源运行时
      • 跨账号查询需提前配置好角色信任关系,确保CDK执行角色能切换到目标账号的权限角色
      • 避免用动态查询结果作为CDK资源定义的依赖——CDK的声明式模型要求资源定义是确定性的,动态结果可能导致部署不稳定
  • 若仅需在部署前获取用户列表,可单独编写Node.js脚本执行上述SDK调用,再将结果传入CDK上下文,这种方式更灵活可控。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 02:57:41