

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 使用导出 AWS IAM 身份中心身份及其分配的报告 PowerShell
<a name="export-a-report-of-aws-iam-identity-center-identities-and-their-assignments-by-using-powershell"></a>

*Jorge Pava, Frank Allotta、Manideep Reddy Gillela 和 Chad Miles，Amazon Web Services*

## Summary
<a name="export-a-report-of-aws-iam-identity-center-identities-and-their-assignments-by-using-powershell-summary"></a>

当您使用 AWS IAM Identity Center（AWS Single Sign-On 的后续版本）集中管理对所有 Amazon Web Services (AWS) 账户和云应用程序的单点登录（SSO）访问时，通过 AWS 管理控制台报告和审核这些分配可能既乏味又耗时。如果您要报告数十个或数百个 Amazon Web Services account 中的用户或组的权限，则尤其如此。

对于许多人来说，查看此信息的理想工具是电子表格应用程序，例如 Microsoft Excel。这可以帮助您筛选、搜索和观察由 AWS Organizations 管理的整个组织的数据。

此模式描述了如何使用 AWS 工具在 IAM 身份中心生成 SSO 身份配置报告。 PowerShell 该报告的格式为 CSV 文件，包括身份名称（主体）、身份类型（用户或群组）、该身份可以访问的账户以及权限集。生成此报告后，您可在首选应用程序中将其打开，以便根据需要搜索、筛选和审核数据。下图显示了电子表格应用程序中的示例数据。

![\[PowerShell 在电子表格应用程序中查看脚本结果。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/46c7dc7f-c726-4754-b590-2f09d657b167/images/bbc21d8b-fc5d-4b5d-b159-81197a89823e.png)



| 
| 
| 重要：由于此报告包含敏感信息，因此我们强烈建议您将其安全存储，并且仅在 need-to-know基础上共享。 | 
| --- |

## 先决条件和限制
<a name="export-a-report-of-aws-iam-identity-center-identities-and-their-assignments-by-using-powershell-prereqs"></a>

**先决条件**
+ 已配置并启用 IAM Identity Center 和 AWS Organizations。
+ PowerShell，已安装并配置。有关更多信息，请参阅[安装 PowerShell](https://learn.microsoft.com/en-us/powershell/scripting/install/installing-powershell?view=powershell-7.2)（Microsoft 文档）。
+ 已安装并配置 PowerShell的 AWS 工具。出于性能考虑，我们强烈建议您安装名`AWS.Tools`为的 AWS 工具的 PowerShell模块化版本。每个 Amazon Web Service 都由其自己的小模块提供支持。在 PowerShell shell 中，输入以下命令来安装此模式所需的模块：`AWS.Tools.Installer``Organizations`、`SSOAdmin`、和`IdentityStore`。

  ```
  Install-Module AWS.Tools.Installer
  Install-AWSToolsModule -Name Organizations, SSOAdmin, IdentityStore
  ```

  有关更多信息，请参阅[在 Windows 上安装 AWS.Tools 或在 Linux 或 macOS 上](https://docs.aws.amazon.com/powershell/latest/userguide/pstools-getting-set-up-windows.html#ps-installing-awstools)[安装 AWS.Tools（文档的 AWS 工具](https://docs.aws.amazon.com/powershell/latest/userguide/pstools-getting-set-up-linux-mac.html#install-aws.tools-on-linux-macos)）。 PowerShell 如果您在安装模块时收到错误，请参阅此模式的[故障排除](#export-a-report-of-aws-iam-identity-center-identities-and-their-assignments-by-using-powershell-troubleshooting)部分。
+ AWS 命令行界面（AWS CLI）或 AWS 开发工具包必须事先通过以下任一操作配置有效凭证：
  + 使用 AWS CLI `aws configure`。有关更多信息，请参阅[快速配置](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-quickstart.html#cli-configure-quickstart-config)（AWS CLI 文档）。
  + 配置 AWS CLI 或 AWS Cloud Development Kit (AWS CDK)，以通过 AWS Identity and Access Management (IAM) 角色获得临时访问。有关更多信息，请参阅[获取用于 CLI 访问的 IAM 角色凭证](https://docs.aws.amazon.com/singlesignon/latest/userguide/howtogetcredentials.html)（IAM Identity Center 文档）。
+ AWS CLI 的命名配置文件，其中保存了 IAM 主体的证书，该主体具有以下特征：
  + 有权访问 AWS Organizations 管理账户或 IAM Identity Center 的委派管理员账户
  + `AWSSSOReadOnly` 和 `AWSSSODirectoryReadOnly` AWS 托管策略是否已应用于此

  有关更多信息，请参阅[使用命名配置](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html#cli-configure-files-using-profiles)文件(AWS CLI 文档)和 [AWS 托管策略](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-vs-inline.html#aws-managed-policies)（IAM 文档）。

**限制**
+ 目标 Amazon Web Services account 必须在 AWS Organizations 中作为一个组织进行管理。

**产品版本**
+ 对于所有操作系统，建议您使用 [7.0 或更高PowerShell 版本](https://github.com/powershell/powershell)。

## 架构
<a name="export-a-report-of-aws-iam-identity-center-identities-and-their-assignments-by-using-powershell-architecture"></a>

**目标架构**

![\[使用 AWS CLI 命名配置文件编写脚本，在 IAM Identity Center 中创建 SSO 身份报告。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/46c7dc7f-c726-4754-b590-2f09d657b167/images/ae5189aa-8197-4a05-88df-7c0294a679a1.png)


1. 用户在 PowerShell 命令行中运行脚本。

1. 该脚本采用 AWS CLI 命名配置文件。这授予对 IAM Identity Center

1. 该脚本从 IAM Identity Center 检索 SSO 身份配置。

1. 该脚本会在本地工作站上保存脚本的同一目录中生成一个 CSV 文件。

## 工具
<a name="export-a-report-of-aws-iam-identity-center-identities-and-their-assignments-by-using-powershell-tools"></a>

**Amazon Web Services**
+ [AWS 命令行界面（AWS CLI）](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)是一种开源工具，它可帮助您通过命令行 Shell 中的命令与 Amazon Web Services 交互。
+ [AWS IAM Identity Center](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html) 可帮助您集中管理对所有 AWS 账户和云应用程序的单点登录（SSO）访问权限。
+ [AWS 工具 PowerShell](https://docs.aws.amazon.com/powershell/latest/userguide/pstools-welcome.html)是一组 PowerShell 模块，可帮助您通过 PowerShell 命令行编写对 AWS 资源的操作的脚本。

**其他工具**
+ [PowerShell](https://learn.microsoft.com/en-us/powershell/)是一款在 Windows、Linux 和 macOS 上运行的微软自动化和配置管理程序。

## 操作说明
<a name="export-a-report-of-aws-iam-identity-center-identities-and-their-assignments-by-using-powershell-epics"></a>

### 生成报告。
<a name="generate-the-report"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 准备脚本 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/export-a-report-of-aws-iam-identity-center-identities-and-their-assignments-by-using-powershell.html) | 云管理员 | 
| 运行 脚本。 | 建议您使用以下命令在 PowerShell shell 中运行您的自定义脚本。<pre>.\SSO-Report.ps1</pre>或者，您可以通过输入以下命令从其他 Shell 运行脚本。<pre>pwsh .\SSO-Report.ps1</pre>该脚本在脚本文件所在目录中生成一个 CSV 文件。 | 云管理员 | 
| 分析报告数据。 | 输出的 CSV 文件包含标题**AccountName**PermissionSet****、“**主体**” 和 “**类型”**。在首选电子表格应用程序打开此文件。您可创建数据表来筛选和排序输出。 | 云管理员 | 

## 故障排除
<a name="export-a-report-of-aws-iam-identity-center-identities-and-their-assignments-by-using-powershell-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| `The term ‘Get-<parameter>’ is not recognized as the name of a cmdlet, function, script file, or operable program.`错误 | 未安装适用于 PowerShell 或其模块的 AWS 工具。在 PowerShell shell 中，输入以下命令来安装 AWS 工具 PowerShell 以及该模式所需的模块：`AWS.Tools.Installer``Organizations`、`SSOAdmin`、和`IdentityStore`。<pre>Install-Module AWS.Tools.Installer<br />Install-AWSToolsModule -Name Organizations, SSOAdmin, IdentityStore</pre> | 
| `No credentials specified or obtained from persisted/shell defaults`错误 | 在*操作说明[操作说明](#export-a-report-of-aws-iam-identity-center-identities-and-their-assignments-by-using-powershell-epics)部分的准备脚本*中，确认您已正确输入 `ProfileName` 和 `Region` 变量。确保指定配置文件中的设置和凭证具有足够的权限来管理 IAM Identity Center。 | 
| 安装 AWS.Tools 模块时出错 `Authenticode Issuer …` | 向 `Install-AWSToolsModule` 命令添加 `-SkipPublisherCheck`参数。 | 
| `Get-ORGAccountList : Assembly AWSSDK.SSO could not be found or loaded.`错误 | 当指定指定的 AWS CLI 配置文件、AWS CLI 配置为使用 IAM Identity Center 对用户进行身份验证并且 AWS CLI 配置为自动检索刷新的身份验证令牌时，可能会发生此错误。要纠正这个错误，可以执行下列操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/export-a-report-of-aws-iam-identity-center-identities-and-their-assignments-by-using-powershell.html) | 

## 相关资源
<a name="export-a-report-of-aws-iam-identity-center-identities-and-their-assignments-by-using-powershell-resources"></a>
+ [配置设置存储在何处？](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html#cli-configure-files-where) （AWS CLI 文档）
+ [配置 AWS CLI 以使用 AWS IAM Identity Center](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html)（AWS CLI 文档）
+ [使用命名配置文件](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html#cli-configure-files-using-profiles)（AWS CLI 文档）

## 附加信息
<a name="export-a-report-of-aws-iam-identity-center-identities-and-their-assignments-by-using-powershell-additional"></a>

在以下脚本中，确定是否需要更新以下参数值：
+ 如果您在 AWS CLI 中使用命名个人资料访问配置了 IAM Identity Center 的账户，请更新 `$ProfileName` 值。
+ 如果 IAM 身份中心部署在与您的 AWS CLI 或 AWS 开发工具包配置的默认区域不同的 AWS 区域，请更新 `$Region` 值以使用部署 IAM 身份中心的区域。
+ 如果这两种情况都不适用，则不需要更新脚本。

```
param (
    # The name of the output CSV file
    [String] $OutputFile  = "SSO-Assignments.csv",
    # The AWS CLI named profile
    [String] $ProfileName = "",
    # The AWS Region in which IAM Identity Center is configured
    [String] $Region      = ""
)
$Start = Get-Date; $OrgParams = @{}
If ($Region){ $OrgParams.Region = $Region}
if ($ProfileName){$OrgParams.ProfileName = $ProfileName}
$SSOParams   = $OrgParams.Clone(); $IdsParams = $OrgParams.Clone()
$AccountList = Get-ORGAccountList @OrgParams | Select-Object Id, Name
$SSOinstance = Get-SSOADMNInstanceList @OrgParams
$SSOParams['InstanceArn']       = $SSOinstance.InstanceArn
$IdsParams['IdentityStoreId']   = $SSOinstance.IdentityStoreId
$PSsets       = @{}; $Principals   = @{}
$Assignments  = @(); $AccountCount = 1; Write-Host ""
foreach ($Account in $AccountList) {
    $Duration = New-Timespan -Start $Start -End (Get-Date) | ForEach-Object {[Timespan]::New($_.Days, $_.Hours, $_.Minutes, $_.Seconds)}
    Write-Host "`r$Duration - Account $AccountCount of $($AccountList.Count) (Assignments:$($Assignments.Count))        " -NoNewline
    $AccountCount++
    foreach ($PS in Get-SSOADMNPermissionSetsProvisionedToAccountList -AccountId $Account.Id @SSOParams) {
        if (-not $PSsets[$PS]) {$PSsets[$PS] = (Get-SSOADMNPermissionSet @SSOParams -PermissionSetArn $PS).Name;$APICalls++}
        $AssignmentsResponse = Get-SSOADMNAccountAssignmentList @SSOParams -PermissionSetArn $PS -AccountId $Account.Id
        if ($AssignmentsResponse.NextToken) {$AccountAssignments = $AssignmentsResponse.AccountAssignments}
        else {$AccountAssignments = $AssignmentsResponse}
        While ($AssignmentsResponse.NextToken) {
            $AssignmentsResponse = Get-SSOADMNAccountAssignmentList @SSOParams -PermissionSetArn $PS -AccountId $Account.Id -NextToken $AssignmentsResponse.NextToken
            $AccountAssignments += $AssignmentsResponse.AccountAssignments}
        foreach ($Assignment in $AccountAssignments) {
            if (-not $Principals[$Assignment.PrincipalId]) {
                $AssignmentType = $Assignment.PrincipalType.Value
                $Expression     = "Get-IDS"+$AssignmentType+" @IdsParams -"+$AssignmentType+"Id "+$Assignment.PrincipalId
                $Principal      = Invoke-Expression $Expression
                if ($Assignment.PrincipalType.Value -eq "GROUP") { $Principals[$Assignment.PrincipalId] = $Principal.DisplayName } 
                else { $Principals[$Assignment.PrincipalId] = $Principal.UserName }
            }
            $Assignments += [PSCustomObject]@{
                AccountName     = $Account.Name
                PermissionSet   = $PSsets[$PS]
                Principal       = $Principals[$Assignment.PrincipalId]
                Type            = $Assignment.PrincipalType.Value}
        }
    }
}
$Duration = New-Timespan -Start $Start -End (Get-Date) | ForEach-Object {[Timespan]::New($_.Days, $_.Hours, $_.Minutes, $_.Seconds)}
Write-Host "`r$($AccountList.Count) accounts done in $Duration. Outputting result to $OutputFile"
$Assignments | Sort-Object Account | Export-CSV -Path $OutputFile -Force
```