

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# IAM 角色
<a name="id_roles"></a>

*IAM 角色*是您可以在帳戶中建立的另一種 IAM 身分，具有特定的許可。IAM 角色類似於 IAM 使用者，因為同樣是 AWS 身分，也有許可政策可決定該身分在 AWS中可執行和不可執行的操作。但是，角色的目的是讓需要它的任何人可代入，而不是單獨地與某個人員關聯。此外，角色沒有與之關聯的標準長期憑證，例如密碼或存取金鑰。反之，當您擔任角色時，其會為您的角色工作階段提供臨時安全性憑證。

您可以使用 角色，將存取權委派給通常無法存取 AWS 資源的使用者、應用程式或服務。例如，您可能想要授予您 AWS 帳戶中的使用者存取他們通常沒有的資源，或授予使用者 AWS 帳戶 存取另一個帳戶中的資源。或者，您可能想要允許行動應用程式使用 AWS 資源，但不想在應用程式中嵌入 AWS 金鑰 （在難以更新的地方，以及使用者可以擷取的地方）。有時，您想要提供 AWS 存取權給已在 外部定義身分的使用者 AWS，例如在您的公司目錄中。或者，您可能需要向第三方授予存取您帳戶的許可，讓他們可以對您的資源執行稽核。

對於這些案例，您可以使用 *IAM 角色*委派對 AWS 資源的存取。本節介紹各種角色和它們的不同使用方式，如何從不同方式中選出適合的時機與方法，以及如何建立、管理、切換到 (或擔任) 和刪除角色。

**注意**  
當您第一次建立 時 AWS 帳戶，預設不會建立任何角色。為帳戶新增服務時，這些服務可能會新增服務連結角色，以支援其使用案例。  
 服務連結角色是連結至 的一種服務角色 AWS 服務。服務可以擔任代表您執行動作的角色。服務連結角色會出現在您的 中 AWS 帳戶 ，並由服務擁有。IAM 管理員可以檢視，但不能編輯服務連結角色的許可。  
在您刪除服務連結角色之前，您必須先刪除這些角色的相關資源。這可保護您的資源，避免您不小心移除資源的存取許可。  
如需哪些服務支援使用服務連結角色的資訊，請參閱 [AWS 使用 IAM 的 服務](reference_aws-services-that-work-with-iam.md)，並尋找 **Service-Linked Role (服務連結角色)** 欄中顯示 **Yes (是)** 的服務。選擇具有連結的 **Yes (是)**，以檢視該服務的服務連結角色文件。

**Topics**
+ [何時建立 IAM 使用者 (而不是角色)](#id_which-to-choose)
+ [角色術語和概念](#id_roles_terms-and-concepts)
+ [其他資源](#id_roles_additional-resources)
+ [混淆代理人問題](confused-deputy.md)
+ [IAM 角色的常見案例](id_roles_common-scenarios.md)
+ [IAM 角色建立](id_roles_create.md)
+ [IAM 角色管理](id_roles_manage.md)
+ [擔任角色的方法](id_roles_manage-assume.md)

## 何時建立 IAM 使用者 (而不是角色)
<a name="id_which-to-choose"></a>

建議您僅將 IAM 使用者用於聯合身分不支援的使用案例。以下是部分使用案例：
+ **無法使用 IAM 角色的工作負載** - 您可以從需要存取 AWS的位置執行工作負載。在某些情況下，您無法使用 IAM 角色提供暫時性憑證，例如針對 WordPress 外掛程式。在這些情況下，請將 IAM 使用者長期存取金鑰用於該工作負載，對 AWS進行身分驗證。
+ **第三方 AWS 用戶端** – 如果您使用不支援透過 IAM Identity Center 存取的工具，例如非託管的第三方 AWS 用戶端或廠商 AWS，請使用 IAM 使用者長期存取金鑰。
+ **AWS CodeCommit 存取** – 如果您使用 CodeCommit 存放程式碼，您可以使用 IAM 使用者搭配 SSH 金鑰或服務特定的登入資料，讓 CodeCommit 驗證您的儲存庫。除了將 IAM Identity Center 中的使用者用於一般身分驗證之外，我們也建議您這樣做。IAM Identity Center 中的使用者是您人力中需要存取您的 AWS 帳戶 或雲端應用程式的人員。若要將您 CodeCommit 儲存庫的存取權授予使用者，而不設定 IAM 使用者，您可以設定 **git-remote-codecommit** 公用程式。如需 IAM 和 CodeCommit 的詳細資訊，請參閱 [CodeCommit 的 IAM 登入資料：Git 登入資料、SSH 金鑰和 AWS 存取金鑰](id_credentials_ssh-keys.md)。如需設定**git-remote-codecommit**公用程式的詳細資訊，請參閱*AWS CodeCommit 《 使用者指南*》中的[使用輪換憑證連線至 AWS CodeCommit 儲存庫](https://docs.aws.amazon.com/codecommit/latest/userguide/temporary-access.html#temporary-access-configure-credentials)。
+ **Amazon Keyspaces (適用於 Apache Cassandra) 存取** – 在無法使用 IAM Identity Center 中的使用者的情況下，例如為了測試 Cassandra 相容性，您可以將 IAM 使用者搭配服務特定憑證使用，以便使用 Amazon Keyspaces 進行身分驗證。IAM Identity Center 中的使用者是您人力中需要存取您的 AWS 帳戶 或雲端應用程式的人員。您也可以使用暫時性憑證連線到 Amazon Keyspaces。如需詳細資訊，請參閱 *Amazon Keyspaces (for Apache Cassandra) Developer Guide* 中的 [Using temporary credentials to connect to Amazon Keyspaces using an IAM role and the SigV4 plugin](https://docs.aws.amazon.com/keyspaces/latest/devguide/access.credentials.html#temporary.credentials.IAM)。
+ **緊急存取**：無法存取身分提供者且必須在 AWS 帳戶中採取動作的情況下。您可以將建立緊急存取 IAM 使用者列入彈性計劃中的一環。建議您使用多重要素驗證 (MFA) 嚴格控管緊急使用者憑證並加以保護。

## 角色術語和概念
<a name="id_roles_terms-and-concepts"></a>

以下是一些基本術語，可協助您開始使用角色。

****Role****  
您可以在帳戶中建立的 IAM 身分具有特定的許可。IAM 角色與 IAM 使用者有一些相似之處。角色和使用者都是具備許可政策的 AWS 身分，可決定身分在 AWS中可執行和不可執行的操作。但是，角色的目的是讓需要它的任何人可代入，而不是單獨地與某個人員關聯。此外，角色沒有與之關聯的標準長期憑證，例如密碼或存取金鑰。反之，當您擔任角色時，其會為您的角色工作階段提供臨時安全性憑證。  
角色可由以下項目擔任：  
+ 相同 AWS 帳戶 或另一個 中的 IAM 使用者 AWS 帳戶
+ 相同帳戶中的 IAM 角色
+ 服務主體，用於 AWS 服務和功能，例如：
  + 可讓您在運算服務上執行程式碼的服務，例如 Amazon EC2 或 AWS Lambda
  + 代表您對資源執行動作的功能，例如 Amazon S3 物件複寫
  + 為在 外部執行的應用程式提供臨時安全登入資料的服務 AWS，例如 IAM Roles Anywhere 或 Amazon ECS Anywhere
+ 透過外部身分提供者 (IdP) 服務進行驗證的外部使用者，並且該服務與 SAML 2.0 或 OpenID Connect 相容

****AWS 服務角色****  
 服務角色是服務擔任的 [IAM 角色](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html)，可代您執行動作。IAM 管理員可以從 IAM 內建立、修改和刪除服務角色。如需詳細資訊，請參閱《*IAM 使用者指南*》中的[建立角色以委派許可給 AWS 服務](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-service.html)。

****AWS 服務連結角色****  
 服務連結角色是連結至 的一種服務角色 AWS 服務。服務可以擔任代表您執行動作的角色。服務連結角色會出現在您的 中 AWS 帳戶 ，並由服務擁有。IAM 管理員可以檢視，但不能編輯服務連結角色的許可。  
如果當服務開始支援服務連結的角色時您已經在使用服務，您可能會收到一封電子郵件，宣告您帳戶中的新角色。在這種情況下，服務會自動在您的帳戶中建立服務連結的角色。您不需要採取任何動作來支援此角色，而且您不應手動刪除它。如需詳細資訊，請參閱 [我的 AWS 帳戶中出現新角色](troubleshoot_roles.md#troubleshoot_roles_new-role-appeared)。
如需哪些服務支援使用服務連結角色的資訊，請參閱 [AWS 使用 IAM 的 服務](reference_aws-services-that-work-with-iam.md)，並尋找 **Service-Linked Role (服務連結角色)** 欄中顯示 **Yes (是)** 的服務。選擇具有連結的 **Yes (是)**，以檢視該服務的服務連結角色文件。如需詳細資訊，請參閱[建立服務連結角色](id_roles_create-service-linked-role.md)。

****角色鏈結****  
當您使用一個角色來擔任第二個角色時，會發生角色鏈結。您可以透過 AWS 管理主控台 切換角色 AWS CLI、 或 API，透過 執行角色鏈結。例如，`RoleA` 擁有擔任 `RoleB` 的許可。您可以透過在 AssumeRole API 操作中使用長期使用者憑證，啟用 User1 擔任 `RoleA`。這會傳回 `RoleA` 短期憑證。透過角色鏈結，您可以使用 `RoleA` 的短期憑證，啟用 User1 擔任 `RoleB`。  
當您擔任角色時，您可以傳遞工作階段標籤，並將標籤設為可轉移。可轉移工作階段標籤會傳遞到角色鏈中所有的後續工作階段。若要進一步了解工作階段標籤，請參閱 [在 中傳遞工作階段標籤 AWS STS](id_session-tags.md)。  
角色鏈結會將您的 AWS 管理主控台 AWS CLI 或 AWS API 角色工作階段限制為最多一小時。無論為個別角色設定的工作階段持續時間上限為何，其皆適用。當您使用 [AssumeRole](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) API 操作來擔任角色時，可以使用 `DurationSeconds` 參數指定角色工作階段的持續時間。您可以指定參數值高達 43200 秒 (12 小時)，這取決於您角色的[最大工作階段持續時間設定](id_roles_update-role-settings.md#id_roles_update-session-duration) 。然而，如果在您使用角色鏈結來擔任角色時，並提供大於一小時的 `DurationSeconds` 參數值，則操作失敗。  
如需切換到 中角色的資訊 AWS 管理主控台，請參閱 [從使用者切換至 IAM 角色 (主控台)](id_roles_use_switch-role-console.md)。

****委派****  
授予許可給某人，以允許存取您控制的資源。委派涉及設定兩個帳戶間的信任。第一個是擁有資源的帳戶 (信任帳戶)。第二個是包含需要存取資源使用者的帳戶 (受信任帳戶)。受信任帳戶和信任帳戶可以是以下任何一個：  
+ 相同帳戶。
+ 都在您的組織的控制之下的個別帳戶。
+ 由不同組織擁有的兩個帳戶。
若要委派許可來存取資源，您要在具有連接兩個政策的信任帳戶中[建立 IAM 角色](id_roles_create_for-user.md)。*許可政策*會授予角色的使用者所需的許可，以對資源執行預定的任務。*信任政策*會指定允許哪些受信任帳戶成員可擔任角色。  
建立信任政策時，您無法在主體元素中指定萬用字元 (\$1) 做為 ARN 的一部分。信任政策會連接到信任帳戶中的角色，並且是許可的二分之一。另外一半是連接到受信任帳戶中使用者的許可政策，其[允許切換為該使用者或擔任該角色 ](id_roles_use_permissions-to-switch.md)。擔任角色的使用者會暫時放棄其自己的許可，改為接受該角色的許可。當使用者退出或停止使用該角色時，會恢復原有的使用者許可。其他稱為[外部 ID](id_roles_common-scenarios_third-party.md#id_roles_third-party_external-id) 的參數有助於確保在不是由相同組織控制的帳戶之間安全使用角色。

****信任政策****  
[JSON 政策文件](reference_policies_grammar.md)，您會在其中定義您*信任*擔任角色的主體。角色信任政策是在 IAM 中連接至角色的[以資源為基礎的必要政策](access_policies.md#policies_resource-based)。您在信任政策中可指定的[主體](reference_policies_elements_principal.md)包含使用者、角色、帳戶和服務。如需詳細資訊，請參閱 *AWS 安全部落格*中的 [How to use trust policies in IAM roles](https://aws.amazon.com/blogs//security/how-to-use-trust-policies-with-iam-roles/)。

****跨帳戶存取的角色****  
將一個帳戶中的資源存取權，授予不同帳戶中受信任主體的角色。角色是授予跨帳戶存取權的主要方式。不過，某些 AWS 服務可讓您將政策直接連接到資源 （而不是使用角色做為代理）。這些稱為以資源為基礎的政策，您可以使用它們來授予其他資源 AWS 帳戶 存取權中的委託人。其中一些資源包括 Amazon Simple Storage Service (S3) 儲存貯體、Amazon Glacier 保存庫、Amazon Simple Notification Service (SNS) 主題以及 Amazon Simple Queue Service (SQS) 佇列。若要了解哪些服務支援以資源為基礎的政策，請參閱 [AWS 使用 IAM 的 服務](reference_aws-services-that-work-with-iam.md)。如需有關以資源為基礎的政策詳細資訊，請參閱 [IAM 中的跨帳戶資源存取](access_policies-cross-account-resource-access.md)。

## 其他資源
<a name="id_roles_additional-resources"></a>

下列資源可協助您進一步了解與 IAM 角色相關的 IAM 術語。
+ **委託人**是 中的實體 AWS ，可執行動作和存取資源。委託人可以是 AWS 帳戶根使用者、IAM 使用者或角色。代表 AWS 服務身分的委託人是[服務委託人](reference_policies_elements_principal.md#principal-services)。使用角色信任政策中的 Principal 元素，來定義您信任能夠擔任角色的主體。

   如需您可以允許擔任角色之主體的詳細資訊和範例，請參閱 [AWS JSON 政策元素： Principal](reference_policies_elements_principal.md)。
+ **聯合身分**會在外部身分提供者與 之間建立信任關係 AWS。您可以使用現有的 OpenID Connect (OIDC) 或安全性聲明標記語言 (SAML) 2.0 提供者來管理誰可以存取 AWS 資源。當您使用 OIDC 和 SAML 2.0 設定這些外部身分提供者與 之間的信任關係時 AWS ，系統會將使用者指派給 IAM 角色。使用者也可以接收臨時憑證，其允許使用者存取您的 AWS 資源。

  如需有關聯合身分主體的詳細資訊，請參閱[身分提供者和聯合身分 AWS](id_roles_providers.md)。
+ **聯合主體**是來自 Directory Service企業使用者目錄或 OIDC 提供者的現有身分。當透過[身分提供者](id_roles_providers.md)請求存取時， 會將角色 AWS 指派給聯合主體。

  如需有關 SAML 和 OIDC 聯合身分主體的詳細資訊，請參閱[聯合身分使用者工作階段和角色](introduction_access-management.md#intro-access-roles)。
+ **許可政策**是身分型政策，可定義角色可以使用的動作和資源。文件的撰寫會根據 IAM 政策語言的規則。

  如需詳細資訊，請參閱[IAM JSON 政策參考](reference_policies.md)。
+ **許可界限**是一種進階功能，可供您使用政策，限制身分型政策可以授予角色的最大許可。您不能將許可界限用到服務連結的角色。

  如需詳細資訊，請參閱[IAM 實體的許可界限](access_policies_boundaries.md)。

# 混淆代理人問題
<a name="confused-deputy"></a>

混淆代理人問題屬於安全性議題，其中沒有執行動作許可的實體可以強制具有更多許可的實體執行該動作。為了避免這種情況，如果您提供第三方 （稱為*跨帳戶*) 或其他 AWS 服務 （稱為*跨服務*) 存取您帳戶中的資源， AWS 會提供可協助您保護帳戶的工具。

有時，您可能需要讓第三方存取您的 AWS 資源 （委派存取權）。例如，您決定聘請名為 Example Corp 的第三方公司來監控您的 AWS 帳戶 並協助最佳化成本。為了追蹤您的每日花費，Example Corp 需要存取您的 AWS 資源。Example Corp 也可監控其他客戶的許多其他 AWS 帳戶 。您可以使用 IAM 角色，在您的 AWS 帳戶 和 Example Corp 帳戶之間建立信任關係。此案例的一個重要方面是*外部 ID*。外部 ID 是一個選用識別碼，您可在 IAM 角色信任政策中使用該識別碼來指定誰可以擔任該角色。外部 ID 的主要功能是解決並防止混淆代理人問題。

有些 AWS 服務 （呼叫 服務） 會使用其 AWS 服務主體從其他服務 AWS （稱為 服務） 存取 AWS 資源。在其中一些服務互動中，您可以設定呼叫服務，以與不同 中呼叫服務的資源通訊 AWS 帳戶。其中一個範例是 AWS CloudTrail 將 設定為寫入位於不同 的中央 Amazon S3 儲存貯體 AWS 帳戶。可透過為 `cloudtrail.amazonaws.com` 新增允許陳述式，使用 S3 儲存貯體的政策向呼叫服務 CloudTrail 授予對 S3 儲存貯體的存取權。

當呼叫 AWS 服務的服務委託人從呼叫的服務存取資源時，呼叫服務的資源政策只會授權 AWS 服務委託人，而不是設定呼叫服務的動作者。例如，信任 CloudTrail 服務主體且無條件的 S3 儲存貯體，可以從 AWS 帳戶 信任的管理員設定的 接收 CloudTrail 日誌，但如果 CloudTrail 知道 S3 儲存貯體的名稱 AWS 帳戶，也會從其中未經授權的演員接收 CloudTrail 日誌。

當演員使用 AWS 服務委託人的信任來存取他們不打算存取的資源時，就會發生混淆代理人問題。

## 預防跨帳戶混淆代理人
<a name="mitigate-confused-deputy"></a>

下圖說明了跨帳戶混淆代理人問題。

![\[混淆代理人問題描述。\]](http://docs.aws.amazon.com/zh_tw/IAM/latest/UserGuide/images/confuseddeputyproblem2.png)


此案例假設如下：
+ **AWS 1** 是您的 AWS 帳戶。
+ **AWS 1:ExampleRole** 是您帳戶中的角色。此角色的信任政策透過將 Example Corp 的 AWS 帳戶指定為可擔任該角色的帳戶來信任 Example Corp。

將發生以下情況：

1. 在您開始使用 Example Corp 的服務時，您將向 Example Corp 提供 **AWS 1:ExampleRole** 的 ARN。

1. Example Corp 使用該角色 ARN 來取得臨時安全登入資料，以存取 中的資源 AWS 帳戶。這樣一來，您將信任 Example Corp 做為可代表您執行操作的「代理人」。

1. 另一個 AWS 客戶也開始使用 Example Corp 的服務，而此客戶也提供 **AWS 1：ExampleRole** 的 ARN，供 Example Corp 使用。另一個客戶可能已了解或猜到已不是機密資訊的 **AWS 1:ExampleRole**。

1. 當其他客戶要求 Example Corp 存取其 帳戶中 AWS 的資源 （其聲稱的內容） 時，Example Corp 會使用 **AWS 1：ExampleRole** 來存取您帳戶中的資源。

這就是其他客戶可對您的資源進行未授權存取的方式。由於此客戶能夠誘使 Example Corp 無意中操作您的資源，因此 Example Corp 現在是一個「混淆代理人」。

Example Corp 可以透過要求在角色的信任政策中包含 `ExternalId` 條件檢查來解決混淆代理人問題。Example Corp 為每個客戶生成唯一的 `ExternalId` 值，並在其請求中使用該值來擔任此角色。因此，`ExternalId` 值必須在 Example Corp 的客戶中具備唯一性，並由 Example Corp 而非其客戶控制。這就是您從 Example Corp 取得該 ID 且不能自行提供該 ID 的原因。這可防止 Example Corp 成為混淆代理人，並授予另一個帳戶的 AWS 資源存取權。

在我們的方案中，假設 Example Corp 為您提供的獨有識別碼是 12345，而為另一個客戶提供的識別碼是 67890。這些識別碼已針對此方案進行簡化。通常，這些識別碼為 GUID。假定這些識別碼在 Example Corp 的客戶之間是獨有的，它們將是用於外部 ID 的有意義的值。

Example Corp 將為您提供外部 ID 值 12345。然後，您必須將一個 `Condition` 元素加入到角色的信任政策，該政策要求 [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html#condition-keys-sts](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html#condition-keys-sts) 值為 12345，如下所示：

------
#### [ JSON ]

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": {
    "Effect": "Allow",
    "Principal": {
      "AWS": "Example Corp's AWS Account ID"
    },
    "Action": "sts:AssumeRole",
    "Condition": {
      "StringEquals": {
        "sts:ExternalId": "12345"
      }
    }
  }
}
```

------

此政策中的 Condition 元素允許 Example Corp 僅在 AssumeRole API 呼叫包括外部 ID 值 12345 時擔任該角色。Example Corp 會確認，只要它代表客戶擔任角色，就會一律在 AssumeRole 呼叫中包括客戶的外部 ID。即使其他客戶為您的 ARN 提供 Example Corp，也無法控制 Example Corp 在其請求中包含的外部 ID AWS。這有助於防止未經授權的客戶取得對您的資源的存取權限。

下圖說明此程序。

![\[如何消除混淆代理人問題。\]](http://docs.aws.amazon.com/zh_tw/IAM/latest/UserGuide/images/confuseddeputymitigation2.png)


1. 與之前一樣，在您開始使用 Example Corp 的服務時，您將向 Example Corp 提供 **AWS 1:ExampleRole** 的 ARN。

1.  在 Example Corp 使用該角色 ARN 來擔任 **AWS 1:ExampleRole** 角色時，Example Corp 將在 AssumeRole API 呼叫中包含您的外部 ID (12345)。外部 ID 符合角色的信任政策，因此 AssumeRole API 呼叫成功，而 Example Corp 會取得臨時安全登入資料來存取您 中的資源 AWS 帳戶。

1. 另一個 AWS 客戶也開始使用 Example Corp 的服務，而如同之前一樣，此客戶也提供 **AWS 1：ExampleRole** 的 ARN，供 Example Corp 使用。

1. 但這一次，在 Example Corp 嘗試擔任角色 **AWS 1:ExampleRole** 時，它提供與其他客戶建立關聯的外部 ID (67890)。其他客戶無法更改此外部 ID。Example Corp 這樣做是因為另一個客戶請求使用該角色，因此 67890 表示 Example Corp 正在其中操作的環境。因為您已將具有您自己的外部 ID (12345) 的條件新增至 **AWS 1:ExampleRole** 的信任政策，所以 AssumeRole API 呼叫將失敗。該其他客戶不能對您帳戶中的資源進行未經授權的存取 (由圖表中的紅色 "X" 表示)。

該外部 ID 說明阻止任何其他客戶誘使 Example Corp 無意中存取您的資源。

## 預防跨服務混淆代理人
<a name="cross-service-confused-deputy-prevention"></a>

下圖使用 CloudTrail 和 Amazon S3 互動範例示範了跨服務混淆代理人問題，其中未經授權的執行者將 CloudTrail 日誌寫入到他們無權存取的 Amazon S3 儲存貯體中。

![\[未經授權的執行者利用 CloudTrail 服務主體取得了對另一個帳戶中 Amazon S3 儲存貯體的存取權。\]](http://docs.aws.amazon.com/zh_tw/IAM/latest/UserGuide/images/cross-service-confused-deputy1.png)


為了協助防止未經授權的演員使用 委託人的信任 AWS 來存取您的資源， AWS 服務委託人包含 AWS 資源 AWS 帳戶及其代表 AWS 的組織的相關資訊。

此資訊可用於可在資源政策中使用的全域條件索引鍵值，或用於 AWS 服務主體所提出請求的資源控制政策。建議您在資源政策[aws:SourceOrgPaths](reference_policies_condition-keys.md#condition-keys-sourceorgpaths)中使用 [aws:SourceArn](reference_policies_condition-keys.md#condition-keys-sourcearn)、[aws:SourceOrgID](reference_policies_condition-keys.md#condition-keys-sourceorgid)、 [aws:SourceAccount](reference_policies_condition-keys.md#condition-keys-sourceaccount)或 ，只要 AWS 服務主體獲得存取其中一個資源的許可。這些條件索引鍵可讓您在資源政策或資源控制政策中進行測試，讓存取資源 AWS 的主體代表 AWS 資源執行此操作 AWS 帳戶，或您 AWS Organizations 預期執行此操作。
+ 使用 `aws:SourceArn` 允許 AWS 服務主體代表特定資源存取您的資源，例如特定 AWS CloudTrail 線索或 AppStream 機群。
+ 使用 `aws:SourceAccount` 允許 AWS 服務主體代表特定 存取您的 資源 AWS 帳戶。
+ 使用 `aws:SourceOrgID` 允許 AWS 服務主體代表特定 存取您的 資源 AWS Organizations。
+ 使用 允許`aws:SourceOrgPaths` AWS 服務主體代表特定 AWS Organizations 路徑存取您的資源。

下圖示範當資源使用`aws:SourceAccount`全域條件內容索引鍵設定時，跨服務混淆代理人案例，而來自另一個帳戶的未經授權演員嘗試存取他們不打算存取 AWS 的資源。

![\[未經授權的執行者無法利用 CloudTrail 服務主體存取另一個帳戶中的 Amazon S3 儲存貯體。\]](http://docs.aws.amazon.com/zh_tw/IAM/latest/UserGuide/images/cross-service-confused-deputy2.png)


在政策中使用 `aws:SourceArn`、`aws:SourceAccount`、`aws:SourceOrgID` 和 `aws:SourceOrgPaths` 全域條件索引鍵，可協助您確保服務主體是代表您存取您的資源。建議您在將其中一個資源的存取權授予 AWS 服務委託人時，使用這些條件金鑰。

**注意**  
有些 AWS 服務 互動具有額外的控制，可協助防止測試使用者存取資源的跨服務混淆代理人問題。例如，當 KMS 金鑰授予授予給 時 AWS 服務， AWS KMS 會使用與資源相關聯的加密內容，以及金鑰授予，以協助防範跨服務混淆代理人問題。  
如需有關可協助避免跨服務混淆代理人風險的服務特定機制，以及 `aws:SourceArn`、`aws:SourceAccount`、`aws:SourceOrgID` 和 `aws:SourceOrgPaths` 是否受支援的詳細資訊，請參閱您所用服務的相關文件。

## 跨服務混淆代理人保護與資源型政策搭配使用
<a name="cross-service-confused-deputy-prevention-resource"></a>

下列範例政策僅在服務主體代表 AWS 帳戶 111122223333 時，授予服務主體對 Amazon S3 儲存貯體 arn：aws：s3：：amzn-s3-demo-bucket1 的`cloudtrail.amazonaws.com`存取權。

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "CloudTrailAclCheck",
            "Effect": "Allow",
            "Principal": {"Service": "cloudtrail.amazonaws.com"},
            "Action": "s3:GetBucketAcl",
            "Resource": "arn:aws:s3:::amzn-s3-demo-bucket1",
            "Condition": {
                "StringEquals": {
                    "aws:SourceAccount": "111122223333"
                }
            }
        },
        {
            "Sid": "AWSCloudTrailWrite",
            "Effect": "Allow",
            "Principal": {"Service": "cloudtrail.amazonaws.com"},
            "Action": "s3:PutObject",
            "Resource": "arn:aws:s3:::amzn-s3-demo-bucket1/[optionalPrefix]/Logs/myAccountID/*",
            "Condition": {
                "StringEquals": {
                    "aws:SourceAccount": "111122223333"
                }
            }
        }
    ]
}
```

------

此範例儲存貯體政策僅在服務主體 `appstream.amazonaws.com` 代表指定的 Amazon AppStream 機群執行動作 (透過以 `aws:SourceArn` 來指定機群 ARN) 時，才授予服務主體對 s3://amzn-s3-demo-bucket2 內的 powershell 指令碼 examplefile.psh 的存取權。

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Service": [
                    "appstream.amazonaws.com"
                ]
            },
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::amzn-s3-demo-bucket2/examplefile.psh",
            "Condition": {
                "ArnEquals": {
                    "aws:SourceArn": "arn:aws:appstream:us-east-1:111122223333:fleet/ExampleFleetName"
                } 
            }
        }
    ]
}
```

------

## 跨服務混淆代理人保護與資源控制政策搭配使用
<a name="cross-service-confused-deputy-prevention-resource-control"></a>

您可以使用資源控制政策 (RCP)，將跨服務混淆代理人控制套用至支援的 AWS 服務資源。RCP 讓您可以在資源上集中套用跨服務混淆代理人控制。您可以使用條件金鑰，例如 `aws:SourceOrgId`和 `aws:SourceOrgPaths` 搭配連接至您 AWS Organizations、組織單位 (OU) 或 AWS 帳戶 組織中RCPs，而無需將陳述式新增至特定資源型政策。如需有關 RCP 和支援服務的詳細資訊，請參閱 *AWS Organizations User Guide* 中的 [Resource control policies (RCPs)](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_rcps.html)。

當 `aws:SourceOrgID` 不等於 o-ExampleOrg 時，下列範例 RCP 會拒絕 AWS 服務主體存取成員帳戶中的 Amazon S3 儲存貯體。對應的允許必須存在於 S3 儲存貯體的資源型政策中，以允許`SourceOrgID`等於 o-ExampleOrg 的 AWS 服務 主體。

此政策僅對具有 `aws:SourceAccount` 索引鍵 (`"Null": {"aws:SourceAccount": "false"}`) 的服務主體 (`"Bool": {"aws:PrincipalIsAWSService": "true"}`) 發出的請求套用控制項，因此不需要使用條件索引鍵的服務整合與您主體的呼叫不會受到影響。如果請求內容中存在 `aws:SourceAccount` 條件索引鍵，則 Null 條件將評估為 true，從而導致強制執行 `aws:SourceOrgID`。我們在 Null 條件運算子中使用 `aws:SourceAccount` 而非 `aws:SourceOrgID`，因此如果請求來自不屬於組織的帳戶，則控制項仍然適用。

------
#### [ JSON ]

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "RCPEnforceConfusedDeputyProtectionForS3",
      "Effect": "Deny",
      "Principal": "*",
      "Action": [
        "s3:*"
      ],
      "Resource": "*",
      "Condition": {
        "StringNotEqualsIfExists": {
          "aws:SourceOrgID": "o-ExampleOrg"
        },
        "Null": {
          "aws:SourceAccount": "false"
        },
        "Bool": {
          "aws:PrincipalIsAWSService": "true"
        }
      }
    }
  ]
}
```

------

# IAM 角色的常見案例
<a name="id_roles_common-scenarios"></a>

與大多數 AWS 功能一樣，您通常有兩種方式可以使用角色：在 IAM 主控台中以互動方式使用，或以程式設計方式使用 AWS CLI、Tools for Windows PowerShell 或 API。
+ 使用 IAM 主控台的帳戶中的 IAM 使用者可以*切換到*角色，以臨時使用主控台中角色的許可。使用者放棄其原始許可並取得指派給該角色的許可。當使用者退出角色時，將恢復其原始許可。
+  AWS （例如 Amazon EC2) 提供的應用程式或服務可以透過請求角色的臨時安全登入資料來*擔任*角色，以便向其發出程式設計請求 AWS。您以這種方式使用角色，這樣您就不必為需要存取資源的每個實體分享或維護長期安全憑證 (例如，透過建立 IAM 使用者)。

**注意**  
本指南互換使用*切換到角色*和*擔任角色*字詞。

使用角色的最簡單方法是授予 IAM 使用者切換到您在自己或另一個 AWS 帳戶中建立之角色的許可。他們可以使用 IAM 主控台輕鬆切換角色，以使用您通常不希望他們擁有的許可，然後退出角色以放棄這些許可。這有助於防止*意外*存取或修改敏感資源。

如需角色的更複雜用途，例如授予存取應用程式和服務，或聯合身分外部使用者，您可以呼叫 `AssumeRole` API。這個 API 呼叫會傳回一組臨時憑證，應用程式可以在後續 API 呼叫中使用這些憑證。嘗試使用臨時憑證的動作只能透過相關的角色授予許可。應用程式不需要像主控台中的使用者般「退出」角色；相反，應用程式只是停止使用臨時憑證並繼續使用原始憑證進行呼叫。

聯合身分使用者使用來自身分提供者 (IdP) 的登入資料來登入。 AWS 然後， 會提供暫時登入資料給信任的 IdP，以傳遞給使用者，以便在後續 AWS 資源請求中包含 。這些憑證提供授予指定角色的許可。

本節概述以下案例：
+ [為您擁有的 IAM 使用者提供存取權 AWS 帳戶 ，以存取您擁有的另一個帳戶中的資源](id_roles_common-scenarios_aws-accounts.md)
+ [提供對非 AWS 工作負載的存取權](id_roles_common-scenarios_non-aws.md)
+ [將存取權提供給第三方擁有之 AWS 帳戶 中的 IAM 使用者](id_roles_common-scenarios_third-party.md)
+ [為 AWSAWS 資源提供的服務提供存取權](id_roles_common-scenarios_services.md)
+ [將存取權提供給外部驗證使用者 (聯合身分)](id_roles_common-scenarios_federated-users.md)

# 在您擁有的另一個 IAM 使用者中 AWS 帳戶 存取
<a name="id_roles_common-scenarios_aws-accounts"></a>

您可以授予 IAM 使用者許可，以切換到 內的角色， AWS 帳戶 或切換到 AWS 帳戶 您擁有的其他 中定義的角色。

**注意**  
如果要授予對您未擁有或無法控制的帳戶的存取許可，請參閱本主題後面的 [存取第三方 AWS 帳戶 擁有的](id_roles_common-scenarios_third-party.md)。

假設您擁有一個對組織來說至關重要的 Amazon EC2 執行個體。您可以使用這些許可來建立角色，而非直接授予使用者終止執行個體的許可。然後，允許管理員可以在需要終止執行個體時切換為該角色。這麼做，可為執行個體加入以下幾層保護：
+ 您必須向使用者明確授予擔任該角色的許可。
+ 您的使用者必須使用 主動切換到角色， AWS 管理主控台 或使用 AWS CLI 或 AWS API 擔任角色。
+ 您可以為角色加入多重要素驗證 (MFA) 保護，僅限登入 MFA 裝置的使用者才能擔任該角色。若要了解如何配置角色以使擔任角色的使用者必須先使用多重要素驗證 (MFA) 進行身分驗證，請參閱 [透過 MFA 實現安全的 API 存取](id_credentials_mfa_configure-api-require.md)。

我們建議使用此方法強制實施*最低權限*。也就是僅限於特定任務需要時，才能使用升級的許可。藉由角色，您可以幫助防止意外更改敏感環境，如果您將它們與[審核](cloudtrail-integration.md)合併以協助確保僅在需要時才使用角色，將會有極大幫助。

在您出於此目的建立角色時，可在該角色的信任政策的 `Principal` 元素中依照 ID 指定其使用者需要存取許可的帳戶。隨後可以向這些其他帳戶中的特定使用者授予切換到角色的許可。若要了解在您信任區域 (受信任組織或帳戶) 外帳戶中的主體是否具有擔任您角色的許可，請參閱[什麼是 IAM Access Analyzer？](https://docs.aws.amazon.com/IAM/latest/UserGuide/what-is-access-analyzer.html)。

一個帳戶中的使用者可以切換為相同或不同帳戶中的角色。使用角色過程中，使用者只能執行角色允許的操作並且只能存取角色允許的資源；其原始使用者許可處於暫停狀態。使用者退出角色時，恢復原始使用者許可。

## 使用不同的開發和生產帳戶的範例方案
<a name="id_roles_common-scenarios_aws-accounts-example"></a>

假設您的組織有多個 AWS 帳戶 來隔離開發環境與生產環境。開發帳戶中的使用者有時可能需要存取生產帳戶中的資源。例如在將更新從開發環境推廣到生產環境時，可能就需要跨帳戶存取許可。儘管您可以為在兩個帳戶中工作的使用者建立單獨的身分 (和密碼)，多個帳戶的憑證管理還是會為身分管理帶來難題。在以下圖表中，所有使用者都透過開發帳戶進行管理，但部分開發人員需要對生產帳戶進行有限存取。開發帳戶有兩個群組：測試人員和開發人員，每個群組有其專屬的政策。

![\[使用角色將許可指派給在不同帳戶中的使用者\]](http://docs.aws.amazon.com/zh_tw/IAM/latest/UserGuide/images/roles-usingroletodelegate.png)


1. 生產帳戶中的一名管理員使用 IAM 在該帳戶中建立 `UpdateApp` 角色。在角色中，管理員定義信任政策，該政策將開發帳戶指定為 `Principal`，這表示開發帳戶中的授權使用者可以使用 `UpdateApp` 角色。管理員也可以為角色定義許可政策，該政策指定名為 `productionapp` 之 Amazon S3 儲存貯體的讀取和寫入許可。

   然後，管理員將與需要擔任角色的任何人共用該角色的帳號和名稱。該資訊是角色的帳號和名稱 （適用於 AWS 主控台使用者） 或 Amazon Resource Name (ARN) （適用於 AWS CLI 或 AWS API 存取）。角色 ARN 類似於 `arn:aws:iam::123456789012:role/UpdateApp`，其中角色名為 `UpdateApp`，而且角色使用帳戶號碼 123456789012 所建立。
**注意**  
管理員可以選擇是否配置角色，以便擔任角色的使用者必須先使用多重要素驗證 (MFA) 進行身分驗證。如需詳細資訊，請參閱 [透過 MFA 實現安全的 API 存取](id_credentials_mfa_configure-api-require.md)。

1. 在開發帳戶中，管理員向開發人員群組的成員授予切換為角色的許可。這是透過授予開發人員群組許可來呼叫`UpdateApp`角色的 AWS Security Token Service (AWS STS) `AssumeRole` API 來完成的。開發帳戶中的開發人員群組的所有 IAM 使用者現在都可以切換為生產帳戶中的 `UpdateApp` 角色。不在開發人員群組中的其他使用者無權切換為該角色，因此無法存取生產帳戶中的 S3 儲存貯體。

1. 使用者請求切換為該角色：
   + AWS 主控台：使用者選擇導覽列上的帳戶名稱，然後選擇**切換角色**。使用者指定帳戶 ID (或別名) 和角色名稱。或者，使用者可以按一下管理員在電子郵件中發送的連結。透過該連結，使用者可以前往已填寫詳細資訊的 **Switch Role (切換角色)** 頁面。
   + AWS API/AWS CLI：開發帳戶開發人員群組中的使用者呼叫 `AssumeRole`函數以取得`UpdateApp`角色的登入資料。使用者將 `UpdateApp` 角色的 ARN 指定為呼叫的一部分。如果測試人員群組中的使用者發出相同請求，請求將失敗，因為測試人員沒有針對 `AssumeRole` 角色 ARN 呼叫 `UpdateApp` 的許可。

1. AWS STS 傳回臨時登入資料：
   + AWS console：使用角色的信任政策 AWS STS 驗證請求，以確保請求來自信任的實體 （即開發帳戶）。驗證後， 會將 AWS [臨時安全登入](https://docs.aws.amazon.com/STS/latest/UsingSTS/Welcome.html)資料 AWS STS 傳回至 主控台。
   + API/CLI：根據角色的信任政策 AWS STS 驗證請求，以確保請求來自信任的實體 （即開發帳戶）。驗證後， 會 AWS STS 傳回[暫時安全登入](https://docs.aws.amazon.com/STS/latest/UsingSTS/Welcome.html)資料給應用程式。

1. 暫時登入資料允許存取 AWS 資源：
   + AWS 主控台： AWS 主控台會代表使用者使用暫時登入資料進行所有後續主控台動作，在此情況下會讀取和寫入儲存`productionapp`貯體。主控台無法存取生產帳戶中的任何其他資源。使用者退出角色時，使用者的許可恢復為切換為角色之前所擁有的原始許可。
   + API/CLI：應用程式使用臨時安全性憑證更新 `productionapp` 儲存貯體。應用程式只能使用臨時安全性憑證讀取和寫入 `productionapp` 儲存貯體，無法存取生產帳戶的任何其他資源。應用程式不必退出角色，只需在後續 API 呼叫中停止使用臨時憑證並使用原始憑證。

## 其他資源
<a name="id_roles_common-scenarios_more-info"></a>

如需詳細資訊，請參閱下列內容：
+ [IAM 教學課程：使用 IAM 角色在 AWS 帳戶之間委派存取權](tutorial_cross-account-with-roles.md)

# 非 AWS 工作負載的存取
<a name="id_roles_common-scenarios_non-aws"></a>

[IAM 角色](id_roles.md)是 AWS Identity and Access Management (IAM) 中獲指派[許可](access_policies.md)的物件。當您使用來自 外部的 IAM 身分或身分[擔任該角色](id_roles_manage-assume.md)時 AWS，它會為您的角色工作階段提供暫時安全登入資料。您可能在資料中心或 外部的其他基礎設施中執行工作負載 AWS ，這些工作負載必須存取您的 AWS 資源。您可以使用 AWS Identity and Access Management Roles Anywhere (IAM Roles Anywhere) 驗證非 AWS 工作負載，而不是建立、分發和管理長期存取金鑰。IAM Roles Anywhere 使用來自憑證授權單位 (CA) 的 X.509 憑證來驗證身分 AWS 服務 ，並使用 IAM 角色提供的臨時憑證安全地提供對 的存取。

**若要使用 IAM Roles Anywhere**

1. 使用 [AWS 私有憑證授權單位](https://docs.aws.amazon.com/privateca/latest/userguide/PcaWelcome.html)設定 CA，或者使用您自己的 PKI 基礎設施中的 CA。

1. 設定 CA 之後，在 IAM Roles Anywhere 中建立稱為*信任錨*的物件。此錨點在 IAM Roles Anywhere 和 CA 之間建立信任，以進行身分驗證。

1. 然後您可以設定現有的 IAM 角色，或建立信任 IAM Roles Anywhere 服務的新角色。

1. 使用信任錨點透過 IAM Roles Anywhere 驗證您的非 AWS 工作負載。 會將非 AWS 工作負載臨時憑證 AWS 授予可存取您 AWS 資源的 IAM 角色。

## 其他資源
<a name="id_roles_non-aws_additional_resources"></a>

下列資源可協助您進一步了解如何提供對非AWS 工作負載的存取權。
+ 如需設定 IAM Roles Anywhere 的詳細資訊，請參閱*《IAM Roles Anywhere 使用者指南》*中的 [What is AWS Identity and Access Management Roles Anywhere](https://docs.aws.amazon.com/rolesanywhere/latest/userguide/introduction.html) (什麼是 IAM Roles Anywhere)。
+ 若要了解如何為 IAM Roles Anywhere 設定公有金鑰基礎設施 (PKI)，請參閱 *AWS 安全部落格*中的 [IAM Roles Anywhere with an external certificate authority](https://aws.amazon.com/blogs/)。

# 存取第三方 AWS 帳戶 擁有的
<a name="id_roles_common-scenarios_third-party"></a>

當第三方需要存取您組織 AWS 的資源時，您可以使用 角色來委派存取權給他們。例如，第三方可能提供一種用於管理您的 AWS 資源之服務。透過 IAM 角色，您可以授予這些第三方存取 資源 AWS 的權限，而無需共用您的 AWS 安全登入資料。相反地，第三方可以透過擔任您在 中建立的角色來存取您的 AWS 資源 AWS 帳戶。若要了解在您信任區域 (受信任組織或帳戶) 外帳戶中的主體是否具有擔任您角色的許可，請參閱[什麼是 IAM Access Analyzer？](https://docs.aws.amazon.com/IAM/latest/UserGuide/what-is-access-analyzer.html)。

為了建立他們可以代入的角色，第三方必須為您提供以下資訊：
+ **第三方的 AWS 帳戶 ID**。為角色定義信任政策時，可將其 AWS 帳戶 ID 指定為主體。
+ **與角色唯一關聯的外部 ID**。外部 ID 可以是只有您和第三方知道的任何識別碼。例如，您可以使用您與該第三方之間的發票 ID，但不要使用能被猜到的內容，例如第三方的電話號碼。為角色定義信任政策時，必須指定該 ID。第三方在代入角色時必須提供該 ID。
+ **第三方為使用您的 AWS 資源而請求獲得的許可**。定義角色的許可政策時，必須指定這些許可。這個政策定義了他們可以執行哪些操作以及可以存取哪些資源。

建立完角色後，您必須向第三方提供該角色的 Amazon Resource Name (ARN)。他們需要使用您的角色的 ARN 來代入該角色。

**重要**  
當您授予第三方存取 資源的權限時 AWS ，他們可以存取您在政策中指定的任何資源。他們使用的資源費用將由您支付。請確保適當地限制他們對資源的使用。

## 第三方存取的外部 ID
<a name="id_roles_third-party_external-id"></a>

外部 ID 允許正擔任該角色的使用者聲明所操作的環境。它還為帳戶擁有者提供一種方法來允許僅在特定情況下擔任該角色。外部 ID 的主要功能是解決並防止 [混淆代理人問題](confused-deputy.md)。

**重要**  
AWS 不會將外部 ID 視為秘密。在您建立存取金鑰對或密碼等秘密之後 AWS，就無法再次檢視它們。具有檢視角色許可的任何人都可看見角色的外部 ID。

## 我何時應使用外部 ID？
<a name="external-id-use"></a>

在以下情況下使用外部 ID：
+ 您是 AWS 帳戶 擁有者，而且已為存取 AWS 帳戶 您 以外的其他 的第三方設定角色。您應要求第三方提供其在擔任您的角色時包含的外部 ID。然後，在您角色的信任政策中檢查該外部 ID。這樣做可確保外部方僅在代表您執行操作時才能擔任您的角色。
+ 在前述情況下，您代表不同客戶 (如 Example Corp) 擔任角色。您應該為每個客戶分配一個唯一的外部 ID 並指導他們將該外部 ID 加入到其角色的信任政策。然後，您必須確保在代入角色的請求中始終包含正確的外部 ID。

  您可能已為您的每個客戶提供一個獨有識別碼，而且此獨有 ID 足以用作外部 ID。該外部 ID 不是您要明確建立或分別追蹤所需的特殊值 (僅用於此目的)。

  您應始終在您的 `AssumeRole` API 呼叫中指定外部 ID。此外，在客戶為您提供角色 ARN 時，請測試是否能在含有/不含有正確外部 ID 的情況下擔任該角色。如果可在沒有正確外部 ID 的情況下擔任角色，則請勿在您的系統中儲存該客戶的角色 ARN。等待該客戶將角色信任政策更新為要求提供正確的外部 ID。這樣一來，您協助您的客戶執行了正確的操作，並幫助您和客戶避免了混淆代理人問題。

## 使用外部 ID 的範例案例
<a name="id_roles_third-party_example"></a>

例如，假設您決定聘請名為 Example Corp 的第三方公司來監控您的 AWS 帳戶 並協助最佳化成本。為了追蹤您的每日花費，Example Corp 需要存取您的 AWS 資源。Example Corp 也可監控其他客戶的許多其他 AWS 帳戶。

請不要向 Example Corp 提供對您 AWS 帳戶中的 IAM 使用者和其長期憑證的存取權。請改用 IAM 角色及其臨時安全性憑證。IAM 角色提供一種機制，允許第三方存取您的 AWS 資源，而不需要共用長期憑證 （例如 IAM 使用者存取金鑰）。

您可以使用 IAM 角色，在您的 AWS 帳戶 與 Example Corp 帳戶之間建立信任關係。建立此關係後，Example Corp 帳戶的成員可以呼叫 AWS Security Token Service [AssumeRole](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) API 來取得臨時安全登入資料。Example Corp 成員接著可以使用登入資料來存取您帳戶中 AWS 的資源。

**注意**  
如需 AssumeRole 和其他您可以呼叫以取得臨時安全登入資料之 AWS API 操作的詳細資訊，請參閱 [比較 AWS STS 登入資料](id_credentials_sts-comparison.md)。

以下是此方案的更多詳細資訊：

1. 您聘請了 Example Corp，此公司將為您建立獨有的客戶識別碼。他們為您提供這個唯一的客戶 ID 及其 AWS 帳戶 號碼。您需要此資訊來在下一個步驟中建立 IAM 角色。
**注意**  
Example Corp 可使用其想用於 ExternalId 的任何字串值，只要該值對於每個客戶來說都是獨有的。該值可以是客戶帳戶，甚至可以是一個隨機字串，只要沒有兩個客戶擁有相同的值即可。該值不是「機密」。Example Corp 必須為每個客戶提供 ExternalId 值。關鍵在於，該值必須由 Example Corp 而***非***由其客戶產生，以確保每個外部 ID 都是唯一的。

1. 您登入 AWS 並建立 IAM 角色，讓 Example Corp 存取您的 資源。與任何 IAM 角色類似，該角色具有兩個政策：許可政策和信任政策。角色的信任政策指定擔任該角色的對象。在我們的範例案例中，政策會將 Example Corp AWS 帳戶 的數量指定為 `Principal`。這允許來自此帳戶的身分擔任該角色。此外，您新增 `[Condition](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition)` 元素到信任政策。此 `Condition` 測試 `ExternalId` 內容索引鍵，以確保它與 Example Corp 的獨有客戶 ID 一致。例如：

   ```
       "Principal": {"AWS": "Example Corp's AWS 帳戶 ID"},
       "Condition": {"StringEquals": {"sts:ExternalId": "Unique ID Assigned by Example Corp"}}
   ```

1. 該角色的許可政策指定該角色允許某個人執行哪些操作。例如，您可以指定該角色允許某人只能管理您的 Amazon EC2 和 Amazon RDS 資源，但不能管理您的 IAM 使用者或群組。在我們的範例方案中，您使用許可政策為 Example Corp 授予帳戶中的所有資源的唯讀存取許可。

1. 建立完角色後，為 Example Corp 提供該角色的 Amazon Resource Name (ARN) (ARN)。

1. 當 Example Corp 需要存取您的 AWS 資源時，公司的某人會 AWS `sts:AssumeRole`呼叫 API。此呼叫包括要擔任的角色的 ARN 和與其客戶 ID 對應的 ExternalId 參數。

如果請求來自使用 Example Corp 的某人 AWS 帳戶，且角色 ARN 和外部 ID 正確，則請求會成功。然後，它會提供臨時安全登入資料，讓 Example Corp 可用來存取您的角色允許 AWS 的資源。

換言之，當角色政策包括外部 ID 時，任何需要擔任該角色的人都必須是該角色中的主體，還必須包括正確的外部 ID。

## 外部 ID 的要點
<a name="id_roles_third-party_key-points"></a>
+ 在多租戶環境中，您支援具有不同 AWS 帳戶的多個客戶，我們建議每個客戶使用一個外部 ID AWS 帳戶。此 ID 應該是由第三方產生的隨機字串。
+ 如要請求第三方在取得角色時提供外部 ID，請使用您選擇的外部 ID 來更新角色的信任政策。
+ 若要在擔任角色時提供外部 ID，請使用 AWS CLI 或 AWS API 擔任該角色。如需詳細資訊，請參閱 STS [AssumeRole](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) API 操作，或是 STS [assume-role](https://docs.aws.amazon.com/cli/latest/reference/sts/assume-role.html) CLI 操作。
+ `ExternalId` 值必須最少為 2 個字元，最多為 1,224 個字元。該值必須為英數字元，且不包含空格。也可以包含下列符號：加號 (\$1)、等號 (=)、逗號 (,)、句號 (.)、小老鼠 (@)、冒號 (:)、正斜線 (/) 和連字號 (-)。

## 其他資源
<a name="id_roles_third-party_additional_resources"></a>

下列資源可協助您進一步了解如何提供對第三方擁有的 AWS 帳戶 的存取權。
+ 若要了解如何允許其他人在您的 中執行動作 AWS 帳戶，請參閱 [使用自訂信任政策建立角色](id_roles_create_for-custom.md)。
+ 若要了解如何授予許可以切換至角色，請參閱[向使用者授予切換角色的許可](id_roles_use_permissions-to-switch.md)
+ 若要了解如何建立並向信任的使用者提供臨時安全憑證，請參閱[臨時安全憑證的許可](id_credentials_temp_control-access.md)。

# 存取 AWS 服務
<a name="id_roles_common-scenarios_services"></a>

許多 AWS 服務要求您使用 角色來控制該服務可存取的內容。服務會擔任代您執行動作的角色稱為[服務角色](id_roles.md#iam-term-service-role)。當角色做為服務的專業用途時，它可以歸類為[服務連結角色](id_roles.md#iam-term-service-linked-role)。請參閱每個服務的 [AWS 文件](https://docs.aws.amazon.com/)，以查看它是否使用角色，以及了解如何指派角色以供服務使用。

如需建立角色以委派存取 提供的服務的詳細資訊 AWS，請參閱 [建立角色以將許可委派給 AWS 服務](id_roles_create_for-service.md)。

# 對外部驗證的使用者的存取權 (聯合身分)
<a name="id_roles_common-scenarios_federated-users"></a>

您的使用者可能已經在 外部擁有身分 AWS，例如在您的公司目錄中。如果這些使用者需要使用 AWS 資源 （或使用存取這些資源的應用程式），則這些使用者也需要 AWS 安全登入資料。您可以使用 IAM 角色為從您的組織或第三方身分提供者 (IdP) 聯合身分的使用者指定許可。

**注意**  
作為安全最佳實務，建議您使用聯合身分在 [IAM Identity Center](https://docs.aws.amazon.com//singlesignon/latest/userguide/what-is.html) 中管理使用者存取權，而不是建立 IAM 使用者。若要了解需要 IAM 使用者的特定情形，請參閱[建立 IAM 使用者 (而非角色) 的時機](https://docs.aws.amazon.com/IAM/latest/UserGuide/id.html#id_which-to-choose)。

## 使用 Amazon Cognito 聯合行動或以 Web 為基礎的應用程式的使用者
<a name="id_roles_common-scenarios_federated-users-cognito"></a>

如果您建立可存取 AWS 資源的行動或 Web 應用程式，則應用程式需要安全登入資料，才能向 發出程式設計請求 AWS。對於大多數行動應用程式藍本，建議您使用 [Amazon Cognito](https://aws.amazon.com/cognito/)。您可以將此服務與適用於 [AWS iOS 的 Mobile SDK](https://aws.amazon.com/sdkforios/) 和[AWS 適用於 Android 和 Fire OS 的 Mobile SDK](https://aws.amazon.com/sdkforandroid/) 搭配使用，為使用者建立唯一身分，並對其進行驗證，以安全地存取您的 AWS 資源。Amazon Cognito 支援與下一個部分中列出的身分提供者相同的身分提供者，並且還支援[開發人員驗證身分](https://aws.amazon.com/blogs/mobile/amazon-cognito-announcing-developer-authenticated-identities)和未經身分驗證 (訪客) 的存取。Amazon Cognito 還提供 API 操作以同步使用者資料，如此可在使用者於不同裝置之間移動時進行保留。如需詳細資訊，請參閱 [用於行動應用程式的 Amazon Cognito](id_federation_common_scenarios.md#id_roles_providers_oidc_cognito)。

## 使用公有身分服務提供者或 OpenID Connect 來聯合使用者
<a name="id_roles_common-scenarios_federated-users-openId"></a>

在可能的情況下，將 Amazon Cognito 用於行動和以 Web 為基礎的應用程式案例。Amazon Cognito 為您提供公有身分提供者服務的大部分幕後工作。它適用於相同的第三方服務，並且還支援匿名登入。但是，對於更進階的案例，您可以直接使用 Login with Amazon、Facebook、Google 或與 OpenID Connect (OIDC) 相容的任何 IdP 等第三方服務。如需有關使用 OIDC 聯合身分來使用其中一項服務的詳細資訊，請參閱 [OIDC 聯合身分](id_roles_providers_oidc.md)。

## 使用 SAML 2.0 聯合使用者
<a name="id_roles_common-scenarios_federated-users-saml20"></a>

如果您的組織已使用支援 SAML 2.0 （安全性聲明標記語言 2.0) 的身分提供者軟體套件，您可以在組織之間建立信任做為身分提供者 (IdP) 和 AWS 做為服務提供者。然後，您可以使用 SAML 為使用者提供 AWS 管理主控台 或 聯合身分的單一登入 (SSO)，以呼叫 AWS API 操作。例如，如果您的公司使用 Microsoft Active Directory 和 Active Directory Federation Services，則可以使用 SAML 2.0 聯合。如需有關使用 SAML 2.0 聯合使用者的詳細資訊，請參閱[SAML 2.0 聯合身分](id_roles_providers_saml.md)。

## 透過建立自訂身分經紀人應用程式來聯合使用者
<a name="id_roles_common-scenarios_federated-users-idbroker"></a>

如果您的身分存放區與 SAML 2.0 不相容，則可以建置自訂身分經紀人應用程式以執行類似的功能。代理程式應用程式會驗證使用者、請求使用者的臨時登入資料 AWS，然後將他們提供給使用者以存取 AWS 資源。

例如，Example Corp. 有許多員工需要執行存取公司 AWS 資源的內部應用程式。員工已經在公司身分和身分驗證系統中擁有身分，而 Example Corp. 不想要為每個公司員工建立個別的 IAM 使用者。

Bob 是 Example Corp. 的開發人員。 為了讓 Example Corp. 內部應用程式能夠存取公司的 AWS 資源，Bob 開發了自訂身分代理程式應用程式。該應用程式驗證員工是否已登入到現有的 Example Corp. 身分和身分驗證系統，該系統可能使用 LDAP、Active Directory 或其他系統。然後，身分經紀人應用程式取得員工的臨時安全憑證。此案例類似於前一個案例 （使用自訂身分驗證系統的行動應用程式），但需要存取 AWS 資源的應用程式全都在公司網路中執行，而且公司有現有的身分驗證系統。

若要取得臨時安全憑證，身分經紀人應用程式將呼叫 `AssumeRole` 或 `GetFederationToken` 以取得臨時安全憑證，具體取決於 Bob 想要如何管理使用者政策以及臨時憑證何時過期。(如需有關這些 API 操作間差異的詳細資訊，請參閱 [IAM 中的暫時安全憑證](id_credentials_temp.md) 和 [臨時安全憑證的許可](id_credentials_temp_control-access.md))。呼叫會傳回暫時性安全登入資料，其中包含 AWS 存取金鑰 ID、私密存取金鑰和工作階段字符。身分經紀人應用程式讓這些臨時安全憑證可供內部公司應用程式使用。然後，應用程式可以使用臨時憑證直接呼叫 AWS 。該應用程式快取憑證，直到過期，然後請求一組新的臨時憑證。下圖說明此情況。

![\[使用自訂身分經紀人應用程式的範例工作流程\]](http://docs.aws.amazon.com/zh_tw/IAM/latest/UserGuide/images/enterprise-authentication-with-identity-broker-application.diagram.png)


此案例具有以下屬性：
+ 身分經紀人應用程式有權存取 IAM 的權杖服務 (STS) API 來建立臨時安全憑證。
+ 身分經紀人應用程式能夠驗證員工是否在現有身分驗證系統中進行了身分驗證。
+ 使用者可以取得臨時 URL，讓他們能夠存取 AWS 管理主控台 （稱為單一登入）。

如需建立臨時安全性憑證檔案的詳細資訊，請參閱 [比較 AWS STS 登入資料](id_credentials_sts-comparison.md)。如需 SAML 聯合身分主體存取 AWS 管理主控台的詳細資訊，請參閱 [啟用 SAML 2.0 聯合主體來存取 AWS 管理主控台](id_roles_providers_enable-console-saml.md)。

# IAM 角色建立
<a name="id_roles_create"></a>

若要建立角色，您可以使用 AWS 管理主控台、 AWS CLI、Tools for Windows PowerShell 或 IAM API。

如果您使用 AWS 管理主控台，精靈會引導您完成建立角色的步驟。精靈的步驟略有不同，具體取決於您是為 AWS 服務、為 建立角色 AWS 帳戶，還是為 SAML 或 OIDC 聯合委託人建立角色。

**IAM 使用者的角色**  
建立此角色，將 或您擁有之其他 中定義的角色的許可委派 AWS 帳戶 給 AWS 帳戶 。一個帳戶中的使用者可以切換為相同或不同帳戶中的角色。使用角色過程中，使用者只能執行角色允許的操作並且只能存取角色允許的資源；其原始使用者許可處於暫停狀態。使用者退出角色時，恢復原始使用者許可。

如需詳細資訊，請參閱[建立角色以將許可授予 IAM 使用者](id_roles_create_for-user.md)。

如需有關建立跨帳戶存取權的角色的詳細資訊，請參閱[使用自訂信任政策建立角色](id_roles_create_for-custom.md)。

**AWS 服務的角色**  
建立此角色，以將許可委派給可以代表您執行動作的服務。您傳遞給服務的[服務角色](id_roles.md#iam-term-service-role)必須具有 IAM 政策，其許可允許服務執行與該服務關聯的動作。每個 AWS 服務需要不同的許可。

如需有關建立服務角色的詳細資訊，請參閱[建立角色以將許可委派給 AWS 服務](id_roles_create_for-service.md)。

如需有關建立服務連結角色的詳細資訊，請參閱[建立服務連結角色](id_roles_create-service-linked-role.md)。

**聯合身分的角色**  
建立此角色，以將許可委派給已在 AWS外部擁有身分的使用者。當您使用 身分提供者時，您不需要建立自訂登入代碼或管理自己的使用者身分，IdP 會為您處理這些工作。您的外部使用者透過 IdP 登入，您可以授予這些外部身分許可，以使用您帳戶中 AWS 的資源。身分提供者可協助保護 AWS 您的帳戶安全，因為您不必在應用程式中分發或嵌入長期安全登入資料，例如存取金鑰。

如需詳細資訊，請參閱[為第三方身分提供者建立角色](id_roles_create_for-idp.md)。

# 建立角色以將許可授予 IAM 使用者
<a name="id_roles_create_for-user"></a>

您可以使用 IAM 角色來提供 AWS 資源的存取權。透過 IAM 角色，您可以在*信任*帳戶和其他 AWS *信任*帳戶之間建立信任關係。信任帳戶擁有要存取的資源，而受信任帳戶包含需要存取資源的使用者。不過，可以讓另一個帳戶在您的帳戶中擁有資源。例如，信任的帳戶可能允許信任的帳戶來建立新的資源，例如在 Amazon S3 儲存貯體中建立新物件。在這種情況下，建立資源的帳戶擁有資源，並控制誰可以存取該資源。

建立信任關係後，來自信任帳戶的 IAM 使用者或應用程式可以使用 AWS Security Token Service (AWS STS) [https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) API 操作。此操作提供臨時安全登入資料，可讓您存取帳戶中 AWS 的資源。

兩個帳戶可都由您控制，或者含有使用者的帳戶可由第三方進行控制。如果使用者的其他帳戶是您無法控制的 AWS 帳戶 ，則您可以使用 `externalId` 屬性。外部 ID 可以是您和第三方帳戶管理員之間商定的任何文字或數字。此選項會自動新增條件到信任政策，讓使用者只在請求包含正確的 `sts:ExternalID` 時才擔任該角色。如需詳細資訊，請參閱[存取第三方 AWS 帳戶 擁有的](id_roles_common-scenarios_third-party.md)。

如需有關如何使用角色委派許可的資訊，請參閱[角色術語和概念](id_roles.md#id_roles_terms-and-concepts)。如需使用服務角色以允許服務存取您帳戶中的資源的資訊，請參閱[建立角色以將許可委派給 AWS 服務](id_roles_create_for-service.md)。

## 建立 IAM 角色 (主控台)
<a name="roles-creatingrole-user-console"></a>

您可以使用 AWS 管理主控台 來建立 IAM 使用者可以擔任的角色。例如，假設您的組織有多個 AWS 帳戶 來隔離開發環境與生產環境。如需有關建立可讓開發帳戶中的使用者存取生產帳戶中資源的角色的高級別資訊，請參閱[使用不同的開發和生產帳戶的範例方案](id_roles_common-scenarios_aws-accounts.md#id_roles_common-scenarios_aws-accounts-example)。

**最低許可**  
若要執行下列步驟，您至少必須擁有下列 IAM 許可：  
`access-analyzer:ValidatePolicy`
`iam:AttachRolePolicy`
`iam:CreatePolicy`
`iam:CreateRole`
`iam:GetAccountSummary`
`iam:GetPolicy`
`iam:GetPolicyVersion`
`iam:GetRole`
`iam:ListAccountAliases`
`iam:ListAttachedRolePolicies`
`iam:ListOpenIDConnectProviders`
`iam:ListPolicies`
`iam:ListRolePolicies`
`iam:ListRoles`
`iam:ListRoleTags`
`iam:ListSAMLProviders`

------
#### [ Console ]

1. 登入 AWS 管理主控台 ，並在 https：//[https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/) 開啟 IAM 主控台。

1. 在主控台的導覽窗格中，選擇 **Roles (角色)**，然後選擇 **Create role (建立角色)**。

1. 選擇 **AWS 帳戶** 角色類型。

1. 若要為您的帳戶建立角色，請選取 **This account** (此帳號)。若要為其他帳戶建立角色，請選擇 **Another AWS 帳戶** (另一個 )，然後輸入您要對其授予資源存取權的 **Account ID** (帳戶 ID)。

   指定帳戶的管理員可以授予許可給該帳戶中的任何 IAM 使用者來擔任此角色。若要執行此操作，管理員要將政策連接到授予 `sts:AssumeRole` 動作之許可的使用者或群組。該政策必須指定角色的 ARN 為 `Resource`。

1. 如果您將許可授予您不控制之帳戶的使用者，而且使用者將以程式設計方式擔任此角色，則請選取 **Require external ID** (需要外部 ID)。外部 ID 可以是您和第三方帳戶管理員之間商定的任何文字或數字。此選項會自動新增條件到信任政策，讓使用者只在請求包含正確的 `sts:ExternalID` 時才擔任該角色。如需詳細資訊，請參閱[存取第三方 AWS 帳戶 擁有的](id_roles_common-scenarios_third-party.md)。
**重要**  
選擇此選項只會透過 AWS CLI、Tools for Windows PowerShell 或 AWS API 來限制對角色的存取。這是因為您無法使用 AWS 主控台切換到在其信任政策中具有 `externalId`條件的角色。不過，您可以程式設計方式建立存取這類存取，即透過編寫指令碼或使用相關開發套件的應用程式。如需詳細資訊和範例指令碼，請參閱 AWS 安全部落格中的[如何啟用跨帳戶存取 AWS 管理主控台](https://aws.amazon.com/blogs/security/how-to-enable-cross-account-access-to-the-aws-management-console)。

1. 如果您想限制角色為使用多重要素驗證 (MFA) 登入的使用者，請選取 **Require MFA (需要 MFA)**。這會新增條件到角色的信任政策，以檢查 MFA 登入。想要擔任該角色的使用者必須從設定的 MFA 裝置使用臨時的一次性密碼登入。未經 MFA 身分驗證的使用者無法擔任角色。如需有關 MFA 的詳細資訊，請參閱 [AWS IAM 中的多重要素驗證](id_credentials_mfa.md)

1. 選擇**下一步**。

1. IAM 包含您帳戶中 AWS 受管和客戶受管政策的清單。選取用於許可政策的政策，或者選擇 **Create policy (建立政策)** 以開啟新的瀏覽器標籤，並從頭建立新的政策。如需詳細資訊，請參閱[建立 IAM 政策](access_policies_create-console.md#access_policies_create-start)。在您建立政策後，關閉該標籤並返回您的原始標籤。選取您希望擔任角色的任何人具有的許可政策旁的核取方塊。如果您希望，您目前可以不選取政策，稍後再將政策連接到角色。角色預設沒有任何許可。

1. (選用) 設定[許可界限](access_policies_boundaries.md)。這是進階功能。

   開啟 **Set permissions boundary (設定許可界限)** 區段，並選擇 **Use a permissions boundary to control the maximum role permissions (使用許可界限來控制角色許可上限)**。選取用於許可界限的政策。

1. 選擇**下一步**。

1. 針對 **Role name (角色名稱)**，輸入您的角色名稱。角色名稱在您的 中必須是唯一的 AWS 帳戶。角色名稱用在政策中或作為 ARN 的一部分時，角色名稱區分大小寫。當主控台中的客戶顯示角色名稱時 (例如在登入程序期間)，角色名稱不區分大小寫。因為有各種實體可能會參考此角色，所以建立角色之後，您就無法編輯其名稱。

1. (選用) 在 **Description** (說明) 中，輸入新角色的說明。

1. 在 **Step 1: Select trusted entities** (步驟 1：選取受信任的實體) 或者 **Step 2: Add permissions** (步驟 2：新增許可) 區段中選擇 **Edit** (編輯)，可編輯使用案例和角色許可。您將會返回先前的頁面進行編輯。

1. (選用) 藉由連接標籤作為鍵值對，將中繼資料新增至角色。如需有關在 IAM 中使用標籤的詳細資訊，請參閱 [AWS Identity and Access Management 資源的標籤](id_tags.md)。

1. 檢閱角色，然後選擇 **Create role** (建立角色)。
**重要**  
請記住，這只是所需設定的前半部。您也必須以信任的帳戶許可提供給個別使用者，以切換到主控台中的角色，或程式化方式擔任角色。如需有關此步驟的詳細資訊，請參閱 [向使用者授予切換角色的許可](id_roles_use_permissions-to-switch.md)。

------

## 建立 IAM 角色 (AWS CLI)
<a name="roles-creatingrole-user-cli"></a>

從 建立角色 AWS CLI 涉及多個步驟。當您使用 主控台建立角色時，會為您完成許多步驟，但您必須使用 自行 AWS CLI 明確執行每個步驟。您必須建立角色，然後為該角色指派許可政策。或者，您也可以設定角色的[許可界限](access_policies_boundaries.md)。

**若要為跨帳戶存取建立角色 (AWS CLI)**

1. 建立角色：[aws iam create-role](https://docs.aws.amazon.com/cli/latest/reference/iam/create-role.html)

1. 將受管許可政策連接到角色：[aws iam attach-role-policy](https://docs.aws.amazon.com/cli/latest/reference/iam/attach-role-policy.html)

    或

   為角色建立內嵌許可政策：[aws iam put-role-policy](https://docs.aws.amazon.com/cli/latest/reference/iam/put-role-policy.html)

1. (選用) 透過連接標籤來將自訂屬性新增至該角色：[aws iam tag-role](https://docs.aws.amazon.com/cli/latest/reference/iam/tag-role.html)

   如需詳細資訊，請參閱 [管理 IAM 角色 (AWS CLI 或 AWS API) 上的標籤](id_tags_roles.md#id_tags_roles_procs-cli-api)。

1. (選用) 設定角色的[許可界限](access_policies_boundaries.md)：[aws iam put-role-permissions-boundary](https://docs.aws.amazon.com/cli/latest/reference/iam/put-role-permissions-boundary.html)

   許可界限控制角色可以擁有的許可上限。許可界限是一項進階 AWS 功能。

以下範例顯示前兩個最常見步驟，可在簡單的環境中建立一個跨帳戶角色。此範例允許 `123456789012` 帳戶中的任何使用者擔任角色，並檢視 `example_bucket` Amazon S3 儲存貯體。此範例也假定您使用執行 Windows 的用戶端電腦，並且已使用您的帳戶憑證和區域設定您的命令列界面。如需詳細資訊，請參閱[設定 AWS 命令列界面](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html)。

當您建立角色時，這個範例在第一個命令包含下列信任政策。此信任政策允許 `123456789012` 帳戶中的使用者使用 `AssumeRole` 操作來擔任角色，但只在使用者採用 `SerialNumber` 和 `TokenCode` 參數以提供 MFA 身分驗證時。如需有關 MFA 的詳細資訊，請參閱 [AWS IAM 中的多重要素驗證](id_credentials_mfa.md)。

------
#### [ JSON ]

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
      {
          "Effect": "Allow",
          "Principal": { "AWS": "arn:aws:iam::123456789012:root" },
          "Action": "sts:AssumeRole",
          "Condition": { "Bool": { "aws:MultiFactorAuthPresent": "true" } }
      }
  ]
}
```

------

**重要**  
如果您的 `Principal` 元素包含特定 IAM 角色或使用者的 ARN，則該 ARN 會在儲存政策時轉換為唯一的主體 ID。如果有人希望藉由刪除並重新建立角色或使用者來提升許可時，這麼做可有助於減少此類風險。您通常不會在主控台中看到此 ID，因為在顯示信任政策時還會反向轉換回 ARN。不過，如果您刪除角色或使用者，則主體 ID 會顯示在主控台中，因為 AWS 無法再將其對應回 ARN。因此，如果您刪除並重新建立了信任政策的 `Principal` 元素所引用的使用者或角色，您必須編輯角色來替換 ARN。

當您使用第二個命令的政策，您必須將現有受管政策連接到角色。下列許可政策允許任何擔任角色的人只對 `example_bucket` Amazon S3 儲存貯體執行 `ListBucket` 動作。

------
#### [ JSON ]

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
      {
          "Effect": "Allow",
          "Action": "s3:ListBucket",
          "Resource": "arn:aws:s3:::example_bucket"
      }
  ]
}
```

------

若要建立此 `Test-UserAccess-Role` 角色，您必須先將之前的信任政策以名稱 `trustpolicyforacct123456789012.json` 儲存到 `policies` 資料夾 (在您的本機 `C:` 磁碟機)。然後將先前的許可政策儲存為 中的客戶受管政策 AWS 帳戶 ，名稱為 `PolicyForRole`。然後，您可以使用以下命令來建立角色，並連接受管政策。

```
# Create the role and attach the trust policy file that allows users in the specified account to assume the role.
$ aws iam create-role --role-name Test-UserAccess-Role --assume-role-policy-document file://C:\policies\trustpolicyforacct123456789012.json

# Attach the permissions policy (in this example a managed policy) to the role to specify what it is allowed to do.
$ aws iam attach-role-policy --role-name Test-UserAccess-Role --policy-arn arn:aws:iam::123456789012:policy/PolicyForRole
```

**重要**  
請記住，這只是所需設定的前半部。您還必須提供受信任帳戶中的個別使用者許可，以切換到該角色。如需有關此步驟的詳細資訊，請參閱 [向使用者授予切換角色的許可](id_roles_use_permissions-to-switch.md)。

在您建立角色並授予其執行 AWS 任務或存取 AWS 資源的許可後，`123456789012`帳戶中的任何使用者都可以擔任該角色。如需詳細資訊，請參閱[切換到 IAM 角色 (AWS CLI)](id_roles_use_switch-role-cli.md)。

## 建立 IAM 角色 (AWS API)
<a name="roles-creatingrole-user-api"></a>

從 AWS API 建立角色涉及多個步驟。當您使用主控台建立角色時，有許多步驟會自動為您完成，但是使用 API 的話，您必須自行明確執行每個步驟。您必須建立角色，然後為該角色指派許可政策。或者，您也可以設定角色的[許可界限](access_policies_boundaries.md)。

**在程式碼中建立角色 (AWS API)**

1. 建立角色：[CreateRole](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateRole.html)

   對於角色的信任政策，您可以指定一個檔案位置。

1. 將受管許可政策連接到角色：[AttachRolePolicy](https://docs.aws.amazon.com/IAM/latest/APIReference/API_AttachRolePolicy.html)

   或

   為角色建立內嵌許可政策：[PutRolePolicy](https://docs.aws.amazon.com/IAM/latest/APIReference/API_PutRolePolicy.html)
**重要**  
請記住，這只是所需設定的前半部。您還必須提供受信任帳戶中的個別使用者許可，以切換到該角色。如需有關此步驟的詳細資訊，請參閱 [向使用者授予切換角色的許可](id_roles_use_permissions-to-switch.md)。

1. (選用) 藉由連接標籤將自訂屬性新增至使用者：[TagRole](https://docs.aws.amazon.com/IAM/latest/APIReference/API_TagRole.html)

   如需詳細資訊，請參閱 [管理 IAM 使用者 (AWS CLI 或 AWS API) 上的標籤](id_tags_users.md#id_tags_users_procs-cli-api)。

1. (選用) 設定角色的[許可界限](access_policies_boundaries.md)：[PutRolePermissionsBoundary](https://docs.aws.amazon.com/IAM/latest/APIReference/API_PutRolePermissionsBoundary.html)

   許可界限控制角色可以擁有的許可上限。許可界限是一項進階 AWS 功能。

在您建立角色並授予其執行 AWS 任務或存取 AWS 資源的許可後，您必須將許可授予帳戶中的使用者，以允許他們擔任該角色。如需有關擔任角色的詳細資訊，請參閱 [切換到 IAM 角色 (AWS API)](id_roles_use_switch-role-api.md)。

## 建立 IAM 角色 (AWS CloudFormation)
<a name="roles_creatingrole-user-cloudformation"></a>

如需有關在 中建立 IAM 角色的資訊 AWS CloudFormation，請參閱*AWS CloudFormation 《 使用者指南*》中的[資源和屬性參考](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-role.html)和[範例](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-role.html#aws-resource-iam-role--examples)。

如需 IAM 範本的詳細資訊 AWS CloudFormation，請參閱《 *AWS CloudFormation 使用者指南*》中的[AWS Identity and Access Management 範本程式碼片段](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/quickref-iam.html)。

# 建立角色以將許可委派給 AWS 服務
<a name="id_roles_create_for-service"></a>

許多 AWS 服務要求您使用 角色，以允許服務代表您存取其他 服務中的資源。服務會擔任代您執行動作的角色稱為[服務角色](id_roles.md#iam-term-service-role)。當角色做為服務的專業用途時，它歸類為[服務連結角色](id_roles.md#iam-term-service-linked-role)。若要查看使用服務連結的角色支援哪些服務，或者服務是否支援任何形式的臨時憑證的詳細資訊，請參閱 [AWS 使用 IAM 的 服務](reference_aws-services-that-work-with-iam.md)。若要了解個別服務如何使用角色，請在表格中選擇服務名稱以查看該服務的文件。

設定 `PassRole` 許可時，您應確保使用者傳遞的角色不會具有比您希望使用者具有之許可更多的許可。例如，可能不允許 Alice 執行任何 Amazon S3 動作。如果 Alice 可以將角色傳遞給允許 Amazon S3 動作的服務，則該服務可以在執行任務時代表 Alice 執行 Amazon S3 動作。

如需有關角色如何協助您委派許可的詳細資訊，請參閱 [角色術語和概念](id_roles.md#id_roles_terms-and-concepts)。

## 服務角色許可
<a name="id_roles_create_service-permissions"></a>

您必須設定許可，允許 IAM 實體 (使用者或角色) 建立或編輯服務角色。

**注意**  
服務連結角色的 ARN 包括服務主體，這在下列政策中以 `SERVICE-NAME.amazonaws.com` 形式指出。不要嘗試猜測服務主體，因為它是區分大小寫，且格式可以因各 AWS 服務而異。若要檢視服務的服務主體，請參閱該服務連結的角色文件。

**允許 IAM 實體建立特定服務角色**

將下列政策新增至需要建立服務角色的 IAM 實體。此政策可讓您建立所指定服務且具有特定名稱的服務角色。然後，您可以將受管或內嵌政策連接至該角色。

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iam:AttachRolePolicy",
                "iam:CreateRole",
                "iam:PutRolePolicy"
            ],
            "Resource": "arn:aws:iam::*:role/SERVICE-ROLE-NAME"
        }
    ]
}
```

------

**允許 IAM 實體建立任何服務角色**

AWS 建議您只允許管理使用者建立任何服務角色。具有建立角色和連接任何政策之許可的人員可以提升自己的許可。反之，建立一個政策，讓他們只建立所需的角色，或讓系統管理員代表他們建立服務角色。

若要連接允許管理員存取整個 的政策 AWS 帳戶，請使用 [AdministratorAccess](https://console.aws.amazon.com/iam/home#policies/arn:aws:iam::aws:policy/AdministratorAccess) AWS 受管政策。

**允許 IAM 實體編輯服務角色**

將下列政策新增至需要編輯服務角色的 IAM 實體。

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "EditSpecificServiceRole",
            "Effect": "Allow",
            "Action": [
                "iam:AttachRolePolicy",
                "iam:DeleteRolePolicy",
                "iam:DetachRolePolicy",
                "iam:GetRole",
                "iam:GetRolePolicy",
                "iam:ListAttachedRolePolicies",
                "iam:ListRolePolicies",
                "iam:PutRolePolicy",
                "iam:UpdateRole",
                "iam:UpdateRoleDescription"
            ],
            "Resource": "arn:aws:iam::*:role/SERVICE-ROLE-NAME"
        },
        {
            "Sid": "ViewRolesAndPolicies",
            "Effect": "Allow",
            "Action": [
                "iam:GetPolicy",
                "iam:ListRoles"
            ],
            "Resource": "*"
        }
    ]
}
```

------

**允許 IAM 實體刪除特定服務角色**

將下列陳述式新增至需要刪除所指定服務角色之 IAM 實體的許可政策。

```
{
    "Effect": "Allow",
    "Action": "iam:DeleteRole",
    "Resource": "arn:aws:iam::*:role/SERVICE-ROLE-NAME"
}
```

**允許 IAM 實體刪除任何服務角色**

AWS 建議您只允許管理使用者刪除任何服務角色。反之，建立一個政策，只允許他們刪除所需的角色，或讓系統管理員代表他們刪除服務角色。

若要連接允許管理員存取整個 的政策 AWS 帳戶，請使用 [AdministratorAccess](https://console.aws.amazon.com/iam/home#policies/arn:aws:iam::aws:policy/AdministratorAccess) AWS 受管政策。

## 為 AWS 服務建立角色 （主控台）
<a name="roles-creatingrole-service-console"></a>

您可以使用 AWS 管理主控台 來建立 服務的角色。因為有些服務支援多個服務角色，所以請參閱服務的 [AWS 文件](https://docs.aws.amazon.com/)，以查看要選擇的使用案例。您可以了解如何為角色指派必要的信任和許可政策，以便服務可以代表您擔任角色。您用來控制角色的許可的步驟可能有所不同，端視服務如何定義使用案例，以及是否建立服務連結的角色而定。

------
#### [ Console ]

**為 AWS 服務 (IAM 主控台） 建立角色**

1. 登入 AWS 管理主控台 ，並在 https：//[https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/) 開啟 IAM 主控台。

1. 在 IAM 主控台的導覽窗格中，選擇**角色**，然後選擇**建立角色**。

1. 對於 **Trusted entity type** (信任的實體類型)，請選擇 **AWS 服務**。

1. 針對**服務或使用案例**，選擇服務，然後選擇使用案例。服務會定義使用案例，以包含服務所需的信任政策。

1. 選擇**下一步**。

1. 對於**許可政策**，選項取決於您選取的使用案例：
   + 如果服務定義了角色的許可，則您無法選取許可政策。
   + 從一組有限的許可政策中選取。
   + 從所有許可政策中選取。
   + 選取無許可政策，在建立角色之後建立政策，然後將政策連接到角色。

1. (選用) 設定[許可界限](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html)。這是進階功能，可用於服務角色，而不是服務連結的角色。

   1. 開啟**設定許可界限**區段，然後選擇**使用許可界限來控制角色許可上限**。

      IAM 包含您帳戶中 AWS 受管和客戶受管政策的清單。

   1. 選取用於許可界限的政策。

1. 選擇**下一步**。

1. 對於**角色名稱**，選項取決於服務：
   + 如果服務定義了角色名稱，則無法編輯角色名稱。
   + 如果服務定義了角色名稱的字首，則可以輸入選用字尾。
   + 如果服務未定義角色名稱，則可以為角色命名。
**重要**  
當您命名角色時，請注意下列事項：  
角色名稱在您的 中必須是唯一的 AWS 帳戶，而且無法依大小寫設為唯一。  
例如，不要同時建立名為 **PRODROLE** 和 **prodrole** 的角色。當角色名稱用於政策或 ARN 的一部分時，角色名稱會區分大小寫，但是當角色名稱在主控台中顯示給客戶時，例如在登入過程中，角色名稱不會區分大小寫。
因為其他實體可能會參考角色，所以在建立角色之後，就無法編輯其名稱。

1. (選用) 在**說明**中，輸入角色的說明。

1. (選用) 若要編輯使用案例和角色許可，請在**步驟 1：選取受信任的實體**或者**步驟 2：新增許可**區段中選擇**編輯**。

1. (選用) 若要協助識別、組織或搜尋角色，請將標籤新增為索引鍵值對。如需在 IAM 中使用標籤的詳細資訊，請參閱《*IAM 使用者指南*》中的[AWS Identity and Access Management 資源的標籤](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html)。

1. 檢閱角色，然後選擇 **Create role** (建立角色)。

------

## 為服務建立角色 (AWS CLI)
<a name="roles-creatingrole-service-cli"></a>

從 建立角色 AWS CLI 涉及多個步驟。當您使用 主控台建立角色時，會為您完成許多步驟，但您必須使用 自行 AWS CLI 明確執行每個步驟。您必須建立角色，然後為該角色指派許可政策。如果您使用的服務是 Amazon EC2，則還必須建立執行個體描述檔並新增該角色。或者，您也可以設定角色的[許可界限](access_policies_boundaries.md)。

**從 建立 AWS 服務的角色 AWS CLI**

1. 以下 `[create-role](https://docs.aws.amazon.com/cli/latest/reference/iam/create-role.html)` 命令會建立名為 *Test-Role* 的角色，並將信任政策連接至該角色：

   `aws iam create-role --role-name Test-Role --assume-role-policy-document file://Test-Role-Trust-Policy.json`

1. 將受管許可政策連接到角色：[aws iam attach-role-policy](https://docs.aws.amazon.com/cli/latest/reference/iam/attach-role-policy.html)

   例如，下列 `attach-role-policy` 命令會將名為 `ReadOnlyAccess` 的 AWS 受管政策連接至名為 `ReadOnlyRole` 的 IAM 角色：

   `aws iam attach-role-policy --policy-arn arn:aws:iam::aws:policy/ReadOnlyAccess --role-name ReadOnlyRole`

    或

   為角色建立內嵌許可政策：[aws iam put-role-policy](https://docs.aws.amazon.com/cli/latest/reference/iam/put-role-policy.html)

   若要新增嵌許可政策，請參閱以下範例：

    `aws iam put-role-policy --role-name Test-Role --policy-name ExamplePolicy --policy-document file://AdminPolicy.json`

1. (選用) 透過連接標籤來將自訂屬性新增至該角色：[aws iam tag-role](https://docs.aws.amazon.com/cli/latest/reference/iam/tag-role.html)

   如需詳細資訊，請參閱 [管理 IAM 角色 (AWS CLI 或 AWS API) 上的標籤](id_tags_roles.md#id_tags_roles_procs-cli-api)。

1. (選用) 設定角色的[許可界限](access_policies_boundaries.md)：[aws iam put-role-permissions-boundary](https://docs.aws.amazon.com/cli/latest/reference/iam/put-role-permissions-boundary.html)

   許可界限控制角色可以擁有的許可上限。許可界限是一項進階 AWS 功能。

如果您要將角色與 Amazon EC2 或其他使用 Amazon EC2 AWS 的服務搭配使用，則必須將角色存放在執行個體描述檔中。執行個體描述檔是角色的容器，可以在啟動時連接到 Amazon EC2 執行個體。執行個體設定檔只能包含一個角色，並且無法增加該限制。如果您使用 建立角色 AWS 管理主控台，則會使用與角色相同的名稱為您建立執行個體描述檔。如需有關執行個體描述檔的詳細資訊，請參閱 [使用執行個體設定檔](id_roles_use_switch-role-ec2_instance-profiles.md)。如需有關如何使用角色啟動 EC2 執行個體的資訊，請參閱《Amazon EC2 使用者指南》**中的[控制對 Amazon EC2 資源的存取](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/UsingIAM.html#UsingIAMrolesWithAmazonEC2Instances)。

**建立執行個體設定檔並將角色存放在其中 (AWS CLI)**

1. 建立執行個體描述檔：[aws iam create-instance-profile](https://docs.aws.amazon.com/cli/latest/reference/iam/create-instance-profile.html)

1. 將角色新增至執行個體描述檔：[aws iam add-role-to-instance-profile](https://docs.aws.amazon.com/cli/latest/reference/iam/add-role-to-instance-profile.html)

以下 AWS CLI 範例命令集示範建立角色和連接許可的前兩個步驟。它還說明兩個建立執行個體設定檔和新增角色至描述檔的步驟。此範例信任允許 Amazon EC2 服務擔任角色並檢視 `example_bucket` Amazon S3 儲存貯體的政策。此範例也假定您在執行 Windows 的用戶端電腦上執行，並且已使用您的帳戶憑證和區域設定您的命令列界面。如需詳細資訊，請參閱[設定 AWS 命令列界面](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html)。

當您建立角色時，這個範例在第一個命令包含下列信任政策。此信任政策允許 Amazon EC2 服務擔任該角色。

------
#### [ JSON ]

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": {
    "Effect": "Allow",
    "Principal": {"Service": "ec2.amazonaws.com"},
    "Action": "sts:AssumeRole"
  }
}
```

------

當您使用第二個命令的政策，您必須將許可政策連接到角色。以下範例許可政策允許角色僅在 `example_bucket` Amazon S3 儲存貯體上執行 `ListBucket` 動作。

------
#### [ JSON ]

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": {
    "Effect": "Allow",
    "Action": "s3:ListBucket",
    "Resource": "arn:aws:s3:::example_bucket"
  }
}
```

------

若要建立此 `Test-Role-for-EC2` 角色，您必須先將之前的信任政策以名稱 `trustpolicyforec2.json` 和之前名為 `permissionspolicyforec2.json` 的許可政策儲存到您本機 `policies` 磁碟機的 `C:` 目錄。然後，您可以使用以下命令來建立角色、連接政策、建立執行個體設定檔，並新增角色到執行個體設定檔。

```
# Create the role and attach the trust policy that allows EC2 to assume this role.
$ aws iam create-role --role-name Test-Role-for-EC2 --assume-role-policy-document file://C:\policies\trustpolicyforec2.json

# Embed the permissions policy (in this example an inline policy) to the role to specify what it is allowed to do.
$ aws iam put-role-policy --role-name Test-Role-for-EC2 --policy-name Permissions-Policy-For-Ec2 --policy-document file://C:\policies\permissionspolicyforec2.json

# Create the instance profile required by EC2 to contain the role
$ aws iam create-instance-profile --instance-profile-name EC2-ListBucket-S3

# Finally, add the role to the instance profile
$ aws iam add-role-to-instance-profile --instance-profile-name EC2-ListBucket-S3 --role-name Test-Role-for-EC2
```

當您啟動 EC2 執行個體時，如果您使用 AWS 主控台，請在**設定執行個體詳細資訊頁面中指定執行個體**描述檔名稱。如果您使用 `aws ec2 run-instances` CLI 命令，指定 `--iam-instance-profile` 參數。

## 為服務建立角色 (AWS API)
<a name="roles-creatingrole-service-api"></a>

從 AWS API 建立角色涉及多個步驟。當您使用主控台建立角色時，有許多步驟會自動為您完成，但是使用 API 的話，您必須自行明確執行每個步驟。您必須建立角色，然後為該角色指派許可政策。如果您使用的服務是 Amazon EC2，則還必須建立執行個體描述檔並新增該角色。或者，您也可以設定角色的[許可界限](access_policies_boundaries.md)。

**為 AWS 服務建立角色 (AWS API)**

1. 建立角色：[CreateRole](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateRole.html)

   對於角色的信任政策，您可以指定一個檔案位置。

1. 將受管許可政策連接到角色：[AttachRolePolicy](https://docs.aws.amazon.com/IAM/latest/APIReference/API_AttachRolePolicy.html)

    或

   為角色建立內嵌許可政策：[PutRolePolicy](https://docs.aws.amazon.com/IAM/latest/APIReference/API_PutRolePolicy.html)

1. (選用) 藉由連接標籤將自訂屬性新增至使用者：[TagRole](https://docs.aws.amazon.com/IAM/latest/APIReference/API_TagRole.html)

   如需詳細資訊，請參閱 [管理 IAM 使用者 (AWS CLI 或 AWS API) 上的標籤](id_tags_users.md#id_tags_users_procs-cli-api)。

1. (選用) 設定角色的[許可界限](access_policies_boundaries.md)：[PutRolePermissionsBoundary](https://docs.aws.amazon.com/IAM/latest/APIReference/API_PutRolePermissionsBoundary.html)

   許可界限控制角色可以擁有的許可上限。許可界限是一項進階 AWS 功能。

如果您要將角色與 Amazon EC2 或其他使用 Amazon EC2 AWS 的服務搭配使用，則必須將角色存放在執行個體描述檔中。執行個體設定檔是角色的容器。每個執行個體設定檔只能包含一個角色，並且無法增加該限制。如果您在 中建立角色 AWS 管理主控台，則會使用與角色相同的名稱為您建立執行個體描述檔。如需有關執行個體描述檔的詳細資訊，請參閱 [使用執行個體設定檔](id_roles_use_switch-role-ec2_instance-profiles.md)。如需有關如何使用角色啟動 Amazon EC2 執行個體的資訊，請參閱《Amazon EC2 使用者指南》**中的[控制對 Amazon EC2 資源的存取](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/UsingIAM.html#UsingIAMrolesWithAmazonEC2Instances)。

**建立執行個體描述檔並將角色存放在其中 (AWS API)**

1. 建立執行個體描述檔：[CreateInstanceProfile](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateInstanceProfile.html)

1. 將角色新增至執行個體描述檔：[AddRoleToInstanceProfile](https://docs.aws.amazon.com/IAM/latest/APIReference/API_AddRoleToInstanceProfile.html)

# 建立服務連結角色
<a name="id_roles_create-service-linked-role"></a>

服務連結角色是一種獨特的 IAM 角色類型，可直接連結到 AWS 服務。服務連結角色是由服務預先定義，並包含服務代表您呼叫其他 AWS 服務所需的所有許可。連結的服務也定義您如何建立、修改和刪除服務連結的角色。服務可能會自動建立或刪除角色。做為服務中精靈或程序一部分，它也許可讓您建立、修改或刪除角色。或者，它可能要求您使用 IAM 來建立或刪除角色。不論採用何種方式，服務連結角色可簡化設定服務流程，因為您不必手動新增服務許可，以代表您完成動作。

**注意**  
請記得，服務角色與服務連結角色不同。服務角色是服務擔任的 [IAM 角色](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html)，可代您執行動作。IAM 管理員可以從 IAM 內建立、修改和刪除服務角色。如需詳細資訊，請參閱《*IAM 使用者指南*》中的[建立角色以委派許可給 AWS 服務](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-service.html)。服務連結角色是連結至 的一種服務角色 AWS 服務。服務可以擔任代表您執行動作的角色。服務連結角色會出現在您的 中 AWS 帳戶 ，並由服務擁有。IAM 管理員可以檢視，但不能編輯服務連結角色的許可。

連結的服務定義其服務連結角色的許可，除非另有定義，否則僅有該服務可以擔任其角色。定義的許可包括信任政策和許可政策，且該許可政策無法附加至其他 IAM 實體。

在您刪除角色之前，您必須首先刪除它們的相關資源。這有助於防止不小心移除資源存取許可。

**提示**  
如需哪些服務支援使用服務連結角色的資訊，請參閱 [AWS 使用 IAM 的 服務](reference_aws-services-that-work-with-iam.md)，並尋找 **Service-Linked Role (服務連結角色)** 欄中顯示 **Yes (是)** 的服務。選擇具有連結的 **Yes (是)**，以檢視該服務的服務連結角色文件。

## 服務連結角色許可
<a name="service-linked-role-permissions"></a>

您必須設定 IAM 實體 (使用者或角色) 的許可，允許使用者或角色建立或編輯服務連結角色。

**注意**  
服務連結角色的 ARN 包括服務主體，這在下列政策中以 `SERVICE-NAME.amazonaws.com` 形式指出。請勿嘗試猜測服務委託人，因為它區分大小寫，而且格式可能因 AWS 服務而異。若要檢視服務的服務主體，請參閱該服務連結的角色文件。

**允許 IAM 實體建立特定服務連結角色**

將下列政策新增至需要建立服務連結角色的 IAM 實體。

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "iam:CreateServiceLinkedRole",
            "Resource": "arn:aws:iam::*:role/aws-service-role/SERVICE-NAME.amazonaws.com/SERVICE-LINKED-ROLE-NAME-PREFIX*",
            "Condition": {"StringLike": {"iam:AWSServiceName": "SERVICE-NAME.amazonaws.com"}}
        },
        {
            "Effect": "Allow",
            "Action": [
                "iam:AttachRolePolicy",
                "iam:PutRolePolicy"
            ],
            "Resource": "arn:aws:iam::*:role/aws-service-role/SERVICE-NAME.amazonaws.com/SERVICE-LINKED-ROLE-NAME-PREFIX*"
        }
    ]
}
```

------

**若要允許 IAM 實體建立任何服務連結角色**

將下列陳述式新增至需要建立服務連結角色的 IAM 實體的許可政策，或包含所需政策的任何服務角色。此政策陳述式不允許 IAM 實體連接政策到角色。

```
{
    "Effect": "Allow",
    "Action": "iam:CreateServiceLinkedRole",
    "Resource": "arn:aws:iam::*:role/aws-service-role/*"
}
```

**若要允許 IAM 實體編輯任何服務連結角色的說明**

將下列陳述式新增至需要編輯服務連結角色說明或任何服務角色的 IAM 實體的許可政策。

```
{
    "Effect": "Allow",
    "Action": "iam:UpdateRoleDescription",
    "Resource": "arn:aws:iam::*:role/aws-service-role/*"
}
```

**若要允許 IAM 實體刪除特定服務連結角色**

將下列陳述式新增至需要刪除服務連結角色的 IAM 實體的許可政策。

```
{
    "Effect": "Allow",
    "Action": [
        "iam:DeleteServiceLinkedRole",
        "iam:GetServiceLinkedRoleDeletionStatus"
    ],
    "Resource": "arn:aws:iam::*:role/aws-service-role/SERVICE-NAME.amazonaws.com/SERVICE-LINKED-ROLE-NAME-PREFIX*"
}
```

**允許 IAM 實體刪除任何服務連結角色**

將下列陳述式新增至需要刪除服務連結角色 (但並非服務角色) 的 IAM 實體許可政策。

```
{
    "Effect": "Allow",
    "Action": [
        "iam:DeleteServiceLinkedRole",
        "iam:GetServiceLinkedRoleDeletionStatus"
    ],
    "Resource": "arn:aws:iam::*:role/aws-service-role/*"
}
```

**允許 IAM 實體將現有角色傳遞到服務**

有些 AWS 服務可讓您將現有角色傳遞給服務，而不是建立新的服務連結角色。若要執行此操作，使用者必須擁有*傳遞角色*給服務的許可。在需要傳遞角色之 IAM 實體的許可政策中，新增下列陳述式。透過這個政策陳述式，實體也可以檢視角色清單，並從中選擇要傳遞的角色。如需詳細資訊，請參閱[授予使用者將角色傳遞至 AWS 服務的許可](id_roles_use_passrole.md)。

```
{
  "Sid": "PolicyStatementToAllowUserToListRoles",
  "Effect": "Allow",
  "Action": ["iam:ListRoles"],
  "Resource": "*"
},
{
  "Sid": "PolicyStatementToAllowUserToPassOneSpecificRole",
  "Effect": "Allow",
  "Action": [ "iam:PassRole" ],
  "Resource": "arn:aws:iam::account-id:role/my-role-for-XYZ"
}
```

## 具有服務連結角色的間接許可
<a name="create-service-linked-role-permissions-transfer"></a>

可將服務連結角色授予的許可間接轉移給其他使用者和角色。當 AWS 服務使用服務連結角色時，該服務連結角色可以使用自己的許可來呼叫其他 AWS 服務。這表示使用者和角色 (具有呼叫使用服務連結角色之服務的許可) 可能會間接存取該服務連結角色所能存取的服務。

例如，當您建立 Amazon RDS 資料庫執行個體時，[RDS 的服務連結角色](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAM.ServiceLinkedRoles.html)如果尚未存在，則會自動建立。此服務連結角色可讓 RDS 代您呼叫 Amazon EC2、Amazon SNS、Amazon SNS、Amazon CloudWatch Logs 和 Amazon Kinesis。如果您允許帳戶中的使用者和角色修改或建立 RDS 資料庫，則他們可能可以透過呼叫 RDS 的方式，與 Amazon EC2、Amazon SNS、Amazon CloudWatch Logs 日誌和 Amazon Kinesis 資源間接互動，因為 RDS 會使用其服務連結角色存取這些資源。

### 服務連結角色建立方法
<a name="create-service-linked-role"></a>

您用來建立服務連結角色的方法取決於服務。在某些情況下，您不需要手動建立一個服務連結角色。例如，當您在服務中完成特定動作 (例如建立資源)，該服務可能會為您建立服務連結角色。或者，您若在服務開始支援服務連結角色之前已在使用該服務，則服務可能已在您的帳戶中自動建立角色。如需進一步了解，請參閱 [我的 AWS 帳戶中出現新角色](troubleshoot_roles.md#troubleshoot_roles_new-role-appeared)。

在其他情況下，服務可能支援使用服務主控台、API 或 CLI 手動建立服務連結角色。如需哪些服務支援使用服務連結角色的資訊，請參閱 [AWS 使用 IAM 的 服務](reference_aws-services-that-work-with-iam.md)，並尋找 **Service-Linked Role (服務連結角色)** 欄中顯示 **Yes (是)** 的服務。若要了解服務是否支援建立服務連結角色，請選擇**是**連結以檢視該服務的服務連結角色的文件。

如果服務不支援建立角色，則可以使用 IAM 來建立服務連結角色。

**重要**  
服務連結角色算作您的 [AWS 帳戶中的 IAM 角色](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html#reference_iam-quotas-entities)限制，但是如果您已達到限制，仍然可以在您的帳戶中建立服務連結角色。只有服務連結角色可以超過限制。

### 建立服務連結角色 (主控台)
<a name="create-service-linked-role-iam-console"></a>

在 IAM 中建立服務連結角色之前，了解連結的服務是否自動建立服務連結角色，此外，了解是否您可以從服務主控台、API 或 CLI 建立角色。<a name="create-service-linked-role-iam-console"></a>

**建立服務連結角色 (主控台)**

1. 登入 AWS 管理主控台 並開啟位於 https：//[https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/) 的 IAM 主控台。

1. 在 IAM 主控台的導覽窗格中，選擇**角色**。然後，選擇 **Create role** (建立角色)。

1. 選擇 **AWS Service** (服務) 角色類型。

1. 選擇服務的使用案例。服務會定義使用案例，以包含服務所需的信任政策。然後選擇**下一步**。

1. 選擇一或多個許可政策以連接至角色。根據您選取的使用案例，服務可能可以執行下列任何操作：
   + 定義角色使用的許可。
   + 可讓您從有限的一組許可中進行選擇。
   + 可讓您從任何許可中進行選擇。
   + 可讓您目前無法選取政策、稍後建立政策，然後將它們連接至角色。

   選取可指派您希望角色擁有之許可政策旁的核取方塊，然後選擇**下一步**。
**注意**  
您指定的許可適用於任何使用角色的實體。角色預設沒有任何許可。

1. 針對 **Role name (角色名稱)**，服務會定義角色名稱自訂程度。如果服務定義角色的名稱，則此選項無法編輯。在其他情況下，服務可能會定義角色的字首，並且允許您輸入選用後綴。

   如果可能，輸入要新增至預設名稱的角色名稱後綴。此後綴可協助您識別此角色的用途。角色名稱在您的 AWS 帳戶內必須是獨一無二的。它們無法透過大小寫進行區分。例如，您無法建立名為 **<service-linked-role-name>\$1SAMPLE** 和 **<service-linked-role-name>\$1sample** 的角色。因為有各種實體可能會參照角色，所以您無法在建立角色之後編輯角色名稱。

1. (選用) 在 **Description** (說明) 中，編輯新服務連結角色的說明。

1. 您不能在建立角色時，將標籤連接至服務連結的角色。如需有關在 IAM 中使用標籤的詳細資訊，請參閱 [AWS Identity and Access Management 資源的標籤](id_tags.md)。

1. 檢閱角色，然後選擇 **Create role** (建立角色)。

### 建立服務連結角色 (AWS CLI)
<a name="create-service-linked-role-iam-cli"></a>

在 IAM 中建立服務連結角色之前，了解連結的服務是否自動建立服務連結角色，並且了解是否您可以從服務的 CLI 建立角色。如果不支援服務 CLI，您可以使用 IAM 命令，使用服務擔任該角色所需的信任政策與內嵌政策來建立服務連結角色。

**建立服務連結角色 (AWS CLI)**

執行以下命令：

```
aws iam [create-service-linked-role](https://docs.aws.amazon.com/cli/latest/reference/iam/create-service-linked-role.html) --aws-service-name SERVICE-NAME.amazonaws.com
```

### 建立服務連結角色 (AWS API)
<a name="create-service-linked-role-iam-api"></a>

在 IAM 中建立服務連結角色之前，了解連結的服務是否自動建立服務連結角色，並且了解是否您可以從服務的 API 建立角色。如果不支援服務 API，您可以使用 AWS API 來建立具有信任政策和內嵌政策的服務連結角色，該政策是服務擔任該角色所需的。

**建立服務連結角色 (AWS API)**

使用 [CreateServiceLinkedRole](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateServiceLinkedRole.html) API 呼叫。在請求中指定 `SERVICE_NAME_URL.amazonaws.com` 的服務名稱。

例如，要建立 ** Lex Bots ** 服務連結的角色，使用 `lex.amazonaws.com`。

# 為第三方身分提供者建立角色
<a name="id_roles_create_for-idp"></a>

您可以使用身分提供者，而不是在 中建立 IAM 使用者 AWS 帳戶。使用身分提供者 (IdP)，您可以在 外部管理您的使用者身分， AWS 並授予這些外部使用者身分存取您帳戶中 AWS 資源的許可。如需有關聯合身分與身分提供者的詳細資訊，請參閱 [身分提供者和聯合身分 AWS](id_roles_providers.md)。

## 為 OIDC 和 SAML 聯合身分主體建立角色 (主控台)
<a name="roles-creatingrole-federated-users-console"></a>

建立角色的程序取決於所選擇的第三方提供者：
+ 如需 OpenID Connect (OIDC)，請參閱[為 OpenID Connect 聯合身分建立角色 (主控台)](id_roles_create_for-idp_oidc.md)。
+ 關於 SAML 2.0 的詳細資訊，請參閱[為 SAML 2.0 聯合身分建立角色 (主控台)](id_roles_create_for-idp_saml.md)。

## 為聯合存取建立角色 (AWS CLI)
<a name="roles-creatingrole-identityprovider-cli"></a>

從 AWS CLI 為支援的身分提供者 (OIDC 或 SAML) 建立角色的步驟是相同的。區別在於，您在先決條件步驟中建立的信任政策的內容不同。首先，遵循**先決條件**小節中針對您正在使用之提供者類型的步驟操作：
+ 關於 &OIDC; 提供者的詳細資訊，請參閱[建立適用於 OIDC 的角色的先決條件](id_roles_create_for-idp_oidc.md#idp_oidc_Prerequisites)。
+ 關於 &SAML; 提供者的詳細資訊，請參閱[建立適用於 SAML 的角色的先決條件](id_roles_create_for-idp_saml.md#idp_saml_Prerequisites)。

從 建立角色 AWS CLI 涉及多個步驟。當您使用 主控台建立角色時，會為您完成許多步驟，但您必須使用 自行 AWS CLI 明確執行每個步驟。您必須建立角色，然後為該角色指派許可政策。或者，您也可以設定角色的[許可界限](access_policies_boundaries.md)。

**若要建立角色 (AWS CLI)**

1. 建立角色：[aws iam create-role](https://docs.aws.amazon.com/cli/latest/reference/iam/create-role.html)

1. 將許可政策連接到角色：[aws iam attach-role-policy](https://docs.aws.amazon.com/cli/latest/reference/iam/attach-role-policy.html)

    或

   為角色建立內嵌許可政策：[aws iam put-role-policy](https://docs.aws.amazon.com/cli/latest/reference/iam/put-role-policy.html)

1. (選用) 透過連接標籤來將自訂屬性新增至該角色：[aws iam tag-role](https://docs.aws.amazon.com/cli/latest/reference/iam/tag-role.html)

   如需詳細資訊，請參閱 [管理 IAM 角色 (AWS CLI 或 AWS API) 上的標籤](id_tags_roles.md#id_tags_roles_procs-cli-api)。

1. (選用) 設定角色的[許可界限](access_policies_boundaries.md)：[aws iam put-role-permissions-boundary](https://docs.aws.amazon.com/cli/latest/reference/iam/put-role-permissions-boundary.html)

   許可界限控制角色可以擁有的許可上限。許可界限是一項進階 AWS 功能。

以下範例顯示前兩個最常見步驟，可在簡單的環境中建立一個身分提供者角色。此範例允許 `123456789012` 帳戶中的任何使用者擔任角色，並檢視 `example_bucket` Amazon S3 儲存貯體。此範例也假設您在執行 Windows AWS CLI 的電腦上執行 ，並已 AWS CLI 使用您的登入資料設定 。如需詳細資訊，請參閱[設定 AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html)。

下列範例信任政策是針對使用者使用 Amazon Cognito 登入時的行動應用程式而設計。在此範例中，*us-east:12345678-ffff-ffff-ffff-123456* 代表由 Amazon Cognito 指派的身分集區 ID。

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": {
        "Sid": "RoleForCognito",
        "Effect": "Allow",
        "Principal": {"Federated": "cognito-identity.amazonaws.com"},
        "Action": "sts:AssumeRoleWithWebIdentity",
        "Condition": {"StringEquals": {"cognito-identity.amazonaws.com:aud": "us-east:12345678-ffff-ffff-ffff-123456"}}
    }
}
```

------

下列許可政策允許任何擔任角色的人只對 `example_bucket` Amazon S3 儲存貯體執行 `ListBucket` 動作。

------
#### [ JSON ]

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": {
    "Effect": "Allow",
    "Action": "s3:ListBucket",
    "Resource": "arn:aws:s3:::example_bucket"
  }
}
```

------

若要建立此 `Test-Cognito-Role` 角色，您必須先將之前的信任政策以名稱 `trustpolicyforcognitofederation.json` 和之前名為 `permspolicyforcognitofederation.json` 的許可政策儲存到您本機 `policies` 磁碟機的 `C:` 資料夾。然後，您可以使用以下命令來建立角色，並連接內嵌政策。

```
# Create the role and attach the trust policy that enables users in an account to assume the role.
$ aws iam create-role --role-name Test-Cognito-Role --assume-role-policy-document file://C:\policies\trustpolicyforcognitofederation.json

# Attach the permissions policy to the role to specify what it is allowed to do.
aws iam put-role-policy --role-name Test-Cognito-Role --policy-name Perms-Policy-For-CognitoFederation --policy-document file://C:\policies\permspolicyforcognitofederation.json
```

## 建立聯合存取 (AWS API) 的角色
<a name="roles-creatingrole-identityprovider-api"></a>

從 AWS CLI 為支援的身分提供者 (OIDC 或 SAML) 建立角色的步驟是相同的。區別在於，您在先決條件步驟中建立的信任政策的內容不同。首先，遵循**先決條件**小節中針對您正在使用之提供者類型的步驟操作：
+ 關於 &OIDC; 提供者的詳細資訊，請參閱[建立適用於 OIDC 的角色的先決條件](id_roles_create_for-idp_oidc.md#idp_oidc_Prerequisites)。
+ 關於 &SAML; 提供者的詳細資訊，請參閱[建立適用於 SAML 的角色的先決條件](id_roles_create_for-idp_saml.md#idp_saml_Prerequisites)。

**建立角色 (AWS API)**

1. 建立角色：[CreateRole](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateRole.html)

1. 將許可政策連接到角色：[AttachRolePolicy](https://docs.aws.amazon.com/IAM/latest/APIReference/API_AttachRolePolicy.html)

    或

   為角色建立內嵌許可政策：[PutRolePolicy](https://docs.aws.amazon.com/IAM/latest/APIReference/API_PutRolePolicy.html)

1. (選用) 藉由連接標籤將自訂屬性新增至使用者：[TagRole](https://docs.aws.amazon.com/IAM/latest/APIReference/API_TagRole.html)

   如需詳細資訊，請參閱 [管理 IAM 使用者 (AWS CLI 或 AWS API) 上的標籤](id_tags_users.md#id_tags_users_procs-cli-api)。

1. (選用) 設定角色的[許可界限](access_policies_boundaries.md)：[PutRolePermissionsBoundary](https://docs.aws.amazon.com/IAM/latest/APIReference/API_PutRolePermissionsBoundary.html)

   許可界限控制角色可以擁有的許可上限。許可界限是一項進階 AWS 功能。

# 為 OpenID Connect 聯合身分建立角色 (主控台)
<a name="id_roles_create_for-idp_oidc"></a>

您可以使用 OpenID Connect (OIDC) 聯合身分提供者，而不是在您的 中建立 AWS Identity and Access Management 使用者 AWS 帳戶。使用身分提供者 (IdP)，您可以在 外部管理您的使用者身分， AWS 並授予這些外部使用者身分存取 AWS 您帳戶中資源的許可。如需有關聯合身分與 IdP 的詳細資訊，請參閱 [身分提供者和聯合身分 AWS](id_roles_providers.md)。

## 建立適用於 OIDC 的角色的先決條件
<a name="idp_oidc_Prerequisites"></a>

您必須先完成以下先決條件步驟，然後才能建立用於 OIDC 聯合身分的角色。<a name="oidc-prereqs"></a>

**若要準備建立用於 OIDC 聯合身分的角色**

1. 使用一或多個提供聯合 OIDC 身分的服務進行註冊。如果您要建立需要存取 AWS 資源的應用程式，您也可以使用提供者資訊來設定應用程式。當您這麼做時，提供者會將應用程式唯一的 ID 提供給您的應用程式或對象。(不同的提供者可能使用不同的術語來表達此程序。本指南則使用術語*設定*來表示向提供者識別您應用程式的程序)。您可以在每個提供者設定多個應用程式，或在單一應用程式設定多個提供者。檢視有關使用身分提供者的相關資訊，如下所示：
   + [Login with Amazon 開發人員中心](https://login.amazon.com/)
   + Facebook 開發人員網站上的[新增 Facebook 登入到您的應用程式或網站](https://developers.facebook.com/docs/facebook-login/v2.1)。
   + Google 開發人員網站上的[登入時使用 OAuth 2.0 (OpenID Connect)](https://developers.google.com/accounts/docs/OAuth2Login)。

1. <a name="idpoidcstep2"></a>從 IdP 收到必要資訊後，請在 IAM 中建立 IdP。如需詳細資訊，請參閱[在 IAM 中建立 OpenID Connect (OIDC) 身分提供者](id_roles_providers_create_oidc.md)。
**重要**  
如果您正在使用來自 Google、Facebook 或 Amazon Cognito 的 OIDC IdP，請勿在 AWS 管理主控台中建立單獨的 IAM IdP。這些 OIDC 身分提供者已內建於 AWS ，可供您使用。略過此步驟，並在接下來的步驟中使用您的 IdP 建立新角色。

1. 為已進行 IdP 身分驗證的使用者要擔任的角色準備政策。正如任何角色一樣，手機應用程式的角色含有兩項政策。其中一項是信任政策，其指定擔任該角色的對象。另一項政策是許可政策，其指定行動應用程式被允許或拒絕存取的 AWS 動作和資源。

   對於 Web 身分提供者，我們建議您使用 [Amazon Cognito](https://aws.amazon.com/cognito/) 來管理身分。在這種情況下，請使用類似於這個範例的信任政策。

------
#### [ JSON ]

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": {
           "Effect": "Allow",
           "Principal": {"Federated": "cognito-identity.amazonaws.com"},
           "Action": "sts:AssumeRoleWithWebIdentity",
           "Condition": {
               "StringEquals": {"cognito-identity.amazonaws.com:aud": "us-east-2:12345678-abcd-abcd-abcd-123456"},
               "ForAnyValue:StringLike": {"cognito-identity.amazonaws.com:amr": "unauthenticated"}
           }
       }
   }
   ```

------

   以 Amazon Cognito 指派給您的身分集區 ID 取代 `us-east-2:12345678-abcd-abcd-abcd-123456`。

   如果您手動設定 OIDC IdP，當您建立信任政策，您必須使用三個值，以確保只有您的應用程式可擔任該角色：
   + 對於 `Action` 元素，可使用 `sts:AssumeRoleWithWebIdentity` 動作。
   + 如需 `Principal` 元素，請使用字串 `{"Federated":providerUrl/providerArn}`。
     + 對於一些常見的 OIDC IdP，`providerUrl` 為 URL。以下範例包含多個方式，為部分常見 idP 指定主體：

       `"Principal":{"Federated":"cognito-identity.amazonaws.com"}`

       `"Principal":{"Federated":"www.amazon.com"}`

       `"Principal":{"Federated":"graph.facebook.com"}`

       `"Principal":{"Federated":"accounts.google.com"}`
     + 對於其他的 OIDC 提供者，請使用您在 [Step 2](#idpoidcstep2) 中建立的 OIDC 身分提供者的 Amazon Resource Name (ARN)，如以下範例所示：

       `"Principal":{"Federated":"arn:aws:iam::123456789012:oidc-provider/server.example.com"}`
   + 對於 `Condition` 元素，可使用 `StringEquals` 條件來限制許可。測試身分集區 ID (對於 Amazon Cognito) 或應用程式 ID (對於其他提供者)。身分集區 ID 應與您透過 IdP 配置應用程式時所收到的應用程式 ID 一致。ID 之間的比對可確保請求來自您的應用程式。
**注意**  
Amazon Cognito 身分集區的 IAM 角色信任服務主體 `cognito-identity.amazonaws.com` 擔任該角色。此類型的角色必須包含至少一個條件索引鍵，以限制可擔任該角色的主體。  
其他考量事項適用於擔任[跨帳戶 IAM 角色](access_policies-cross-account-resource-access.md)的 Amazon Cognito 身分集區。這些角色的信任政策必須接受 `cognito-identity.amazonaws.com` 服務主體，且必須包含 `aud` 條件索引鍵，以限制來自您預期身分集區的使用者擔任角色。如果不符合此條件，信任 Amazon Cognito 身分集區的政策會產生意外身分集區中的使用者可能擔任該角色的風險。如需詳細資訊，請參閱 *Amazon Cognito Developer Guide* 中的 [Trust policies for IAM roles in Basic (Classic) authentication](https://docs.aws.amazon.com/cognito/latest/developerguide/iam-roles.html#trust-policies)。

     建立類似以下其中一個範例的條件元素，其取決於您使用的 IdP：

     `"Condition": {"StringEquals": {"cognito-identity.amazonaws.com:aud": "us-east:12345678-ffff-ffff-ffff-123456"}}`

     `"Condition": {"StringEquals": {"www.amazon.com:app_id": "amzn1.application-oa2-123456"}}`

     `"Condition": {"StringEquals": {"graph.facebook.com:app_id": "111222333444555"}}`

     `"Condition": {"StringEquals": {"accounts.google.com:aud": "66677788899900pro0"}}`

     對於 OIDC 提供者，請將 OIDC IdP 的完全合格 URL 與 `aud` 內容索引鍵一起使用，如以下範例所示：

     `"Condition": {"StringEquals": {"server.example.com:aud": "appid_from_oidc_idp"}}`
**注意**  
角色的信任政策中的主體的值是 IdP 特有的。OIDC 的角色只能指定一個主體。因此，如果行動應用程式允許使用者從多個 IdP 登入，則為您要支援的每個 IdP 建立不同的角色。分別為每個 IdP 建立信任政策。

   如果使用者使用行動應用程式從 Login with Amazon 登入，則以下範例信任政策適用。在範例中，*amzn1.application-oa2-123456* 代表使用 Login with Amazon 設定應用程式時 Amazon 指派的應用程式 ID。

------
#### [ JSON ]

****  

   ```
   {
         "Version":"2012-10-17",		 	 	 
         "Statement": [{
             "Sid": "RoleForLoginWithAmazon",
             "Effect": "Allow",
             "Principal": {"Federated": "www.amazon.com"},
             "Action": "sts:AssumeRoleWithWebIdentity",
             "Condition": {"StringEquals": {"www.amazon.com:app_id": "amzn1.application-oa2-123456"}}
         }]
     }
   ```

------

   如果使用者使用行動應用程式從 Facebook 登入，則以下範例信任政策適用。在本範例中，*111222333444555* 代表 Facebook 指派的應用程式 ID。

------
#### [ JSON ]

****  

   ```
   {
         "Version":"2012-10-17",		 	 	 
         "Statement": [{
             "Sid": "RoleForFacebook",
             "Effect": "Allow",
             "Principal": {"Federated": "graph.facebook.com"},
             "Action": "sts:AssumeRoleWithWebIdentity",
             "Condition": {"StringEquals": {"graph.facebook.com:app_id": "111222333444555"}}
         }]
     }
   ```

------

   如果使用者使用行動應用程式從 Google 登入，則以下範例信任政策適用。在本範例中，*666777888999000* 代表由 Google 指派的應用程式 ID。

------
#### [ JSON ]

****  

   ```
   {
         "Version":"2012-10-17",		 	 	 
         "Statement": [{
             "Sid": "RoleForGoogle",
             "Effect": "Allow",
             "Principal": {"Federated": "accounts.google.com"},
             "Action": "sts:AssumeRoleWithWebIdentity",
             "Condition": {"StringEquals": {"accounts.google.com:aud": "666777888999000"}}
         }]
     }
   ```

------

   如果使用者使用行動應用程式從 Amazon Cognito 登入，則以下範例信任政策適用。在此範例中，*us-east:12345678-ffff-ffff-ffff-123456* 代表 Amazon Cognito 指派的身分集區 ID。

------
#### [ JSON ]

****  

   ```
   {
         "Version":"2012-10-17",		 	 	 
         "Statement": [{
             "Sid": "RoleForCognito",
             "Effect": "Allow",
             "Principal": {"Federated": "cognito-identity.amazonaws.com"},
             "Action": "sts:AssumeRoleWithWebIdentity",
             "Condition": {"StringEquals": {"cognito-identity.amazonaws.com:aud": "us-east:12345678-ffff-ffff-ffff-123456"}}
         }]
     }
   ```

------

## 為 OIDC 建立角色
<a name="idp_oidc_Create"></a>

完成先決條件後，您可在 IAM 建立角色。對於已辨識的共用 OpenID Connect (OIDC) 身分提供者 (IdP)，IAM 需要明確評估 JSON Web 權杖 (JWT) 中稱為*身分提供者控制項*的特定宣告。如需有關具有*身分提供者控制項*之 OIDC IdP 的詳細資訊，請參閱[共用 OIDC 提供者的身分提供者控制項](id_roles_providers_oidc_secure-by-default.md)。

下列程序介紹如何在 AWS 管理主控台中建立用於 OIDC 聯合身分的角色。若要從 AWS CLI 或 AWS API 建立角色，請參閱 中的程序[為第三方身分提供者建立角色](id_roles_create_for-idp.md)。

**重要**  
如果您使用 Amazon Cognito，請使用 Amazon Cognito 主控台來設定角色。否則，請使用 IAM 主控台來為 OIDC 聯合身分建立角色。

**若要為 OIDC 聯合身分建立 IAM 角色**

1. 登入 AWS 管理主控台 ，並在 https：//[https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/) 開啟 IAM 主控台。

1. 在導覽窗格中，選擇 **Roles** (角色)，然後選擇 **Create role** (建立角色)。

1. 選擇 **Web 身分**作為信任的實體類型，然後選取**下一步**。

1. 針對 **Identity provider** (身分提供者)，選擇您角色的身分提供者：
   + 如果要為個別 Web 身分提供者建立角色，請選擇 **Login with Amazon**、**Facebook** 或 **Google**。
**注意**  
您必須為想要支援的每個身分提供者建立單獨的角色。
   + 如果想要為 Amazon Cognito 建立進階案例角色，請選擇 **Amazon Cognito**。
**注意**  
只有在處理進階案例時，必須手動建立與 Amazon Cognito 一起使用的角色。否則，Amazon Cognito 可以為您建立角色。如需 Amazon Cognito 的詳細資訊，請參閱《Amazon Cognito 開發人員指南》**中的[身分集區 (聯合身分) 外部身分提供者](https://docs.aws.amazon.com/cognito/latest/developerguide/external-identity-providers.html)。
   + 如果您想要為 GitHub Actions 建立角色，您必須先將 GitHub OIDC 提供者新增至 IAM。將 GitHub OIDC 提供者新增至 IAM 之後，請選擇 **token.actions.githubusercontent.com**。
**注意**  
如需如何設定 AWS 將 GitHub 的 OIDC 供應商信任為聯合身分的相關資訊，請參閱 [GitHub 文件 - 在 Amazon Web Services 中設定 OpenID Connect](https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/configuring-openid-connect-in-amazon-web-services)。若要針對與 GitHub 的 IAM IdP 相關聯的角色限制存取權，最佳實務的相關資訊請見本頁的[設定 GitHub OIDC 身分提供者的角色](#idp_oidc_Create_GitHub)。
   + 如果想要為 HashiCorp Cloud Platform (HCP) Terraform 建立角色，您必須先將 Terraform OIDC 提供者新增至 IAM。將 Terraform OIDC 提供者新增至 IAM 之後，選擇 **app.terraform.io**。
**重要**  
HashiCorp Cloud Platform (HCP) Terraform OIDC 提供者的 IAM 角色必須在角色信任政策中評估 IAM 條件索引鍵 `app.terraform.io:sub`。此條件索引鍵會限制哪些 HCP Terraform 組織、專案、工作區或執行階段能夠擔任該角色。如果沒有此條件金鑰，您的信任政策會透過組織外部的身分授予對角色 AWS 和資源的存取權，這不符合最低權限原則。  
如果您為 AWS 帳戶中與 HCP Terraform OIDC 供應商相關聯的角色設定或修改角色信任政策，但未評估 IAM 條件金鑰 `app.terraform.io:sub`，您將會收到錯誤。此外，如果您的角色信任政策未評估此條件索引鍵， AWS STS 將拒絕授權請求。

1. 請求的資訊會根據所選擇的 OIDC 提供者而有所不同。
   + 輸入您的應用程式的識別碼。識別碼的標籤會因所選擇的提供者而改變：
     + 如果您要為 Login with Amazon 建立角色，請將應用程式 ID 輸入 **Application ID** (應用程式 ID) 方塊中。
     + 如果您要為 Facebook 建立角色，請將應用程式 ID 輸入 **Application ID** (應用程式 ID) 方塊中。
     + 如果您要為 Google 建立角色，請在 **Audience** (對象) 方塊中輸入對象名稱。
     + 如果您要為 Amazon Cognito 建立角色，請在 **Identity Pool ID** (身分集區 ID) 方塊中輸入您為 Amazon Cognito 應用程式建立的身分集區 ID。
   + 如果您想要為 GitHub Actions 建立角色，請輸入下列詳細資訊：
     + 針對 **Audience** (對象)，選擇 `sts.amazonaws.com`。
     + 針對 **GitHub 組織**，輸入 GitHub 組織名稱。GitHub 組織名稱是必要資訊，而且必須由包含破折號 (-) 的英數字元組成。您無法在 GitHub 組織名稱中使用萬用字元 (\$1 和 ?)。
     + (選用) 針對 **GitHub 儲存庫**，輸入 GitHub 儲存庫名稱。如果您不指定值，則會預設為萬用字元 (`*`)。
     + (選用) 針對 **GitHub 分支**，輸入 GitHub 分支名稱。如果您不指定值，則會預設為萬用字元 (`*`)。
   + 如果您想要為 HashiCorp Cloud Platform (HCP) Terraform 建立角色，請輸入下列詳細資訊：
     + 針對 **Audience** (對象)，選擇 `aws.workload.identity`。
     + 針對**組織**，輸入組織名稱。您可以為所有組織指定萬用字元 (`*`)。
     + 針對**專案**，輸入專案名稱。您可以為所有專案指定萬用字元 (`*`)。
     + 針對**工作區**，輸入工作區名稱。您可以為所有工作區指定萬用字元 (`*`)。
     + 針對**執行階段**，輸入執行階段名稱。您可以為所有執行階段指定萬用字元 (`*`)。

1. (選用) 針對**條件 (選用)**，選擇**新增條件**，以建立應用程式使用者在能夠使用角色所授予的許可之前所必須滿足的其他條件。例如，您可以新增僅針對特定 IAM 使用者 ID 授予 AWS 資源存取權的條件。您也可以在建立角色之後，將條件新增至信任政策。如需詳細資訊，請參閱[更新角色信任政策](id_roles_update-role-trust-policy.md)。

1. 檢閱您的 OIDC 資訊，然後選擇**下一步**。

1. IAM 包含您帳戶中 AWS 受管和客戶受管政策的清單。選取用於許可政策的政策，或者選擇 **Create policy** (建立政策) 以開啟新的瀏覽器標籤，並從頭建立新的政策。如需詳細資訊，請參閱[建立 IAM 政策](access_policies_create-console.md#access_policies_create-start)。在您建立政策後，關閉該標籤並返回您的原始標籤。選取您希望 OIDC 使用者具有的許可政策旁的核取方塊。如果您希望，您目前可以不選取政策，稍後再將政策連接到角色。角色預設沒有任何許可。

1. (選用) 設定[許可界限](access_policies_boundaries.md)。這是進階功能。

   開啟 **Permissions boundary** (許可界限) 區段，並選擇 **Use a permissions boundary to control the maximum role permissions** (使用許可界限來控制角色許可上限)。選取用於許可界限的政策。

1. 選擇**下一步**。

1. 在 **Role name** (角色名稱) 中，輸入角色名稱。角色名稱在您的 中必須是唯一的 AWS 帳戶。它們不區分大小寫。例如，您無法建立名為 **PRODROLE** 和 **prodrole** 的角色。由於其他 AWS 資源可能會參考角色，因此您無法在建立角色之後編輯角色的名稱。

1. (選用) 在 **Description** (說明) 中，輸入新角色的說明。

1. 如要編輯使用案例和角色許可，請在 **Step 1: Select trusted entities** (步驟 1：選取受信任的實體) 或者 **Step 2: Add permissions** (步驟 2：新增許可) 區段中選擇 **Edit** (編輯)。

1. (選用) 若要將中繼資料新增至角色，請附加標籤做為鍵/值對。如需有關在 IAM 中使用標籤的詳細資訊，請參閱 [AWS Identity and Access Management 資源的標籤](id_tags.md)。

1. 檢閱角色，然後選擇 **Create role** (建立角色)。

## 設定 GitHub OIDC 身分提供者的角色
<a name="idp_oidc_Create_GitHub"></a>

如果您使用 GitHub 做為 OpenID Connect (OIDC) 身分提供者 (IdP)，最佳實務是限制可擔任與 IAM IdP 相關聯角色的實體。當您在信任政策中包含條件陳述式時，可以將角色限制到特定 GitHub 組織、儲存庫或分支。您可以使用具有字符條件運算子的條件索引鍵 `token.actions.githubusercontent.com:sub` 來限制存取權。建議您將條件限制為一組特定的儲存庫或 GitHub 組織內的分支。如需如何設定 AWS 將 GitHub 的 OIDC 信任為聯合身分的相關資訊，請參閱 [GitHub 文件 - 在 Amazon Web Services 中設定 OpenID Connect](https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/configuring-openid-connect-in-amazon-web-services)。

如果您在動作工作流程或 OIDC 政策中使用 GitHub 環境，我們強烈建議將保護規則新增至環境，以提升安全性。使用部署分支和標籤來限制哪些分支和索引標籤可以部署至環境。如需有關使用保護規則設定環境的詳細資訊，請參閱 GitHub 的 *Using environments for deployment* 文章中的 [Deployment branches and tags](https://docs.github.com/en/actions/deployment/targeting-different-environments/using-environments-for-deployment#deployment-branches-and-tags)。

當 GitHub 的 OIDC IdP 是您角色的受信任主體時，IAM 會檢查角色信任政策條件以驗證條件索引鍵 `token.actions.githubusercontent.com:sub` 確實存在，且其值不單是萬用字元 (\$1 和 ?) 或 null。IAM 會在建立或更新信任政策時執行此檢查。如果條件索引鍵 `token.actions.githubusercontent.com:sub` 不存在，或者鍵值不滿足上述值標準，請求將失敗且會傳回錯誤。

**重要**  
如果您未將條件金鑰限制`token.actions.githubusercontent.com:sub`為特定組織或儲存庫，則來自您控制範圍之外的組織或儲存庫的 GitHub 動作可以擔任與您 AWS 帳戶中的 GitHub IAM IdP 相關聯的角色。

下列範例信任政策會限制存取已定義的 GitHub 組織、儲存庫和分支。下列範例中，條件索引鍵 `token.actions.githubusercontent.com:sub` 值是 GitHub 所記錄的預設主旨值格式。

------
#### [ JSON ]

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Federated": "arn:aws:iam::012345678910:oidc-provider/token.actions.githubusercontent.com"
      },
      "Action": "sts:AssumeRoleWithWebIdentity",
      "Condition": {
        "StringEquals": {
          "token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
          "token.actions.githubusercontent.com:sub": "repo:GitHubOrg/GitHubRepo:ref:refs/heads/GitHubBranch"
        }
      }
    }
  ]
}
```

------

下列範例條件會限制存取已定義的 GitHub 組織和儲存庫，但會授予對儲存庫內任何分支的存取權。

```
"Condition": {
  "StringEquals": {
          "token.actions.githubusercontent.com:aud": "sts.amazonaws.com"
  },
  "StringLike": {    
    "token.actions.githubusercontent.com:sub": "repo:GitHubOrg/GitHubRepo:*"
  }
}
```

下列範例條件會限制存取已定義的 GitHub 組織中的任何儲存庫或分支。我們建議您將條件索引鍵 `token.actions.githubusercontent.com:sub` 限制為特定值，此特定值可限制從您的 GitHub 組織內部存取 GitHub 動作。

```
"Condition": {
  "StringEquals": {
          "token.actions.githubusercontent.com:aud": "sts.amazonaws.com"
  },
  "StringLike": {    
    "token.actions.githubusercontent.com:sub": "repo:GitHubOrg/*"
  }
}
```

如需有關可用於政策中條件檢查的 OIDC 聯合身分索引鍵的詳細資訊，請參閱[AWS OIDC 聯合的可用金鑰](reference_policies_iam-condition-keys.md#condition-keys-wif)。

# 為 SAML 2.0 聯合身分建立角色 (主控台)
<a name="id_roles_create_for-idp_saml"></a>

 您可以使用 SAML 2.0 聯合，而不是在 中建立 IAM 使用者。 AWS 帳戶使用身分提供者 (IdP)，您可以在 外部管理您的使用者身分， AWS 並授予這些外部使用者身分存取您帳戶中 AWS 資源的許可。如需有關聯合身分與身分提供者的詳細資訊，請參閱 [身分提供者和聯合身分 AWS](id_roles_providers.md)。

**注意**  
若要改善聯合彈性，建議您將 IdP 和 AWS 聯合設定為支援多個 SAML 登入端點。如需詳細資訊，請參閱 AWS 安全部落格文章[如何使用區域 SAML 端點進行容錯移轉](https://aws.amazon.com/blogs//security/how-to-use-regional-saml-endpoints-for-failover)。

## 建立適用於 SAML 的角色的先決條件
<a name="idp_saml_Prerequisites"></a>

您必須先完成以下先決條件步驟，然後才能建立用於 SAML 2.0 聯合身分的角色。<a name="saml-prereqs"></a>

**準備建立用於 SAML 2.0 聯合身分的角色**

1. <a name="idpsamlstep1"></a>在為以 SAML 為基礎的聯合身分建立角色之前，必須在 IAM 中建立 SAML 提供者。如需詳細資訊，請參閱 [在 IAM 中建立 SAML 身分提供者](id_roles_providers_create_saml.md)。

1. 為已進行 SAML 2.0–身分驗證的使用者要擔任的角色準備政策。正如任何角色一樣，SAML 聯合身分的角色含有兩項政策。其中一項是角色信任政策，指定擔任該角色的對象。另一個是 IAM 許可政策，指定允許或拒絕 SAML 聯合主體存取 AWS 的動作和資源。

   當您為您的角色建立信任政策時，必須使用三個值，以確保只有您的應用程式可擔任該角色：
   + 對於 `Action` 元素，可使用 `sts:AssumeRoleWithSAML` 動作。
   + 如需 `Principal` 元素，請使用字串 `{"Federated":ARNofIdentityProvider}`。將 `ARNofIdentityProvider` 取代為您在 [Step 1](#idpsamlstep1) 中建立的 [SAML 身分提供者](id_roles_providers_saml.md) ARN。
   + 對於 `Condition` 元素，請使用 `StringEquals` 條件來測試 SAML 回應中的 `saml:aud` 屬性是否與登入主控台時瀏覽器顯示的 URL 相符。此登入端點 URL 是身分提供者的 SAML 收件人屬性。您可以在特定區域中包含登入 URLs。 AWS 建議使用區域端點而非全域端點來改善聯合彈性。對於可能的 *region-code* 值清單，請參閱 [AWS 登入端點](https://docs.aws.amazon.com/general/latest/gr/signin-service.html)中的 **Region** (區域) 欄位。

     如果需要 SAML 加密，登入 URL 必須包含指派給 SAML 提供者的唯一識別碼 AWS 。可以透過在 IAM 主控台中選取身分提供者來顯示詳細資訊頁面，以檢視唯一識別碼。

     `https://region-code.signin.aws.amazon.com/saml/acs/IdP-ID`

   以下範例信任政策是專為 SAML 聯合身分使用者設計的政策：

------
#### [ JSON ]

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": {
           "Effect": "Allow",
           "Action": "sts:AssumeRoleWithSAML",
           "Principal": {
               "Federated": "arn:aws:iam::111122223333:saml-provider/PROVIDER-NAME"
           },
           "Condition": {
               "StringEquals": {
                   "SAML:aud": "https://region-code.signin.aws.amazon.com/saml"
               }
           }
       }
   }
   ```

------

   將主體 ARN 取代為您在 IAM 中所建立的 SAML 提供者的實際 ARN。它會有自己的帳戶 ID 和提供者名稱。

## 建立 SAML 的角色
<a name="idp_saml_Create"></a>

完成必要步驟後，您可以建立以 SAML 為基礎的聯合身分角色。

**若要為以 SAML 為基礎的聯合身分建立角色**

1. 登入 AWS 管理主控台 ，並在 https：//[https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/) 開啟 IAM 主控台。

1. 在 IAM 主控台的導覽窗格中，選擇 **Roles** (角色)，然後選擇 **Create role** (建立角色)。

1. 選擇 **SAML 2.0 federation (SAML 2.0 聯合身分)** 角色類型。

1. 針對 **Select a SAML provider** (選擇 SAML 提供者)，選擇您角色的提供者。

1. 選擇 SAML 2.0 存取層級的方法。
   + 選擇**僅允許程式設計存取**，以建立可從 AWS API 或 以程式設計方式擔任的角色 AWS CLI。
   + 選擇**允許程式設計和 AWS 管理主控台 存取**，以建立可以程式設計方式從 擔任的角色 AWS 管理主控台。

   同時建立類似的角色，但也可以從主控台所擔任的角色包括具有特定條件的信任政策。該條件明確確保可將 SAML 對象 (`SAML:aud` 屬性) 設定為 SAML 提供者的 AWS 登入端點。

1. 定義屬性的程序因存取類型而異。
   + 如果要為程式設計存取建立角色，請從 **Attribute (屬性)** 清單選取屬性。然後，在 **Value** (值) 方塊中，輸入包含在角色中的值。這會限制從身分提供者存取使用者的角色，其身分提供者的 SAML 身分驗證回應 (聲明) 包括您指定的屬性。您必須至少指定一個屬性，以確保您的角色僅限於組織中的一部分使用者。
   + 如果您要為程式設計和 AWS 管理主控台 存取建立角色，**登入端點**區段會定義您的瀏覽器在登入主控台時顯示的 URL。此端點是身分提供者的 SAML 收件人屬性，會映射至 [`saml:aud`](reference_policies_iam-condition-keys.md#condition-keys-saml) 內容索引鍵。如需詳細資訊，請參閱[為身分驗證回應設定 SAML 聲明](id_roles_providers_create_saml_assertions.md)。

     1. 選擇**區域端點**或**非區域端點**。建議使用多個區域 SAML 登入端點，以便改善聯合身分彈性。

     1. 針對**區域**，選擇 SAML 供應商支援 AWS 登入的區域。

     1.  若要**讓登入 URLs 包含唯一識別符**，請選取登入端點是否包含 AWS 指派給 SAML 身分提供者的唯一識別符。加密 SAML 聲明需要此選項。如需詳細資訊，請參閱[SAML 2.0 聯合身分](id_roles_providers_saml.md)。

1. 若要向信任政策新增更多與屬性相關的條件，請選擇 **Condition (optional)** (條件 (選用))，並選取其他條件，然後指定值。
**注意**  
該清單包含最常用的 SAML 屬性。IAM 支援可用於建立條件的其他屬性。如需所支援屬性的清單，請參閱 [SAML 聯合身分的可用金鑰](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html#condition-keys-saml)。如果您需要不在清單中的受支援 SAML 屬性的條件，您可以手動新增該條件。若要這麼做，請在建立角色後編輯信任政策。

1.  檢閱您的 SAML 2.0 信任資訊，然後選擇 **Next** (下一步)。

1. IAM 包含您帳戶中 AWS 受管和客戶受管政策的清單。選取用於許可政策的政策，或者選擇 **Create policy** (建立政策) 以開啟新的瀏覽器標籤，並從頭建立新的政策。如需詳細資訊，請參閱[建立 IAM 政策](access_policies_create-console.md#access_policies_create-start)。在您建立政策後，關閉該標籤並返回您的原始標籤。選取您希望 SAML 聯合身分使用者具有之許可政策旁的核取方塊。如果您希望，您目前可以不選取政策，稍後再將政策連接到角色。角色預設沒有任何許可。

1. (選用) 設定[許可界限](access_policies_boundaries.md)。這是進階功能。

   開啟 **Permissions boundary** (許可界限) 區段，並選擇 **Use a permissions boundary to control the maximum role permissions** (使用許可界限來控制角色許可上限)。選取用於許可界限的政策。

1. 選擇**下一步**。

1. 選擇下**一步：檢閱**。

1. 在 **Role name** (角色名稱) 中，輸入角色名稱。角色名稱在您的 中必須是唯一的 AWS 帳戶。它們不區分大小寫。例如，您無法建立名為 **PRODROLE** 和 **prodrole** 的角色。由於其他 AWS 資源可能會參考角色，因此您無法在建立角色之後編輯角色的名稱。

1. (選用) 在 **Description** (說明) 中，輸入新角色的說明。

1. 在 **Step 1: Select trusted entities** (步驟 1：選取受信任的實體) 或者 **Step 2: Add permissions** (步驟 2：新增許可) 區段中選擇 **Edit** (編輯)，可編輯使用案例和角色許可。

1. (選用) 藉由連接標籤作為鍵值對，將中繼資料新增至角色。如需有關在 IAM 中使用標籤的詳細資訊，請參閱 [AWS Identity and Access Management 資源的標籤](id_tags.md)。

1. 檢閱角色，然後選擇 **Create role** (建立角色)。

在您建立角色之後，您透過 AWS的相關資訊設定您的身分提供者軟體來完成 SAML 信任。此資訊包含您希望 SAML 聯合身分使用者使用的角色。這是指在您的 IdP 和 AWS之間設定依賴方信任。如需詳細資訊，請參閱[使用依賴方信任設定您的 SAML 2.0 IdP 並新增宣告](id_roles_providers_create_saml_relying-party.md)。

# 使用自訂信任政策建立角色
<a name="id_roles_create_for-custom"></a>

您可以建立自訂信任政策來委派存取權，並允許其他人在您的 中執行動作 AWS 帳戶。如需詳細資訊，請參閱[建立 IAM 政策](access_policies_create-console.md#access_policies_create-start)。

如需有關如何使用角色委派許可的資訊，請參閱[角色術語和概念](id_roles.md#id_roles_terms-and-concepts)。

## 使用自訂信任政策 (主控台) 建立 IAM 角色
<a name="roles-creatingrole-custom-trust-policy-console"></a>

您可以使用 AWS 管理主控台 來建立 IAM 使用者可以擔任的角色。例如，假設您的組織有多個 AWS 帳戶 來隔離開發環境與生產環境。如需有關建立可讓開發帳戶中的使用者存取生產帳戶中資源的角色的高階資訊，請參閱[使用不同的開發和生產帳戶的範例方案](id_roles_common-scenarios_aws-accounts.md#id_roles_common-scenarios_aws-accounts-example)。

**使用自訂信任政策 (主控台) 建立角色**

1. 登入 AWS 管理主控台 ，並在 https：//[https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/) 開啟 IAM 主控台。

1. 在主控台的導覽窗格中，選擇 **Roles (角色)**，然後選擇 **Create role (建立角色)**。

1. 選擇 **Custom trust policy** (自訂信任政策) 角色類型。

1. 在 **Custom trust policy** (自訂信任政策) 區段中，輸入或貼上角色的自訂信任政策。如需詳細資訊，請參閱[建立 IAM 政策](access_policies_create-console.md#access_policies_create-start)。

1. 解決[政策驗證](access_policies_policy-validator.md)期間產生的任何安全性警告、錯誤或一般性警告，然後選擇 **Next** (下一步)。

1. (選用) 設定[許可界限](access_policies_boundaries.md)。這是進階功能，可用於服務角色，而不是服務連結的角色。

   開啟 **Permissions boundary** (許可界限) 區段，並選擇 **Use a permissions boundary to control the maximum role permissions** (使用許可界限來控制角色許可上限)。IAM 包含您帳戶中 AWS 受管和客戶受管政策的清單。選取用於許可界限的政策。

1. 選擇**下一步**。

1. 針對 **Role name (角色名稱)**，服務會定義角色名稱自訂程度。如果服務定義角色名稱，則無法編輯此選項。在其他情況下，服務可能會定義角色的字首，並且可允許您輸入選用後綴。有些服務可讓您指定角色的完整名稱。

   如有可能，請輸入角色名稱或角色名稱後綴。角色名稱在您的 中必須是唯一的 AWS 帳戶。它們不區分大小寫。例如，您無法建立名為 **PRODROLE** 和 **prodrole** 的角色。由於其他 AWS 資源可能會參考角色，因此您無法在建立角色之後編輯角色的名稱。

1. (選用) 在 **Description** (說明) 中，輸入新角色的說明。

1. (選用) 在**步驟 1：選取信任的實體**或**步驟 2：新增許可**區段中選擇**編輯**，以編輯角色的自訂政策和許可。

1. (選用) 藉由連接標籤作為鍵值對，將中繼資料新增至角色。如需有關在 IAM 中使用標籤的詳細資訊，請參閱 [AWS Identity and Access Management 資源的標籤](id_tags.md)。

1. 檢閱角色，然後選擇 **Create role** (建立角色)。

# 委派存取權限的政策範例
<a name="id_roles_create_policy-examples"></a>

下列範例示範如何允許或授予 AWS 帳戶 存取另一個 中的資源 AWS 帳戶。若要了解如何使用這些範例 JSON 政策文件來建立 IAM 政策，請參閱 [正在使用 JSON 編輯器建立政策](access_policies_create-console.md#access_policies_create-json-editor)。

**Topics**
+ [使用 角色將存取權委派給另一個資源的資源 AWS 帳戶](#example-delegate-xaccount-rolesapi)
+ [使用政策將存取權限委託給服務](#id_roles_create_policy-examples-access-to-services)
+ [使用以資源為基礎的政策來指派存取另一個帳戶中的 Amazon S3 儲存貯體的權限。](#example-delegate-xaccount-S3)
+ [使用以資源為基礎的政策來指派存取另一個帳戶中的 Amazon SQS 佇列的權限。](#example-delegate-xaccount-SQS)
+ [當拒絕存取帳戶時，不得委託存取](#example-delegate-xaccount-SQS-denied)

## 使用 角色將存取權委派給另一個資源的資源 AWS 帳戶
<a name="example-delegate-xaccount-rolesapi"></a>

 如需示範如何使用 IAM 角色授予某個帳戶中使用者存取另一個帳戶中 AWS 資源的教學課程，請參閱 [IAM 教學課程：使用 IAM 角色在 AWS 帳戶之間委派存取權](tutorial_cross-account-with-roles.md)。

**重要**  
您可以在角色信任政策的 `Principal` 元素中包含特定角色或使用者的 ARN。當您儲存政策時， 會將 ARN AWS 轉換為唯一的委託人 ID。如果有人希望藉由刪除並重新建立角色或使用者來提升特權，這麼做可有助於減輕此類風險。您通常不會在主控台中看到此 ID，因為在顯示信任政策時還會反向轉換回 ARN。不過，如果您刪除角色或使用者，則關係會中斷。即使重新建立使用者或角色，您的政策都不再適用，因為它不符合信任政策中所儲存的主體 ID。發生這種情況時，主體 ID 會顯示在主控台中，因為 AWS 無法再將其對應回 ARN。結果是，如果您刪除並重新建立了信任政策的 `Principal` 元素所引用的使用者或角色，您必須編輯角色來替換 ARN。當您儲存政策時，它會轉換為新的主體 ID。

## 使用政策將存取權限委託給服務
<a name="id_roles_create_policy-examples-access-to-services"></a>

以下範例顯示一個可以連接到角色的政策。此政策可讓 Amazon EMR 和 這兩個服務 AWS Data Pipeline擔任該角色。然後服務可以執行指派給角色的許可政策所授予的任何任務 (不顯示)。若要指定多個服務主體，不用指定兩個 `Service` 元素；您可以只使用一個該元素。實際上，您可以將一組多個服務主體做為單一 `Service` 元素的值。

------
#### [ JSON ]

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": [
          "elasticmapreduce.amazonaws.com",
          "datapipeline.amazonaws.com"
        ]
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
```

------

## 使用以資源為基礎的政策來指派存取另一個帳戶中的 Amazon S3 儲存貯體的權限。
<a name="example-delegate-xaccount-S3"></a>

在本範例中，帳戶 A 使用資源類型政策 (一個 Amazon S3 [儲存貯體政策](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingBucketPolicies.html)) 授予帳戶 B 完全存取帳戶 A 的 S3 儲存貯體。然後，帳戶 B 建立一個 IAM 使用者政策，向帳戶 B 中的一個使用者授予針對帳戶 A 的儲存貯體的存取權限。

帳戶 A 中的 S3 儲存貯體政策可能與以下政策類似。在本範例中，帳戶 A 的 S3 儲存貯體的名稱為 *amzn-s3-demo-bucket*，而帳戶 B 的帳戶號碼為 111122223333。它在帳戶 B 中未指定任何單一使用者或群組，僅指定帳戶本身。

------
#### [ JSON ]

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": {
    "Sid": "AccountBAccess1",
    "Effect": "Allow",
    "Principal": {"AWS": "111122223333"},
    "Action": "s3:*",
    "Resource": [
      "arn:aws:s3:::amzn-s3-demo-bucket",
      "arn:aws:s3:::amzn-s3-demo-bucket/*"
    ]
  }
}
```

------

或者，帳戶 A 可使用 Amazon S3 [存取控制清單 (ACL)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/S3_ACLs_UsingACLs.html) 來授予帳戶 B 存取 S3 儲存貯體或某個儲存貯體內的單一物件。這種情況下，唯一改變的是帳戶 A 授權存取帳戶 B 的方式。如此範例的下一個部分所述，帳戶 B 仍使用一個政策委託針對帳戶 B 中的 IAM 群組的存取許可。如需有關對 S3 儲存貯體和物件實施控制存取的詳細資訊，請前往*Amazon Simple Storage Service 使用者指南*中的[存取控制](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingAuthAccess.html)。

帳戶 B 的管理員可能建立以下政策範例。該政策向帳戶 B 中的群組或使用者授予讀取存取許可。前一政策向帳戶 B 授予存取許可。但是，除非組或使用者政策明確授予資源存取許可，否則帳戶 B 中的單個群組和使用者不能存取資源。此政策中的許可只能是上述跨帳戶政策中的許可的一個子集。相比於帳戶 A 在第一個政策中授予帳戶 B 的許可，帳戶 B 無法向其群組和使用者授予更多許可。在此政策中，將明確定義 `Action` 元素以僅允許 `List` 操作，而且此政策的 `Resource` 元素與由帳戶 A 執行的儲存貯體政策的 `Resource` 配對。

為執行此政策，帳戶 B 使用 IAM 將其連接到帳戶 B 中的適用使用者 (或群組)。

------
#### [ JSON ]

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": {
    "Effect": "Allow",
    "Action": "s3:List*",
    "Resource": [
      "arn:aws:s3:::amzn-s3-demo-bucket",
      "arn:aws:s3:::amzn-s3-demo-bucket/*"
    ]
  }
}
```

------

## 使用以資源為基礎的政策來指派存取另一個帳戶中的 Amazon SQS 佇列的權限。
<a name="example-delegate-xaccount-SQS"></a>

在下列範例中，帳戶 A 具有 Amazon SQS 佇列，而此佇列使用連接至佇列的資源類型政策向帳戶 B 授予佇列存取權。然後，帳戶 B 使用 IAM 群組原則委派帳戶 B 中群組的存取權。

以下範例佇列政策為帳戶 B 授予許可，以對帳戶 A 中名為 *queue1* 的佇列執行 `SendMessage` 和 `ReceiveMessage` 動作，但只能在 2014 年 11 月 30 日中午 12:00 至下午 3:00 之間執行該動作。Account B 的帳戶編號為 1111-2222-3333。帳戶 A 使用 Amazon SQS 執行此政策。

------
#### [ JSON ]

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": {
    "Effect": "Allow",
    "Principal": {"AWS": "111122223333"},
    "Action": [
      "sqs:SendMessage",
      "sqs:ReceiveMessage"
    ],
    "Resource": ["arn:aws:sqs:*:123456789012:queue1"],
    "Condition": {
      "DateGreaterThan": {"aws:CurrentTime": "2014-11-30T12:00Z"},
      "DateLessThan": {"aws:CurrentTime": "2014-11-30T15:00Z"}
    }
  }
}
```

------

帳戶 B 向帳戶 B 中的組委託存取許可的政策可能類似於以下範例。帳戶 B 使用 IAM 將此政策連接到群組 (或使用者)。

------
#### [ JSON ]

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": {
    "Effect": "Allow",
    "Action": "sqs:*",
    "Resource": "arn:aws:sqs:*:123456789012:queue1"
  }
}
```

------

在前述 IAM 使用者政策範例中，帳戶 B 使用萬用字元授權其使用者存取針對帳戶 A 的佇列的所有 Amazon SQS 操作。但是帳戶 B 可委託的範圍僅限於帳戶 B 被授權存取的範圍。擁有第二個政策的帳戶 B 群組只能在 2014 年 11 月 30 日中午至下午 3:00 之間存取該佇列。根據帳戶 A 的 Amazon SQS 佇列政策的定義，使用者只能執行 `SendMessage` 與 `ReceiveMessage` 操作。

## 當拒絕存取帳戶時，不得委託存取
<a name="example-delegate-xaccount-SQS-denied"></a>

如果另一個帳戶明確拒絕存取使用者的父帳戶，則 AWS 帳戶 無法將存取權委派給另一個帳戶的 資源。拒絕將傳播到該帳戶內的所有使用者，無論使用者的現有政策是否授予這些使用者存取許可。

例如，帳戶 A 編寫了一個針對其帳戶中 S3 儲存貯體的儲存貯體政策，其中明確拒絕了帳戶 B 存取帳戶 A 的儲存貯體。但帳戶 B 編寫了一個 IAM 使用者政策，其中對帳戶 B 中的一個使用者授予了對帳戶 A 的儲存貯體的存取權限。應用於帳戶 A 的 S3 儲存貯體的「明確拒絕」將傳播到帳戶 B 中的使用者。它會覆蓋用於對帳戶 B 中使用者授予存取權限的 IAM 使用者政策 (有關如何計算許可的詳細資訊，請參閱 [政策評估邏輯](reference_policies_evaluation-logic.md))。

帳戶 A 的儲存貯體政策可能與下列政策類似。在本範例中，帳戶 A 的 S3 儲存貯體的名稱為 *amzn-s3-demo-bucket*，而帳戶 B 的帳戶號碼為 1111-2222-3333。帳戶 A 使用 Amazon S3 執行此政策。

------
#### [ JSON ]

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": {
    "Sid": "AccountBDeny",
    "Effect": "Deny",
    "Principal": {"AWS": "111122223333"},
    "Action": "s3:*",
    "Resource": "arn:aws:s3:::amzn-s3-demo-bucket/*"
  }
}
```

------

此「明確拒絕」將覆蓋帳戶 B 中所有提供帳戶 A 中 S3 儲存貯體存取許可的政策。

# IAM 角色管理
<a name="id_roles_manage"></a>

在使用者、應用程式或服務可以使用您建立的角色之前，您必須授予切換到該角色的許可。您可以使用連接至群組或使用者的任何政策，來授予必要的許可。本節說明如何授予使用者使用角色的許可。它還說明使用者如何從 AWS 管理主控台、Tools for Windows PowerShell、 AWS Command Line Interface (AWS CLI) 和 [https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) API 切換到角色。

**重要**  
當您以程式設計方式而不是在 IAM 主控台中建立角色時，則除了 `RoleName` 之外，您還可以選擇新增高達 512 個字元的 `Path`，該字元長度最多 64 個字元。不過，如果您想要在 中使用具有**切換角色**功能的角色 AWS 管理主控台，則合併的 `Path`和 `RoleName`不得超過 64 個字元。

**Topics**
+ [檢視角色存取](#roles-modify_prerequisites)
+ [根據存取資訊產生政策](#roles-modify_gen-policy)
+ [向使用者授予切換角色的許可](id_roles_use_permissions-to-switch.md)
+ [授予使用者將角色傳遞至 AWS 服務的許可](id_roles_use_passrole.md)
+ [撤銷 IAM 角色臨時安全憑證](id_roles_use_revoke-sessions.md)
+ [更新服務連結角色](id_roles_update-service-linked-role.md)
+ [更新角色信任政策](id_roles_update-role-trust-policy.md)
+ [更新角色的許可](id_roles_update-role-permissions.md)
+ [更新角色的設定](id_roles_update-role-settings.md)
+ [刪除角色或執行個體設定檔](id_roles_manage_delete.md)

## 檢視角色存取
<a name="roles-modify_prerequisites"></a>

變更角色的許可之前，您應該檢閱其最近的服務層級活動。這很重要，因為您不希望從正在使用該許可的主體 (人員或應用程式) 中移除存取。如需有關檢視上次存取的資訊的詳細資訊，請參閱 [AWS 使用上次存取的資訊在 中精簡許可](access_policies_last-accessed.md)。

## 根據存取資訊產生政策
<a name="roles-modify_gen-policy"></a>

您有時可能會對 IAM 實體 (使用者或角色) 授予超出其要求的許可。為了協助您精簡所授予的許可，您可以根據實體的存取活動產生 IAM 政策。IAM Access Analyzer 會檢閱您的 AWS CloudTrail 日誌，並產生政策範本，其中包含實體在指定日期範圍內已使用的許可。您可以使用範本建立具有精細許可的受管政策，然後將其連接至 IAM 實體。如此一來，您只會授予使用者或角色與特定使用案例 AWS 的資源互動所需的許可。若要進一步了解，請參閱 [IAM Access Analyzer 政策產生](https://docs.aws.amazon.com/IAM/latest/UserGuide/access-analyzer-policy-generation.html)。

# 向使用者授予切換角色的許可
<a name="id_roles_use_permissions-to-switch"></a>

當管理員[建立用於跨帳戶存取的角色](id_roles_create_for-user.md)時，他們會在擁有角色和資源的帳戶 (信任帳戶) 和包含使用者的帳戶 (可信帳戶) 之間建立信任。若要執行此操作，信任帳戶的系統管理員要在角色的信任政策中將可信的帳戶編號指定為 `Principal`。這*可能*會允許可信帳戶中的任何使用者擔任該角色。要完成設定，信任帳戶的管理員必須為該帳戶中的特定群組或使用者提供切換到該角色的許可。

**要授予許可以切換到角色**

1. 身為可信帳戶的管理員，請為使用者建立新政策，或編輯現有政策來新增必要元素。如需詳細資訊，請參閱[建立或編輯政策](#roles-usingrole-createpolicy)。

1. 然後，選擇您想要如何共享角色資訊：
   + **角色連結：**向使用者傳送連結，讓他們進入已填寫所有詳細資訊的 **Switch Role** (切換角色) 頁面。
   + **帳戶 ID 或別名：**為每個使用者提供角色名稱以及帳戶 ID 號碼或帳戶別名。使用者接著前往 **Switch Role (切換角色)** 頁面，然後手動新增詳細資訊。

   如需詳細資訊，請參閱[提供資訊給使用者](#roles-usingrole-giveuser)。

請注意，只有當您做為 IAM 使用者、SAML 聯合角色或 Web 聯合身分角色登入時，才能切換角色。如果您以 AWS 帳戶根使用者登入，則無法切換角色。

**重要**  
您無法將 中的角色切換 AWS 管理主控台 為需要 [ExternalId](id_roles_common-scenarios_third-party.md#id_roles_third-party_external-id) 值的角色。您只能透過呼叫支援 `ExternalId` 參數的 [https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) API 來切換到此類角色。

**備註**  
本主題討論*使用者*的政策，因為您最終會向使用者授予完成任務的許可。不過，我們不建議您直接向個別使用者授予許可。當使用者擔任角色時，他們會被指派得到與該角色關聯的許可。
當您在 中切換角色時 AWS 管理主控台，主控台一律會使用您的原始登入資料來授權切換。無論您作為 IAM 使用者、SAML 聯合角色還是 Web 聯合身分角色登入，上述情形均適用。例如，如果您切換到 RoleA，IAM 會使用您的原始使用者或聯合角色憑證確定是否允許您擔任 RoleA。如果您*在使用 RoleA 時*嘗試切換到 RoleB，仍會使用您的**原始**使用者或聯合身分角色憑證對您切換到 RoleB 的嘗試進行授權。RoleA 的憑證不會用於此動作。

**Topics**
+ [建立或編輯政策](#roles-usingrole-createpolicy)
+ [提供資訊給使用者](#roles-usingrole-giveuser)

## 建立或編輯政策
<a name="roles-usingrole-createpolicy"></a>

授予使用者擔任角色的許可政策必須包含在下列項目中擁有 `Allow` 效果的陳述式：
+ `sts:AssumeRole` 動作
+ 在 `Resource` 元素中的角色的 Amazon Resource Name (ARN)。

取得政策的使用者被允許在所列資源上切換角色 (無論是透過群組成員還是直接連接)。

**注意**  
如果 `Resource` 已設定為 `*`，則使用者可以在信任使用者帳戶的任何帳戶中擔任任何角色。(換句話說，角色的信任政策會將使用者的帳戶指定為 `Principal`)。最佳實務是建議您遵循[最低權限原則](http://en.wikipedia.org/wiki/Principle_of_least_privilege)，並且僅為使用者所需的角色指定完整的 ARN。

以下範例顯示一個政策，該政策僅允許使用者擔任一個帳戶中的角色。此外，政策使用萬用字元 (\$1) 指定，如果角色名稱以字元 `Test` 開頭並後跟任何其他字元組合，則使用者只能切換到該帳戶中的角色。

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": {
        "Effect": "Allow",
        "Action": "sts:AssumeRole",
        "Resource": "arn:aws:iam::111122223333:role/Test*"
    }
}
```

------

**注意**  
角色向使用者授予的許可不會新增到使用者已獲得的許可。當使用者切換到某個角色時，使用者可臨時放棄其原始許可以換取由該角色授予的許可。使用者退出該角色時，將自動恢復原始使用者許可。例如，如果使用者的許可允許使用 Amazon EC2 執行個體，但是角色的許可政策未授予這些許可。在這種情況下，在使用角色的同時，使用者不能使用在主控台中的 Amazon EC2 執行個體。此外，透過 `AssumeRole` 取得的暫時憑證不可透過程式設計方式使用 Amazon EC2 執行個體。

## 提供資訊給使用者
<a name="roles-usingrole-giveuser"></a>

建立一個角色並向使用者授予切換為該角色的許可後，您必須提供使用者下列項目：
+ 角色的名稱
+ 包含角色的帳戶 ID 或別名

您可以向使用者發送使用帳戶 ID 和角色名稱預先配置的連結，以簡化他們的存取操作。完成**建立角色**精靈後，您可以選取**檢視角色**橫幅，或在任何跨帳戶啟用之角色的**角色摘要**頁面上查看角色連結。

您還可使用以下格式來手動建構連結。請用您的帳戶 ID 或別名及角色名稱來替換下列範例中的兩個參數：

`https://signin.aws.amazon.com/switchrole?account=your_account_ID_or_alias&roleName=optional_path/role_name`

我們建議您將使用者導向到 [從使用者切換至 IAM 角色 (主控台)](id_roles_use_switch-role-console.md)，以便向他們演練該過程。若要排除您在擔任角色時可能遇到的常見問題，請參閱 [我無法擔任角色](troubleshoot_roles.md#troubleshoot_roles_cant-assume-role)。

**考量事項**
+ 如果您以程式設計方式建立角色，則可使用路徑以及名稱來建立角色。如果您這麼做，則必須為您的使用者提供完整的路徑和角色名稱以便在 AWS 管理主控台的 **Switch Role** (切換角色) 頁面上輸入。例如：`division_abc/subdivision_efg/role_XYZ`。
+ 如果您以程式設計方式建立角色，則除了 `RoleName` 外，您還可以新增最長 512 個字元的 `Path`。角色名稱長度上限為 64 個字元。不過，若要搭配 中的**切換角色**功能使用角色 AWS 管理主控台，合併 `Path`和 `RoleName`不得超過 64 個字元。
+ 基於安全考量，您可以[檢閱 AWS CloudTrail 日誌](cloudtrail-integration.md#cloudtrail-integration_signin-tempcreds)，以了解在其中執行動作的人員 AWS。您可以使用角色信任政策中的 `sts:SourceIdentity` 條件金鑰，請求使用者在擔任角色時指定身分。例如，您可以請求 IAM 使用者將自己的使用者名稱指定為其來源身分。這可以協助您判斷哪位使用者在 AWS中執行了特定動作。如需詳細資訊，請參閱[`sts:SourceIdentity`](reference_policies_iam-condition-keys.md#ck_sourceidentity)。您亦可以使用 [`sts:RoleSessionName`](reference_policies_iam-condition-keys.md#ck_rolesessionname)，請求使用者在擔任角色時指定工作階段名稱。當不同的主體使用角色時，這可協助您區分角色工作階段。

# 授予使用者將角色傳遞至 AWS 服務的許可
<a name="id_roles_use_passrole"></a>

若要設定許多 AWS 服務，您必須將 IAM 角色*傳遞*給服務。這樣可讓該服務擔任該角色，並代表您執行動作。對於大多數服務，您只需在設定期間將角色傳遞服務一次，該服務不需要每次都要擔任角色。例如，假設您的應用程式正在 Amazon EC2 執行個體上執行。該應用程式需要暫時性憑證進行身分驗證，需要許可來授權應用程式在 AWS中執行動作。當設定應用程式時，您必須將角色傳遞到 Amazon EC2，與提供使些憑證的執行個體搭配使用。您為在執行個體上執行的應用程式定義許可，做法是將 IAM 政策連接到角色。應用程式在每次需要時擔任該角色，並在角色允許下執行動作。

若要將角色 （及其許可） 傳遞給 AWS 服務，使用者必須具有*將角色傳遞*給 服務的許可。這可幫助管理員確定只有核准的使用者可以透過授予許可的角色來設定服務。若要允許使用者將角色傳遞至 AWS 服務，您必須將 `PassRole` 許可授予使用者的 IAM 使用者、角色或群組。

**警告**  
您只能使用 `PassRole`許可將 IAM 角色傳遞至共用相同 AWS 帳戶的服務。若要將帳戶 A 中的角色傳遞給帳戶 B 中的服務，您必須先在帳戶 B 中建立可從帳戶 A 擔任該角色的 IAM 角色，接著帳戶 B 中的角色才可以傳遞至該服務。如需詳細資訊，請參閱[IAM 中的跨帳戶資源存取](access_policies-cross-account-resource-access.md)。
請勿嘗試透過標記角色，然後使用政策中的 `ResourceTag` 條件金鑰搭配 `iam:PassRole` 動作來控制誰可以傳遞角色。這種方法所產生的結果並不可靠。

設定 `PassRole` 許可時，您應確保使用者傳遞的角色不會具有比您希望使用者具有之許可更多的許可。例如，可能不允許 Alice 執行任何 Amazon S3 動作。如果 Alice 可以將角色傳遞給允許 Amazon S3 動作的服務，則該服務可以在執行任務時代表 Alice 執行 Amazon S3 動作。

當您指定服務連結角色時，您也必須擁有將該角色傳遞到服務的許可。有些服務會自動在您在該服務中執行動作時，在您的帳戶中建立服務連結角色。例如，Amazon EC2 Auto Scaling 會在您第一次建立 Auto Scaling 群組時，為您建立 `AWSServiceRoleForAutoScaling` 服務連結角色。如果您在建立 Auto Scaling 群組時，嘗試指定服務連結角色並且您沒有 `iam:PassRole` 許可，則會收到錯誤。如果您沒有明確指定角色，則不需要 `iam:PassRole` 許可，預設情況下，對該群組執行的所有操作都使用 `AWSServiceRoleForAutoScaling` 角色。若要了解哪些服務支援服務連結角色，請參閱 [AWS 使用 IAM 的 服務](reference_aws-services-that-work-with-iam.md)。若要了解哪些服務在您於服務中執行動作時會自動建立服務連結角色，請選擇 **Yes (是)** 連結，並檢視該服務的服務連結角色文件。

使用者可以在任何 API 操作中，以參數方式傳遞角色 ARN，而該操作便是使用角色將許可指派給服務。然後，該服務會檢查該使用者是否擁有 `iam:PassRole` 許可。若要限制使用者只傳遞核准的角色，您可以使用 IAM 政策陳述式的 `Resources` 元素來篩選 `iam:PassRole` 許可。

您可以使用 JSON 政策中的 `Condition`元素來測試包含在所有請求請求內容中的金鑰值 AWS 。若要進一步了解如何在政策中使用條件索引鍵，請參閱 [IAM JSON 政策元素：Condition](reference_policies_elements_condition.md)。`iam:PassedToService` 條件索引鍵可用來指定能傳遞角色之服務的服務主體。若要進一步了解如何在政策中使用 `iam:PassedToService` 條件金鑰，請參閱 [iam:PassedToService](reference_policies_iam-condition-keys.md#ck_PassedToService)。

**範例 1**  
假設您想要授予使用者在啟動執行個體時，能夠將任何已核准的一組角色傳遞到 Amazon EC2 服務。您需要三種元素：
+ 連接到角色的 IAM *許可政策*，其決定角色可以做什麼。將許可侷限在角色必須執行的動作，以及角色針對那些動作所需的資源。您可以使用 AWS 受管或客戶建立的 IAM 許可政策。

------
#### [ JSON ]

****  

  ```
  {
      "Version":"2012-10-17",		 	 	 
      "Statement": {
          "Effect": "Allow",
          "Action": [ "A list of the permissions the role is allowed to use" ],
          "Resource": [ "A list of the resources the role is allowed to access" ]
      }
  }
  ```

------
+ 角色的「信任政策」**，其允許服務擔任角色。例如，您可以將以下信任政策連接到角色及 `UpdateAssumeRolePolicy` 動作。此信任政策可讓 Amazon EC2 使用角色和連接到該角色的許可。

------
#### [ JSON ]

****  

  ```
  {
      "Version":"2012-10-17",		 	 	 
      "Statement": {
          "Sid": "TrustPolicyStatementThatAllowsEC2ServiceToAssumeTheAttachedRole",
          "Effect": "Allow",
          "Principal": { "Service": "ec2.amazonaws.com" },
         "Action": "sts:AssumeRole"
      }
  }
  ```

------
+ 連接到 IAM 使用者的 IAM *許可政策*，其允許使用者僅傳遞已核准的角色。通常是將 `iam:GetRole` 新增至 `iam:PassRole`，讓使用者可以取得要傳遞之角色的詳細資訊。在這個範例中，使用者可以僅傳遞存在於指定的帳戶，名稱開頭為 `EC2-roles-for-XYZ-` 的角色：

------
#### [ JSON ]

****  

  ```
  {
      "Version":"2012-10-17",		 	 	 
      "Statement": [
          {
              "Effect": "Allow",
              "Action": [
                  "iam:GetRole",
                  "iam:PassRole"
              ],
              "Resource": "arn:aws:iam::111122223333:role/EC2-roles-for-XYZ-*"
          }
      ]
  }
  ```

------

現在，使用者可以使用已指派的角色來啟動 Amazon EC2 執行個體。在執行個體上執行的應用程式，可透過執行個體設定檔中繼資料來存取角色的暫時性憑證。連接到該角色的許可政策決定了執行個體可以執行哪些操作。

**範例 2**  
Amazon Relational Database Service (Amazon RDS) 支援**增強型監控**功能。此功能可讓 Amazon RDS 使用代理程式來監控資料庫執行個體。同時也允許 Amazon RDS 將指標記錄到 Amazon CloudWatch Logs。若要啟用此功能，您必須建立服務角色以提供 Amazon RDS 許可來監控和寫入指標到您的日誌。

**為 Amazon RDS 增強型監控建立角色**

1. 登入 AWS 管理主控台 ，並在 https：//[https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/) 開啟 IAM 主控台。

1. 選擇 **Roles (角色)**，然後選擇 **Create role (建立角色)**。

1. 選擇**AWS 服務**角色類型，然後針對**其他 的使用案例 AWS 服務**，選擇 **RDS** 服務。選擇 **RDS – Enhanced Monitoring** (RDS – 增強型監控)，然後選擇 **Next** (下一步)。

1. 選擇 **AmazonRDSEnhancedMonitoringRole** 許可政策。

1. 選擇**下一步**。

1. 針對 **Role name** (角色名稱)，輸入可協助您識別此角色用途的角色名稱。角色名稱在您的 中必須是唯一的 AWS 帳戶。角色名稱用在政策中或作為 ARN 的一部分時，角色名稱區分大小寫。當主控台中的客戶顯示角色名稱時 (例如在登入程序期間)，角色名稱不區分大小寫。因為有各種實體可能會參考此角色，所以建立角色之後，您就無法編輯其名稱。

1. (選用) 在 **Description** (說明) 中，輸入新角色的說明。

1. (選用) 藉由連接標籤作為鍵值對，將中繼資料新增至使用者。如需有關在 IAM 中使用標籤的詳細資訊，請參閱 [AWS Identity and Access Management 資源的標籤](id_tags.md)。

1. 檢閱角色，然後選擇 **Create role** (建立角色)。

角色會自動取得信任政策，授予 `monitoring.rds.amazonaws.com` 服務許可以擔任角色。在那之後，Amazon RDS 可以執行 `AmazonRDSEnhancedMonitoringRole` 政策允許的所有動作。

您想要存取增強型監控的使用者需要的政策是包含一個可讓使用者列出 RDS 角色的陳述式，以及傳遞角色的陳述式，如下所示。使用您的帳號並將角色名稱取代為您在步驟 6 提供的名稱。

```
    {
      "Sid": "PolicyStatementToAllowUserToListRoles",
      "Effect": "Allow",
      "Action": ["iam:ListRoles"],
      "Resource": "*"
    },
    {
        "Sid": "PolicyStatementToAllowUserToPassOneSpecificRole",
        "Effect": "Allow",
        "Action": [ "iam:PassRole" ],
        "Resource": "arn:aws:iam::account-id:role/RDS-Monitoring-Role"
    }
```

您可以將此陳述式與在另一個政策中的陳述式併在一起，或是將它放在它自己的政策中。若要改為指定使用者可以傳遞任何開頭為 `RDS-` 的角色，您可以將資源 ARN 中的角色名稱取代為萬用字元，如下所示。

```
        "Resource": "arn:aws:iam::account-id:role/RDS-*"
```

## `iam:PassRole` AWS CloudTrail 日誌中的 動作
<a name="id_roles_use_passrole_logs"></a>

 `PassRole` 不是 API 呼叫。`PassRole` 是一項許可，表示沒有為 IAM `PassRole` 產生 CloudTrail 日誌。若要檢閱在 CloudTrail AWS 服務 中傳遞哪些角色，您必須檢閱建立或修改接收角色之 AWS 資源的 CloudTrail 日誌。例如，角色會在建立時傳遞至 AWS Lambda 函數。`CreateFunction` 動作的日誌顯示有關被傳遞到函數之角色的記錄。

# 撤銷 IAM 角色臨時安全憑證
<a name="id_roles_use_revoke-sessions"></a>

**警告**  
如果您遵循此頁面上的步驟，則擔任角色所建立目前工作階段的所有使用者都會被拒絕存取所有 AWS 動作和資源。這會導致使用者遺失未儲存的工作。

當您允許使用者 AWS 管理主控台 以較長的工作階段持續時間 （例如 12 小時） 存取 時，其暫時登入資料不會快速過期。如果使用者不慎將他們的憑證向未經授權的第三方公開，該方在工作階段的持續時間均有權存取。不過，您可以立即撤銷所有在某個時間點前授予該角色的憑證許可，如果需要的話。該角色在指定時間點前發出的所有暫時性憑證變成無效。這會強迫所有使用者重新驗證和請求新的憑證。

 

**注意**  
您無法撤銷[服務連結角色](id_roles.md#iam-term-service-linked-role)**的工作階段。

當您使用此主題中的程序撤銷角色的許可時， 會將新的內嵌政策 AWS 連接到拒絕所有動作的所有許可的角色。如果使用者在您撤銷許可的時間點「之前」**擔任該角色，則它只會包含套用限制條件的情況。如果使用者在撤銷許可「之後」**擔任該角色，則拒絕政策不會套用至該使用者。

如需拒絕存取的詳細資訊，請參閱 [停用臨時安全性憑證的許可](id_credentials_temp_control-access_disable-perms.md)。

**重要**  
此拒絕政策適用於指定角色的所有使用者，而不只是具主控台工作階段較長持續時間的角色。

## 從角色撤銷工作階段許可的最低許可
<a name="revoke-session-permissions"></a>

若要從角色成功地撤銷工作階段許可，您必須擁有該角色的 `PutRolePolicy` 許可。這可讓您將 `AWSRevokeOlderSessions` 內嵌政策連接至該角色。

## 撤銷工作階段許可
<a name="revoke-session"></a>

您可以從角色撤銷工作階段許可，以拒絕擔任該角色之任何使用者的所有許可。

**注意**  
您無法在 IAM 中編輯從 IAM Identity Center 許可集建立的角色。您必須撤銷 IAM Identity Center 中使用者的作用中許可集工作階段。如需詳細資訊，請參閱 *IAM Identity Center User Guide* 中的 [Revoke active IAM role sessions created by permission sets](https://docs.aws.amazon.com/singlesignon/latest/userguide/useraccess.html#revoke-user-permissions)。

**立即拒絕對任何目前使用者的角色憑證的所有許可**

1. 登入 AWS 管理主控台 ，並在 https：//[https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/) 開啟 IAM 主控台。

1. 在導覽窗格中，選擇**角色**，然後選擇您想要撤銷其許可的角色名稱 (不是核取方塊)。

1. 在所選取角色的 **Summary (摘要)** 頁面上，選擇 **Revoke sessions (工作階段)** 標籤。

1. 在 **Revoke sessions (撤銷工作階段)** 標籤上，選擇 **Revoke active sessions (撤銷作用中的工作階段)**。

1. AWS 會要求您確認動作。選取**我確認我將撤銷此角色的所有作用中工作階段。**核取方塊，然後在對話方塊中選擇**撤銷作用中工作階段**。

   然後，IAM 將名為 `AWSRevokeOlderSessions` 的政策連接至角色。在您選擇**撤銷作用中工作階段**後，政策會拒絕過去以及未來約 30 秒內擔任該角色的使用者的所有存取權。此未來時間選擇考量政策的傳播延遲，以便處理在更新的政策在指定區域中生效之前取得或續約的新工作階段。在您選擇「撤銷作用中的工作階段」後，擔任該角色超過大約 30 秒的任何使用者都不會受影響。若要了解變更不一定會立即顯示的原因，請參閱 [我所做的變更不一定都會立刻生效](troubleshoot.md#troubleshoot_general_eventual-consistency)。

**注意**  
如果您稍後再次選擇**撤銷工作階段**，則會重新整理政策中的日期和時間戳記，而且它會再次拒絕在新指定的時間之前擔任該角色之任何使用者的許可。

以這種方式呼叫工作階段的有效使用者必須獲得臨時憑證，新工作階段才能繼續運作。會 AWS CLI 快取登入資料，直到過期為止。若要強制 CLI 刪除並重新整理已失效的快取憑證，請執行以下命令之一：

**Linux、macOS 或 Unix**

```
$ rm -r ~/.aws/cli/cache
```

**Windows**

```
C:\> del /s /q %UserProfile%\.aws\cli\cache
```

## 在指定時間之前撤銷工作階段許可
<a name="revoke-session-policy"></a>

 您也可以使用 AWS CLI 或 SDK 隨時撤銷您選擇的工作階段許可，在政策的條件元素中指定`aws:TokenIssueTime`金鑰的值。

在 `aws:TokenIssueTime` 的值早於指定的日期和時間時，此政策會拒絕所有許可。`aws:TokenIssueTime` 的值對應於臨時安全性憑證的確切建立時間。該`aws:TokenIssueTime`值僅存在於使用臨時安全登入資料簽署的 AWS 請求內容中，因此政策中的拒絕陳述式不會影響使用 IAM 使用者的長期登入資料簽署的請求。

此政策也可連接至角色。在這種情況下，該政策只會影響由該角色在指定日期和時間之前建立的臨時安全性憑證。

------
#### [ JSON ]

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": {
    "Effect": "Deny",
    "Action": "*",
    "Resource": "*",
    "Condition": {
      "DateLessThan": {"aws:TokenIssueTime": "2014-05-07T23:47:00Z"}
    }
  }
}
```

------

以這種方式呼叫工作階段的有效使用者必須獲得臨時憑證，新工作階段才能繼續運作。會 AWS CLI 快取登入資料，直到過期為止。若要強制 CLI 刪除並重新整理已失效的快取憑證，請執行以下命令之一：

**Linux、macOS 或 Unix**

```
$ rm -r ~/.aws/cli/cache
```

**Windows**

```
C:\> del /s /q %UserProfile%\.aws\cli\cache
```

# 更新服務連結角色
<a name="id_roles_update-service-linked-role"></a>

您用來編輯服務連結角色的方法取決於服務。有些服務也許可讓您從服務主控台、API 或 CLI 編輯服務連結角色的許可。不過，因為有各種實體可能會參考服務連結角色，所以您無法在建立角色之後變更角色名稱。您可以從 IAM 主控台、API 或 CLI 編輯任何角色的說明。

如需哪些服務支援使用服務連結角色的資訊，請參閱 [AWS 使用 IAM 的 服務](reference_aws-services-that-work-with-iam.md)，並尋找 **Service-Linked Role (服務連結角色)** 欄中顯示 **Yes (是)** 的服務。若要了解服務是否支援編輯服務連結角色，請選擇**是**連結以檢視該服務的服務連結角色的文件。

## 編輯服務連結角色描述 (主控台)
<a name="edit-service-linked-role-iam-console"></a>

您可以使用 IAM 主控台來編輯服務連結角色的說明。

**編輯服務連結角色的說明 (主控台)**

1. 在 IAM 主控台的導覽窗格中，選擇 **Roles** (角色)。

1. 選擇要修改之角色的名稱。

1. 在 **Role description** (角色說明) 的最右邊，選擇 **Edit** (編輯)。

1. 在方塊中輸入新的描述，然後選擇 **Save (儲存)**。

## 編輯服務連結角色描述 (AWS CLI)
<a name="edit-service-linked-role-iam-cli"></a>

您可以使用 的 IAM 命令 AWS CLI 來編輯服務連結角色的描述。

**變更服務連結角色的說明 (AWS CLI)**

1. (選用) 若要檢視角色的目前說明，請執行下列命令：

   ```
   aws iam [get-role](https://docs.aws.amazon.com/cli/latest/reference/iam/get-role.html) --role-name ROLE-NAME
   ```

   透過 CLI 命令，使用角色名稱 (而非 ARN) 來參照角色。例如，如果角色具有下列 ARN：`arn:aws:iam::123456789012:role/myrole`，請將角色參照為 **myrole**。

1. 若要更新服務連結角色的說明，請執行下列命令：

   ```
   aws iam [update-role](https://docs.aws.amazon.com/cli/latest/reference/iam/update-role.html) --role-name ROLE-NAME --description OPTIONAL-DESCRIPTION
   ```

## 編輯服務連結角色描述 (AWS API)
<a name="edit-service-linked-role-iam-api"></a>

您可以使用 AWS API 編輯服務連結角色的描述。

**變更服務連結角色 (AWS API) 的描述**

1. (選用) 若要檢視角色的目前說明，請呼叫以下操作並指定角色的名稱：

   AWS API：[GetRole](https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetRole.html) 

1. (選用) 若要更新角色的說明，請呼叫以下操作並指定角色的名稱 (和選用描述)：

   AWS API：[UpdateRole](https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateRole.html) 

# 更新角色信任政策
<a name="id_roles_update-role-trust-policy"></a>

若要變更誰可擔任該角色，您必須修改角色的信任政策。您無法修改[服務連結角色](id_roles.md#iam-term-service-linked-role)**的信任政策。

**備註**  
如果使用者已於角色信任政策中列為主體，卻無法擔任該角色，請檢查該使用者的[許可界限](access_policies_boundaries.md)。如果已經設定使用者的許可界限，則其必須允許 `sts:AssumeRole` 動作。
若要允許使用者在角色工作階段中再次擔任目前角色，請在角色信任政策中將角色 ARN 或 AWS 帳戶 ARN 指定為主體。 AWS 服務 提供運算資源，例如 Amazon EC2、Amazon ECS、Amazon EKS 和 Lambda，可提供臨時登入資料並自動更新這些登入資料。此可確保您始終擁有一組有效的憑證。對於這些服務，不需要再次擔任目前的角色即可取得臨時憑證。但是，如果您想要傳遞[工作階段標籤](id_session-tags.md)或一個[工作階段政策](access_policies.md#policies_session)，則需要再次擔任目前的角色。


## 更新角色信任政策 (主控台)
<a name="id_roles_update-trust-policy-console"></a>

**在 中變更角色信任政策 AWS 管理主控台**

1. 登入 AWS 管理主控台 ，並在 https：//[https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/) 開啟 IAM 主控台。

1. 在 IAM 主控台的導覽窗格中，選擇 **Roles** (角色)。

1. 在您帳戶的角色清單中，選擇您想要修改的角色名稱。

1. 選擇 **Trust Relationships** (信任關係) 標籤，然後選擇 **Edit Trust Relationship** (編輯信任政策)。

1. 視需要編輯信任政策。若要新增其他可擔任該角色的主體，請在 `Principal` 元素中指定它們。例如，下列政策程式碼片段示範如何在 `Principal`元素 AWS 帳戶 中參考兩個：

   ```
   "Principal": {
     "AWS": [
       "arn:aws:iam::111122223333:root",
       "arn:aws:iam::444455556666:root"
     ]
   },
   ```

   如果您指定在另一個帳戶中的主體，這時在角色的信任政策中新增帳戶，只能建立一半的跨帳戶信任關係。根據預設，信任帳戶中沒有任何使用者可擔任該角色。剛信任的帳戶管理員必須授予新的使用者擔任該角色的許可。為了這樣做，管理員必須建立或編輯連接於使用者的政策，以允許使用者存取 `sts:AssumeRole` 動作。如需詳細資訊，請參閱下列程序或 [向使用者授予切換角色的許可](id_roles_use_permissions-to-switch.md)。

   下列政策程式碼片段示範如何在 `Principal`元素中參考兩項 AWS 服務：

   ```
   "Principal": {
     "Service": [
       "opsworks.amazonaws.com",
       "ec2.amazonaws.com"
     ]
   },
   ```

1. 當您完成編輯您的信任政策，請選擇 **Update policy** (更新政策) 來儲存您的變更。

   如需有關政策結構和語法的詳細資訊，請參閱 [中的政策和許可 AWS Identity and Access Management](access_policies.md) 和 [IAM JSON 政策元素參考](reference_policies_elements.md)。

**允許信任外部帳戶中的使用者使用該角色 (主控台)**

如需有關此程序的更多資訊和詳細資訊，請參閱 [向使用者授予切換角色的許可](id_roles_use_permissions-to-switch.md)。

1. 登入受信任的外部 AWS 帳戶。

1. 決定是否將許可連接到使用者或群組。在 IAM 主控台的導覽窗格中，相應地選擇 **Users** (使用者) 或 **User groups** (使用者群組)。

1. 選擇要授予其存取許可的使用者或群組的名稱，然後選擇 **Permissions (許可)** 標籤。

1. 執行下列任一步驟：
   + 若要編輯客戶受管政策，請選擇政策名稱，並選擇 **Edit policy (編輯政策)**，然後選擇 **JSON** 標籤。您無法編輯具有 AWS 圖示 (![\[Orange cube icon indicating a policy is managed by AWS.\]](http://docs.aws.amazon.com/zh_tw/IAM/latest/UserGuide/images/policy_icon.png)) 的 受 AWS 管 AWS 政策。如需有關 AWS 受管政策與客戶受管政策之間差異的詳細資訊，請參閱 [受管政策與內嵌政策](access_policies_managed-vs-inline.md)。
   + 若要編輯內嵌政策，請選擇政策名稱旁的箭頭，然後選擇 **Edit policy (編輯政策)**。

1. 在政策編輯器中，新增一個指定以下內容的新 `Statement` 元素：

   ```
   {
     "Effect": "Allow",
     "Action": "sts:AssumeRole",
     "Resource": "arn:aws:iam::ACCOUNT-ID:role/ROLE-NAME"
   }
   ```

   將陳述式中的 ARN 取代為使用者可擔任的角色的 ARN。

1. 按照螢幕上的提示來完成政策編輯。

## 更新角色信任政策 (AWS CLI)
<a name="id_roles-update-trust-policy-cli"></a>

您可以使用 AWS CLI 來變更誰可以擔任角色。

**修改角色信任政策 (AWS CLI)**

1. (選用) 如果您不知道要修改的角色的名稱，請執行以下命令列出您帳戶中的角色：
   + [aws iam list-roles](https://docs.aws.amazon.com/cli/latest/reference/iam/list-roles.html)

1. (選用) 若要檢視角色的目前信任政策，請執行下列命令：
   + [aws iam get-role](https://docs.aws.amazon.com/cli/latest/reference/iam/get-role.html)

1. 若要修改可以存取角色的信任主體，請使用更新的信任政策建立文字檔案。您可以使用任何文字編輯器來建構政策。

   例如，下列信任政策顯示如何在 `Principal` 元素中參考兩個 AWS 帳戶 。這可讓兩個不同 內的使用者 AWS 帳戶 擔任此角色。

------
#### [ JSON ]

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": {
           "Effect": "Allow",
           "Principal": {"AWS": [
               "arn:aws:iam::111122223333:root",
               "arn:aws:iam::444455556666:root"
           ]},
           "Action": "sts:AssumeRole"
       }
   }
   ```

------

   如果您指定在另一個帳戶中的主體，這時在角色的信任政策中新增帳戶，只能建立一半的跨帳戶信任關係。根據預設，信任帳戶中沒有任何使用者可擔任該角色。剛信任的帳戶管理員必須授予新的使用者擔任該角色的許可。為了這樣做，管理員必須建立或編輯連接於使用者的政策，以允許使用者存取 `sts:AssumeRole` 動作。如需詳細資訊，請參閱下列程序或 [向使用者授予切換角色的許可](id_roles_use_permissions-to-switch.md)。

1. 若要使用剛建立的檔案更新信任政策，請執行下列命令：
   + [aws iam update-assume-role-policy](https://docs.aws.amazon.com/cli/latest/reference/iam/update-assume-role-policy.html)

**若要允許信任外部帳戶中的使用者使用該角色 (AWS CLI)**

如需有關此程序的更多資訊和詳細資訊，請參閱 [向使用者授予切換角色的許可](id_roles_use_permissions-to-switch.md)。

1. 建立 JSON 檔案，其中包含擔任該角色所需的許可的許可政策。例如，以下政策包含最低必要許可：

------
#### [ JSON ]

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": {
           "Effect": "Allow",
           "Action": "sts:AssumeRole",
           "Resource": "arn:aws:iam::111122223333:role/ROLE-NAME"
       }
   }
   ```

------

   將陳述式中的 ARN 取代為使用者可擔任的角色的 ARN。

1. 執行以下命令以上傳 JSON 檔案 (其中包含的信任政策) 至 IAM：
   + [aws iam create-policy](https://docs.aws.amazon.com/cli/latest/reference/iam/create-policy.html)

   此命令的輸出結果含有該政策的 ARN。記下此 ARN，因為您需要在稍後的步驟中使用。

1. 決定將政策到連接哪位使用者或群組。如果您不知道適用的使用者或群組的名稱，請使用下列其中一個命令來列出帳戶中的使用者或群組：
   + [aws iam list-users](https://docs.aws.amazon.com/cli/latest/reference/iam/list-users.html)
   + [aws iam list-groups](https://docs.aws.amazon.com/cli/latest/reference/iam/list-groups.html)

1. 使用下列命令之一將您在之前的步驟中建立的政策連接到使用者或群組：
   + [aws iam attach-user-policy](https://docs.aws.amazon.com/cli/latest/reference/iam/attach-user-policy.html)
   + [aws iam attach-group-policy](https://docs.aws.amazon.com/cli/latest/reference/iam/attach-group-policy.html)

## 更新角色信任政策 (AWS API)
<a name="id_roles-update-trust-policy-api"></a>

您可以使用 AWS API 來變更誰可以擔任角色。

**修改角色信任政策 (AWS API)**

1. (選用) 如果您不知道要修改的角色的名稱，請呼叫以下操作列出您帳戶中的角色：
   + [ListRoles](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListRoles.html)

1. (選用) 若要檢視角色的目前信任政策，請呼叫下列操作：
   + [GetRole](https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetRole.html)

1. 若要修改可以存取角色的信任主體，請使用更新的信任政策建立文字檔案。您可以使用任何文字編輯器來建構政策。

   例如，下列信任政策顯示如何在 `Principal` 元素中參考兩個 AWS 帳戶 。這可讓兩個不同 內的使用者 AWS 帳戶 擔任此角色。

------
#### [ JSON ]

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": {
           "Effect": "Allow",
           "Principal": {"AWS": [
               "arn:aws:iam::111122223333:root",
               "arn:aws:iam::444455556666:root"
           ]},
           "Action": "sts:AssumeRole"
       }
   }
   ```

------

   如果您指定在另一個帳戶中的主體，這時在角色的信任政策中新增帳戶，只能建立一半的跨帳戶信任關係。根據預設，信任帳戶中沒有任何使用者可擔任該角色。剛信任的帳戶管理員必須授予新的使用者擔任該角色的許可。為了這樣做，管理員必須建立或編輯連接於使用者的政策，以允許使用者存取 `sts:AssumeRole` 動作。如需詳細資訊，請參閱下列程序或 [向使用者授予切換角色的許可](id_roles_use_permissions-to-switch.md)。

1. 若要使用剛建立的檔案更新信任政策，請呼叫下列操作：
   + [UpdateAssumeRolePolicy](https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateAssumeRolePolicy.html)

**允許受信任外部帳戶中的使用者使用該角色 (AWS API)**

如需有關此程序的更多資訊和詳細資訊，請參閱 [向使用者授予切換角色的許可](id_roles_use_permissions-to-switch.md)。

1. 建立 JSON 檔案，其中包含擔任該角色所需的許可的許可政策。例如，以下政策包含最低必要許可：

------
#### [ JSON ]

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": {
           "Effect": "Allow",
           "Action": "sts:AssumeRole",
           "Resource": "arn:aws:iam::111122223333:role/ROLE-NAME"
       }
   }
   ```

------

   將陳述式中的 ARN 取代為使用者可擔任的角色的 ARN。

1. 呼叫以下操作，以上傳 JSON 檔案 (其中包含的信任政策) 至 IAM：
   + [CreatePolicy](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreatePolicy.html)

   此操作的輸出結果含有該政策的 ARN。記下此 ARN，因為您需要在稍後的步驟中使用。

1. 決定將政策到連接哪位使用者或群組。如果您不知道適用的使用者或群組的名稱，請呼叫下列其中一個操作來列出帳戶中的使用者或群組：
   + [ListUsers](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListUsers.html)
   + [ListGroups](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListGroups.html)

1. 呼叫下列操作之一將您在之前的步驟中建立的政策連接到使用者或群組：
   +  API: [AttachUserPolicy](https://docs.aws.amazon.com/IAM/latest/APIReference/API_AttachUserPolicy.html)
   + [AttachGroupPolicy](https://docs.aws.amazon.com/IAM/latest/APIReference/API_AttachGroupPolicy.html)

# 更新角色的許可
<a name="id_roles_update-role-permissions"></a>

使用下列程序來更新角色的許可政策和許可界限。

## 先決條件：檢視角色存取
<a name="roles-modify_prerequisites"></a>

變更角色的許可之前，您應該檢閱其最近的服務層級活動。這很重要，因為您不希望從正在使用該許可的主體 (人員或應用程式) 中移除存取。如需有關檢視上次存取的資訊的詳細資訊，請參閱 [AWS 使用上次存取的資訊在 中精簡許可](access_policies_last-accessed.md)。

## 更新角色的許可政策
<a name="id_roles_update-role-permissions-policy"></a>

若要變更角色允許的許可，請修改角色的許可政策 (或政策)。您無法修改 IAM 中*[服務連結角色](id_roles.md#iam-term-service-linked-role)*的許可政策。您也許可以修改該服務 (取決於角色) 內的許可政策。若要檢查服務是否支援這項功能，請參閱[AWS 使用 IAM 的 服務](reference_aws-services-that-work-with-iam.md)，並且尋找 **Service-linked roles (服務連結的角色)** 資料列為 **Yes (是)** 的服務。選擇具有連結的 **Yes (是)**，以檢視該服務的服務連結角色文件。

### 更新角色許可政策 (主控台)
<a name="id_roles_update-role-permissions-policy-console"></a>

**變更角色允許的許可 (主控台)**

1. 在以下網址開啟 IAM 主控台：[https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/)。

1. 在 IAM 主控台的導覽窗格中，選擇 **Roles** (角色)。

1. 選擇您要修改的角色的名稱，然後選擇 **Permissions (許可)** 標籤。

1. 執行下列任一步驟：
   + 若要編輯現有客戶受管政策，請選擇政策名稱，然後選擇 **Edit policy (編輯政策)**。
**注意**  
您無法編輯具有 AWS 圖示 (![\[Orange cube icon indicating a policy is managed by AWS.\]](http://docs.aws.amazon.com/zh_tw/IAM/latest/UserGuide/images/policy_icon.png)) 的 受 AWS 管 AWS 政策。如需 AWS 受管政策與客戶受管政策之間差異的詳細資訊，請參閱 [受管政策與內嵌政策](access_policies_managed-vs-inline.md)。
   + 若要將現有受管政策連接至角色，請選擇 **Add permissions** (新增許可)，然後選擇 **Attach policies** (連接政策)。
   + 若要編輯現有內嵌政策，請展開政策，然後選擇 **Edit** (編輯)。
   + 若要嵌入新的內嵌政策，請選擇 **Add permissions** (新增許可)，然後選擇 **Create inline policy** (建立內嵌政策)。
   + 若要從角色移除現有政策，請選取政策名稱旁的核取方塊，然後選擇**移除**。

### 更新角色許可政策 (AWS CLI)
<a name="id_roles_update_permissions-policy-cli"></a>

若要變更角色允許的許可，請修改角色的許可政策 (或政策)。您無法修改 IAM 中*[服務連結角色](id_roles.md#iam-term-service-linked-role)*的許可政策。您也許可以修改該服務 (取決於角色) 內的許可政策。若要檢查服務是否支援這項功能，請參閱[AWS 使用 IAM 的 服務](reference_aws-services-that-work-with-iam.md)，並且尋找 **Service-linked roles (服務連結的角色)** 資料列為 **Yes (是)** 的服務。選擇具有連結的 **Yes (是)**，以檢視該服務的服務連結角色文件。

**若要變更角色允許的許可 (AWS CLI)**

1. (選用) 若要檢視與角色關聯的目前許可，請執行下列命令：

   1. [aws iam list-role-policies](https://docs.aws.amazon.com/cli/latest/reference/iam/list-role-policies.html) 列出內嵌政策

   1. [aws iam list-attached-role-policies](https://docs.aws.amazon.com/cli/latest/reference/iam/list-attached-role-policies.html) 列出受管政策

1. 更新角色許可的命令會有所不同，具體取決於您是要更新受管政策還是內嵌政策。

   若要更新受管政策，請執行下列命令來建立新版本的受管政策：
   + [aws iam create-policy-version](https://docs.aws.amazon.com/cli/latest/reference/iam/create-policy-version.html)

   若要更新內嵌政策，請執行下列命令：
   + [aws iam put-role-policy](https://docs.aws.amazon.com/cli/latest/reference/iam/put-role-policy.html)

### 更新角色許可政策 (AWS API)
<a name="id_roles_update_permissions-policy-api"></a>

若要變更角色允許的許可，請修改角色的許可政策 (或政策)。您無法修改 IAM 中*[服務連結角色](id_roles.md#iam-term-service-linked-role)*的許可政策。您也許可以修改該服務 (取決於角色) 內的許可政策。若要檢查服務是否支援這項功能，請參閱[AWS 使用 IAM 的 服務](reference_aws-services-that-work-with-iam.md)，並且尋找 **Service-linked roles (服務連結的角色)** 資料列為 **Yes (是)** 的服務。選擇具有連結的 **Yes (是)**，以檢視該服務的服務連結角色文件。

**變更角色允許的許可 (AWS API)**

1. (選用) 若要檢視與角色關聯的目前許可，請呼叫下列操作：

   1. [ListRolePolicies](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListRolePolicies.html) 列出內嵌政策

   1. [ListAttachedRolePolicies](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListAttachedRolePolicies.html) 列出受管政策

1. 更新角色許可的操作會有所不同，具體取決於您是要更新受管政策還是內嵌政策。

   若要更新受管政策，請呼叫下列操作來建立新版本的受管政策：
   + [CreatePolicyVersion](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreatePolicyVersion.html)

   若要更新內嵌政策，請呼叫下列操作：
   + [PutRolePolicy](https://docs.aws.amazon.com/IAM/latest/APIReference/API_PutRolePolicy.html)

## 更新角色的許可界限
<a name="id_roles_update-role-permissions-boundary"></a>

若要變更角色適用的許可上限，請修改角色的[許可界限](access_policies_boundaries.md)。

### 更新角色許可界限 (主控台)
<a name="id_roles_update-permissions-boundary-console"></a>

**變更用於設定角色許可界限的政策**

1. 登入 AWS 管理主控台 ，並在 https：//[https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/) 開啟 IAM 主控台。

1. 在導覽窗格中，選擇**角色**。

1. 選擇您想要為其變更[許可界限](access_policies_boundaries.md)的角色名稱。

1. 選擇 **Permissions (許可)** 標籤。如有必要，開啟 **許可界限** 區段，然後選擇 **變更界限**。

1. 選擇要用於許可界限的政策。

1. 選擇 **Change boundary (變更界限)**。

   在下次有人擔任此角色之前，您的變更不會生效。

### 更新角色許可界限 (AWS CLI)
<a name="id_roles_update_permissions-boundary-cli"></a>

**變更用於設定角色許可界限的受管政策 (AWS CLI)**

1. (選用) 若要檢視角色的目前[許可界限](access_policies_boundaries.md)，請執行下列命令：
   + [aws iam get-role](https://docs.aws.amazon.com/cli/latest/reference/iam/get-role.html)

1. 若要使用不同的受管政策來更新角色的許可界限，請執行下列命令：
   + [aws iam put-role-permissions-boundary](https://docs.aws.amazon.com/cli/latest/reference/iam/put-role-permissions-boundary.html)

   角色只能有一個受管政策設定為許可界限。您若變更許可界限，您會變更角色適用的許可上限。

### 更新角色許可界限 (AWS API)
<a name="id_roles_update-permissions-boundary-api"></a>

**變更用於設定角色 (AWS API) 許可界限的受管政策**

1. (選用) 若要檢視角色的目前[許可界限](access_policies_boundaries.md)，請呼叫下列操作：
   + [GetRole](https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetRole.html)

1. 若要使用不同的受管政策來更新角色的許可界限，請呼叫下列操作：
   + [PutRolePermissionsBoundary](https://docs.aws.amazon.com/IAM/latest/APIReference/API_PutRolePermissionsBoundary.html)

   角色只能有一個受管政策設定為許可界限。您若變更許可界限，您會變更角色適用的許可上限。

# 更新角色的設定
<a name="id_roles_update-role-settings"></a>

使用下列程序來更新角色的描述，或者，變更角色的工作階段持續時間上限。

## 更新角色描述
<a name="id_roles_update-description"></a>

若要變更描述的描述，請修改描述文字。

### 更新角色描述 (主控台)
<a name="id_roles_update-description-console"></a>

**變更角色的說明 (主控台)**

1. 登入 AWS 管理主控台 ，並在 https：//[https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/) 開啟 IAM 主控台。

1. 在 IAM 主控台的導覽窗格中，選擇 **Roles** (角色)。

1. 選擇要修改之角色的名稱。

1. 在 **Summary** (摘要) 區段中，選擇 **Edit** (編輯)。

1. 在方塊中輸入新說明，然後選擇 **Save changes** (儲存變更)。

### 更新角色描述 (AWS CLI)
<a name="id_roles_update-description-cli"></a>

**變更角色的說明 (AWS CLI)**

1. (選用) 若要檢視角色的目前說明，請執行下列命令：
   + [aws iam get-role](https://docs.aws.amazon.com/cli/latest/reference/iam/get-role.html)

1. 若要更新角色的說明，請使用說明參數執行下列命令：
   + [aws iam update-role](https://docs.aws.amazon.com/cli/latest/reference/iam/update-role.html)

### 更新角色描述 (AWS API)
<a name="id_roles_update-description-api"></a>

**變更角色的描述 (AWS API)**

1. (選用) 若要檢視角色的目前說明，請呼叫下列操作：
   + [GetRole](https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetRole.html) 

1. 若要更新角色的說明，請使用說明參數呼叫下列操作：
   + [UpdateRole](https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateRole.html)

## 更新角色的最大工作階段持續時間
<a name="id_roles_update-session-duration"></a>

若要為使用主控台 AWS CLI、 或 AWS API 擔任的角色指定工作階段持續時間上限設定，請修改工作階段持續時間上限設定值。此設定的值可介於 1 小時至 12 小時。如果未指定值，則套用預設最大值 1 小時。此設定不會限制 AWS 服務所擔任的工作階段。

### 更新最大角色工作階段持續時間 (主控台)
<a name="id_roles_update-session-duration-console"></a><a name="id_roles_modify_max-session"></a>

**變更使用主控台 AWS CLI或 AWS API （主控台） 擔任之角色的工作階段持續時間上限設定**

1. 登入 AWS 管理主控台 ，並在 https：//[https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/) 開啟 IAM 主控台。

1. 在 IAM 主控台的導覽窗格中，選擇 **Roles** (角色)。

1. 選擇要修改之角色的名稱。

1. 在 **Summary** (摘要) 區段中，選擇 **Edit** (編輯)。

1. 在 **Maximum session duration** (最大工作階段持續時間) 中，選擇一個值。或者，選擇 **Custom duration** (自訂持續時間) 並輸入一個值 (以秒為單位)。

1. 選擇**儲存變更**。

   在下次有人擔任此角色之前，您的變更不會生效。若要了解如何撤銷此角色的現有工作階段，請參閱[撤銷 IAM 角色臨時安全憑證](id_roles_use_revoke-sessions.md)。

在 中 AWS 管理主控台，IAM 使用者工作階段預設為 12 小時。在主控台中切換角色的 IAM 使用者會被授予角色最長工作階段持續時間或使用者工作階段中的剩餘時間，以較短者為準。

從 AWS CLI 或 AWS API 擔任角色的任何人都可以請求更長的工作階段，最高可達此上限。`MaxSessionDuration` 設定決定可以請求之角色工作階段的最大持續時間。
+ 若要使用 指定工作階段持續時間， AWS CLI 請使用 `duration-seconds` 參數。如需詳細資訊，請參閱 [切換到 IAM 角色 (AWS CLI)](id_roles_use_switch-role-cli.md)。
+ 若要使用 AWS API 指定工作階段持續時間，請使用 `DurationSeconds` 參數。如需詳細資訊，請參閱 [切換到 IAM 角色 (AWS API)](id_roles_use_switch-role-api.md)。

### 更新角色工作階段持續時間上限 (AWS CLI)
<a name="id_roles_update-session-duration-cli"></a>

**注意**  
從 AWS CLI 或 API 擔任角色的任何人都可以使用 `duration-seconds` CLI 參數或 `DurationSeconds` API 參數來請求更長的工作階段。`MaxSessionDuration` 設定決定可以使用`DurationSeconds` 參數請求的角色工作階段的最大持續時間。如果使用者不為 `DurationSeconds` 參數指定一個值，則使用者的安全憑證有效期為 1 小時。

**使用 AWS CLI (AWS CLI) 變更所擔任角色的工作階段持續時間上限設定**

1. (選用) 若要檢視角色的目前最大工作階段持續時間設定，請執行下列命令：
   + [aws iam get-role](https://docs.aws.amazon.com/cli/latest/reference/iam/get-role.html)

1. 若要更新角色的工作階段持續時間設定，請使用 `max-session-duration` CLI 參數或 `MaxSessionDuration` API 參數執行以下命令：
   + [aws iam update-role](https://docs.aws.amazon.com/cli/latest/reference/iam/update-role.html)

   在下次有人擔任此角色之前，您的變更不會生效。若要了解如何撤銷此角色的現有工作階段，請參閱[撤銷 IAM 角色臨時安全憑證](id_roles_use_revoke-sessions.md)。

### 更新角色工作階段持續時間上限 (AWS API)
<a name="id_roles_update-session-duration-api"></a>

**注意**  
從 AWS CLI 或 API 擔任角色的任何人都可以使用 `duration-seconds` CLI 參數或 `DurationSeconds` API 參數來請求更長的工作階段。`MaxSessionDuration` 設定決定可以使用`DurationSeconds` 參數請求的角色工作階段的最大持續時間。如果使用者不為 `DurationSeconds` 參數指定一個值，則使用者的安全憑證有效期為 1 小時。

**變更使用 API (AWS API) 擔任之角色的工作階段持續時間上限設定**

1. (選用) 若要檢視角色的目前最大工作階段持續時間設定，請呼叫下列操作：
   + [GetRole](https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetRole.html) 

1. 若要更新角色的工作階段持續時間設定，請使用 `max-sessionduration` CLI 參數或 `MaxSessionDuration` API 參數呼叫以下操作：
   + [UpdateRole](https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateRole.html)

   在下次有人擔任此角色之前，您的變更不會生效。若要了解如何撤銷此角色的現有工作階段，請參閱[撤銷 IAM 角色臨時安全憑證](id_roles_use_revoke-sessions.md)。

# 刪除角色或執行個體設定檔
<a name="id_roles_manage_delete"></a>

如果您不再需要角色，建議您刪除角色及其關聯的許可。如此一來，您就沒有未主動監控或維護的未使用實體。

如果角色與 EC2 執行個體相關聯，您也可以從執行個體設定檔中移除角色，然後刪除執行個體設定檔。

**警告**  
確保您沒有任何 Amazon EC2 執行個體與您即將刪除的角色或執行個體描述檔一起執行。若刪除與執行中的執行個體相關聯的角色或執行個體描述檔，將會中斷執行個體上執行的所有應用程式。

如果您不想永久刪除某個角色，則可以停用該角色。若要執行此操作，請變更角色的政策，然後撤銷所有目前的工作階段。例如，您可以將政策新增至拒絕存取所有 的角色 AWS。您也可以編輯信任政策，以拒絕任何嘗試擔任該角色的人存取。如需有關撤銷工作階段的詳細資訊，請參閱 [撤銷 IAM 角色臨時安全憑證](id_roles_use_revoke-sessions.md)。

**Topics**
+ [檢視角色存取](#roles-delete_prerequisites)
+ [刪除服務連結角色](#id_roles_manage_delete_slr)
+ [刪除 IAM 角色 (主控台)](#roles-managingrole-deleting-console)
+ [刪除 IAM 角色 (AWS CLI)](#roles-managingrole-deleting-cli)
+ [刪除 IAM 角色 (AWS API)](#roles-managingrole-deleting-api)
+ [相關資訊](#roles-managingrole-deleting-related-info)

## 檢視角色存取
<a name="roles-delete_prerequisites"></a>

刪除角色之前，建議您先檢閱上次使用角色的時間。您可以使用 AWS 管理主控台、 AWS CLI或 AWS API 來執行此操作。您應該檢視此資訊，因為您不想移除正在使用該角色之某個使用者的存取權。

角色上次活動的日期可能與**上次存取**索引標籤中報告的上次使用日期不符。[**上次存取**](access_policies_last-accessed-view-data.md)索引標籤僅報告角色許可政策允許服務的活動。角色上次活動的日期包括上次嘗試存取其中任何服務的日期 AWS。

**注意**  
角色上次活動和「上次存取」資料的追蹤期間為過去 400 天。如果您的區域在過去一年內已開始支援這些功能，此期間可能會縮短。該角色的上次使用時間可能已經超過 400 天。如需有關追蹤期間的詳細資訊，請參閱 [其中 會 AWS 追蹤上次存取的資訊](access_policies_last-accessed.md#last-accessed_tracking-period)。

**檢視上次使用角色的時間 (主控台)**

1. 登入 AWS 管理主控台 ，並在 https：//[https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/) 開啟 IAM 主控台。

1. 在導覽窗格中，選擇 **Roles** (角色)。

1. 尋找具有您要檢視活動之角色的資料列。您可以使用搜尋欄位縮減結果。檢視 **Last activity (上次活動)** 欄，查看自上次使用該角色後的天數。如果在追蹤期間內未曾使用該角色，資料表會顯示 **None (無)**。

1. 選擇角色名稱以查看詳細資訊。角色的 **Summary** (摘要) 頁面也包含 **Last activity** (上次活動)，會顯示角色上次使用的日期。如果過去 400 天內未使用過該角色，則 **Last activity (上次活動)** 會顯示 **Not accessed in the tracking period (在追蹤期間內未存取)**。

**檢視上次使用角色的時間 (AWS CLI)**  
`[aws iam get-role](https://docs.aws.amazon.com/cli/latest/reference/iam/get-role.html)` - 執行此命令以傳回角色的資訊，包括 `RoleLastUsed` 物件。此物件包含 `LastUsedDate` 和上次使用角色的 `Region`。如有 `RoleLastUsed` 但不包含值，即表示未在追蹤期間內使用過該角色。

**檢視上次使用角色的時間 (AWS API)**  
`[GetRole](https://docs.aws.amazon.com/IAM/latest/APIReference/GetRole.html)` - 呼叫此操作以傳回角色的資訊，包括 `RoleLastUsed` 物件。此物件包含 `LastUsedDate` 和上次使用角色的 `Region`。如有 `RoleLastUsed` 但不包含值，即表示未在追蹤期間內使用過該角色。

## 刪除服務連結角色
<a name="id_roles_manage_delete_slr"></a>

您用來刪除服務連結角色的方法取決於服務。在某些情況下，您不需要手動刪除一個服務連結角色。例如，當您在服務中完成特定動作 (例如移除資源)，該服務可能會為您刪除服務連結角色。在其他情況下，服務可能支援從服務主控台、API 或 AWS CLI手動刪除服務連結角色。

請檢閱連結服務中*[服務連結角色](id_roles.md#iam-term-service-linked-role)*的文件，以了解如何刪除該角色。您可以前往主控台的 IAM **Roles** (角色) 頁面，檢視您帳戶中的服務連結角色。服務連結角色會在表格的 **Trusted entities (受信任實體)** 欄中以 **(Service-linked role) ((服務連結角色))** 顯示。在 **Summary** (摘要) 頁面上的橫幅，也會指出角色是一個服務連結角色。

如果服務不包含刪除服務連結角色的文件，您可以使用 IAM 主控台 AWS CLI或 API 來刪除角色。

## 刪除 IAM 角色 (主控台)
<a name="roles-managingrole-deleting-console"></a>

當您使用 AWS 管理主控台 刪除角色時，IAM 會自動分離與該角色相關聯的受管政策。它還會自動刪除與該角色關聯的內嵌政策，以及包含該角色的任何 Amazon EC2 執行個體設定檔。

**重要**  
在某些情況下，角色可能會與 Amazon EC2 執行個體描述檔相關聯，而且角色和執行個體描述檔的名稱可能完全相同。在這種情況下，您可以使用 AWS 管理主控台 來刪除角色和執行個體描述檔。此連結就會自動為您在主控台建立的角色和執行個體設定檔。如果您從 AWS CLI、Tools for Windows PowerShell 或 AWS API 建立角色，則角色和執行個體描述檔可能有不同的名稱。在該情況下，您無法使用主控台將它們刪除。反之，您必須使用 AWS CLI Tools for Windows PowerShell 或 AWS API，先從執行個體描述檔中移除角色。然後，您必須採取不同步驟刪除該角色。

**刪除角色 (主控台)**

1. 登入 AWS 管理主控台 ，並在 https：//[https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/) 開啟 IAM 主控台。

1. 在導覽窗格中，選擇 **Roles (角色)**，然後勾選您要刪除之角色名稱旁的核取方塊。

1. 在頁面頂端，選擇 **Delete (刪除)**。

1. 在確認對話方塊中，檢閱上次存取的資訊，其中顯示每個所選角色上次存取 AWS 服務的時間。這可協助您確認角色目前是否在作用中。如果您要繼續，請在文字輸入欄位中輸入角色的名稱，並選擇 **Delete** (刪除)。如果您確定，可以繼續刪除，即使上次存取的資訊仍持續載入。

**注意**  
除非執行個體設定檔和角色同名，否則您不能使用主控台刪除執行個體設定檔。作為刪除角色的過程的一部分，執行個體描述檔會被刪除，如前面的程序中所述。若要刪除執行個體描述檔而不同時刪除角色，您必須使用 AWS CLI 或 AWS API。如需詳細資訊，請參閱下列區段。

## 刪除 IAM 角色 (AWS CLI)
<a name="roles-managingrole-deleting-cli"></a>

當您使用 AWS CLI 刪除角色時，您必須先刪除與該角色相關聯的內嵌政策。您還必須分離與該角色關聯的受管政策。如果您要刪除包含角色的相關聯執行個體設定檔，您必須分開刪除。

**刪除角色 (AWS CLI)**

1. 如果您不知道想要刪除的角色名稱，請輸入以下命令列出帳戶中的角色：

   ```
   aws iam list-roles
   ```

   此清單包含每個角色的 Amazon Resource Name (ARN)。透過 CLI 命令，使用角色名稱 (而非 ARN) 來參照角色。例如，如果角色具有下列 ARN：`arn:aws:iam::123456789012:role/myrole`，請將角色參照為 **myrole**。

1. 從角色關聯的所有執行個體設定檔移除該角色。

   1. 若要列出所有與角色相關聯的執行個體設定檔，請輸入下列命令：

      ```
      aws iam list-instance-profiles-for-role --role-name role-name
      ```

   1. 若要從執行個體設定檔中移除該角色，請針對每個執行個體設定檔輸入下列命令：

      ```
      aws iam remove-role-from-instance-profile --instance-profile-name instance-profile-name --role-name role-name
      ```

1. 刪除所有與該角色相關聯的政策。

   1. 若要列出角色中所有的內嵌政策，請輸入下列命令：

      ```
      aws iam list-role-policies --role-name role-name
      ```

   1. 若要刪除角色中的每個內嵌政策，請針對每個政策輸入下列命令：

      ```
      aws iam delete-role-policy --role-name role-name --policy-name policy-name
      ```

   1. 若要列出連接至角色的所有受管政策，請輸入下列命令：

      ```
      aws iam list-attached-role-policies --role-name role-name
      ```

   1. 若要從角色分離每個受管政策，請針對每個政策輸入下列命令：

      ```
      aws iam detach-role-policy --role-name role-name --policy-arn policy-arn
      ```

1. 輸入下列命令以刪除角色：

   ```
   aws iam delete-role --role-name role-name
   ```

1. 如果您不打算重複使用曾與角色相關聯的執行個體設定檔，您可以輸入下列命令予以刪除：

   ```
   aws iam delete-instance-profile --instance-profile-name instance-profile-name
   ```

## 刪除 IAM 角色 (AWS API)
<a name="roles-managingrole-deleting-api"></a>

當您使用 IAM API 刪除該角色，您必須先刪除與該角色關聯的內嵌政策。您還必須分離與該角色關聯的受管政策。如果您要刪除包含角色的相關聯執行個體設定檔，您必須分開刪除。

**刪除角色 (AWS API)**

1. 若要列出角色關聯的所有執行個體設定檔，請呼叫 [ListInstanceProfilesForRole](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListInstanceProfilesForRole.html)。

   若要從執行個體設定檔移除角色，請呼叫 [RemoveRoleFromInstanceProfile](https://docs.aws.amazon.com/IAM/latest/APIReference/API_RemoveRoleFromInstanceProfile.html)。您必須傳遞角色名稱和執行個體設定檔名稱。

   如果您不打算重複使用曾與角色相關聯的執行個體描述檔，請呼叫 [DeleteInstanceProfile](https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteInstanceProfile.html) 予以刪除。

1. 若要列出角色的所有內嵌政策，請呼叫 [ListRolePolicies](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListRolePolicies.html)。

   若要刪除與角色建立關聯的所有內嵌政策，請呼叫 [DeleteRolePolicy](https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteRolePolicy.html)。您必須傳遞角色名稱和內嵌政策名稱。

1. 若要列出連接至角色的所有受管政策，請呼叫 [ListAttachedRolePolicies](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListAttachedRolePolicies.html)。

   若要分離連接至該角色的受管政策，請呼叫 [DetachRolePolicy](https://docs.aws.amazon.com/IAM/latest/APIReference/API_DetachRolePolicy.html)。您必須傳遞角色名稱和受管政策 ARN。

1. 呼叫 [DeleteRole](https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteRole.html) 以刪除該角色。

## 相關資訊
<a name="roles-managingrole-deleting-related-info"></a>

如需有關執行個體設定檔的一般資訊，請參閱[使用執行個體設定檔](id_roles_use_switch-role-ec2_instance-profiles.md)。

如需服務連結角色的一般資訊，請參閱 [建立服務連結角色](id_roles_create-service-linked-role.md)。

# 擔任角色的方法
<a name="id_roles_manage-assume"></a>

在使用者、應用程式或服務可以使用您建立的角色之前，您必須[授予切換到該角色的許可](id_roles_use_permissions-to-switch.md)。您可以使用連接至群組或使用者的任何政策，來授予必要的許可。授予許可後，使用者可以從 AWS 管理主控台、Tools for Windows PowerShell、 AWS Command Line Interface (AWS CLI) 和 [https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) API 擔任角色。

**重要**  
當您以程式設計方式而不是在 IAM 主控台中建立角色時，則除了 `RoleName` 之外，您還可以選擇新增高達 512 個字元的 `Path`，該字元長度最多 64 個字元。不過，如果您想要在 中使用具有**切換角色**功能的角色 AWS 管理主控台，則合併的 `Path`和 `RoleName`不得超過 64 個字元。

用於擔任角色的方法決定誰可以擔任該角色以及角色工作階段可以持續多久。使用 `AssumeRole*` API 操作時，您擔任的 IAM 角色是資源。呼叫 `AssumeRole*` API 操作的使用者或角色是主體。

下表比較擔任角色的方法。


|  擔任角色的方法 |  **誰可以擔任這個角色**  | **指定憑證生命週期的方法** |  **憑證存留期 (最小 \$1 最大 \$1 預設)**  | 
| --- | --- | --- | --- | 
| AWS 管理主控台 | 使用者或角色¹ (透過[切換角色](id_roles_use_switch-role-console.md)) | Role (角色) 摘要頁面上的 Maximum session duration (最大工作階段持續時間) | 15 分鐘 \$1 最大工作階段持續時間設定² \$1 1 小時 | 
| [https://docs.aws.amazon.com/cli/latest/reference/sts/assume-role.html](https://docs.aws.amazon.com/cli/latest/reference/sts/assume-role.html) CLI 或 [https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) API 操作 |  使用者或角色¹ | duration-seconds CLI 或 DurationSeconds API 參數 | 15 分鐘 \$1 最大工作階段持續時間設定² \$1 1 小時  | 
| [https://docs.aws.amazon.com/cli/latest/reference/sts/assume-role-with-saml.html](https://docs.aws.amazon.com/cli/latest/reference/sts/assume-role-with-saml.html) CLI 或 [https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithSAML.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithSAML.html) API 操作 | 任何使用 SAML 驗證的使用者 | duration-seconds CLI 或 DurationSeconds API 參數 | 15 分鐘 \$1 最大工作階段持續時間設定² \$1 1 小時  | 
| [https://docs.aws.amazon.com/cli/latest/reference/sts/assume-role-with-web-identity.html](https://docs.aws.amazon.com/cli/latest/reference/sts/assume-role-with-web-identity.html) CLI 或 [https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html) API 操作 | 使用 OIDC 提供者進行身分驗證的任何使用者 | duration-seconds CLI 或 DurationSeconds API 參數 | 15 分鐘 \$1 最大工作階段持續時間設定² \$1 1 小時  | 
| 使用 [ 建構的](id_roles_providers_enable-console-custom-url.md)主控台 URLAssumeRole  | 使用者或角色 | SessionDuration URL 中的 HTML 參數 | 15 分鐘 \$1 12 小時 \$1 1 小時  | 
| 使用 [ 建構的](id_roles_providers_enable-console-custom-url.md)主控台 URLAssumeRoleWithSAML  | 任何使用 SAML 驗證的使用者 | SessionDuration URL 中的 HTML 參數 | 15 分鐘 \$1 12 小時 \$1 1 小時 | 
| 使用 [ 建構的](id_roles_providers_enable-console-custom-url.md)主控台 URLAssumeRoleWithWebIdentity  | 使用 OIDC 提供者進行身分驗證的任何使用者 | SessionDuration URL 中的 HTML 參數 | 15 分鐘 \$1 12 小時 \$1 1 小時  | 

¹ 使用來自一個角色的憑證來擔任不同的角色稱為[角色鏈結](id_roles.md#iam-term-role-chaining)。當您使用角色鏈結時，角色的工作階段持續時間限制為一小時。這適用於 AWS 管理主控台 角色切換 AWS CLI和 API 操作。此限制不適用於從使用者憑證初始擔任角色，也不適用於在使用執行個體設定檔的 Amazon EC2 執行個體上執行的應用程式。

² 此設定的值可介於 1 小時至 12 小時。有關修改最大工作階段持續時間設定的詳細資訊，請參閱 [IAM 角色管理](id_roles_manage.md)。此設定決定取得角色憑證時可以請求的最大工作階段持續時間。例如，當您使用 [AssumeRole\$1](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) API 操作來擔任角色時，可以使用 `DurationSeconds` 參數指定工作階段長度。使用此參數指定 900 秒 (15 分鐘) 到角色的最大工作階段持續時間設定之間的角色工作階段長度。在主控台中切換角色的 IAM 使用者會被授予最長工作階段持續時間或使用者工作階段中的剩餘時間，以較短者為準。假設您在角色上設定 5 小時的最大持續時間。已登入主控台 10 小時的 IAM 使用者 (超出預設最大值 12 小時) 會切換至角色。可用的角色工作階段持續時間為 2 小時。如要了解如何查看角色的最大值，請參閱本頁後述的 [更新角色的最大工作階段持續時間](id_roles_update-role-settings.md#id_roles_update-session-duration)。

**備註**  
工作階段持續時間設定上限不會限制由 AWS 服務擔任的工作階段。
Amazon EC2 IAM 角色憑證不受角色中設定的工作階段持續時間上限的限制。
若要允許使用者在角色工作階段中再次擔任目前角色，請在角色信任政策中將角色 ARN 或 AWS 帳戶 ARN 指定為主體。 AWS 服務 會提供運算資源，例如 Amazon EC2、Amazon ECS、Amazon EKS 和 Lambda，可提供臨時登入資料並自動更新這些登入資料。此可確保您始終擁有一組有效的憑證。對於這些服務，不需要再次擔任目前的角色即可取得臨時憑證。但是，如果您想要傳遞[工作階段標籤](id_session-tags.md)或一個[工作階段政策](access_policies.md#policies_session)，則需要再次擔任目前的角色。若要了解如何修改角色信任政策以新增主要角色 ARN 或 AWS 帳戶 ARN，請參閱 [更新角色信任政策](id_roles_update-role-trust-policy.md)。

**Topics**
+ [從使用者切換至 IAM 角色 (主控台)](id_roles_use_switch-role-console.md)
+ [切換到 IAM 角色 (AWS CLI)](id_roles_use_switch-role-cli.md)
+ [切換至 IAM 角色 (Tools for Windows PowerShell)](id_roles_use_switch-role-twp.md)
+ [切換到 IAM 角色 (AWS API)](id_roles_use_switch-role-api.md)
+ [使用 IAM 角色為在 Amazon EC2 執行個體上執行的應用程式授予許可](id_roles_use_switch-role-ec2.md)
+ [使用執行個體設定檔](id_roles_use_switch-role-ec2_instance-profiles.md)

# 從使用者切換至 IAM 角色 (主控台)
<a name="id_roles_use_switch-role-console"></a>

當您做為 IAM 使用者、IAM Identity Center 中的使用者、SAML 聯合角色或 Web 聯合身分角色登入時，才能切換角色。*角色*會指定一組許可，您可以使用這些許可來存取您需要 AWS 的資源。不過，您不登入角色，但一旦以 IAM 使用者身分登入後，就可以切換到 IAM 角色。這會暫時擱置了原始使用者許可，而不是為您提供指派給該角色的許可。該角色可以在您自己的帳戶或任何其他 AWS 帳戶中。如需有關角色、其優勢以及建立方式的詳細資訊，請參閱 [IAM 角色](id_roles.md) 和 [IAM 角色建立](id_roles_create.md)。

您的使用者以及您切換到任何角色的許可都不會累計。每次只有一組許可是作用中。當您切換角色時，您會暫時放棄使用者許可並使用指派給該角色的許可。當您退出角色後，您的使用者許可會自動恢復。

當您在 中切換角色時 AWS 管理主控台，主控台一律會使用您的原始登入資料來授權切換。例如，如果您切換到 RoleA，IAM 會使用您的原始憑證確定是否允許您擔任 RoleA。如果您接著*在使用 RoleA* RoleA 時切換到 RoleB， AWS 仍然會使用**原始**登入資料來授權切換，而不是 RoleA 的登入資料。

**注意**  
以 IAM Identity Center 中的使用者、SAML 聯合角色或 Web 聯合身分角色登入時，您將在啟動工作階段時擔任 IAM 角色。例如，當 IAM Identity Center 中的使用者登入 AWS 存取入口網站時，他們必須先選擇與角色相關的許可集，才能存取 AWS 資源。

## 角色工作階段
<a name="id_roles_iam_user-switch-role-sessions"></a>

當您切換角色時，您的 AWS 管理主控台 工作階段預設會持續 1 小時。IAM 使用者工作階段預設為 12 小時，其他使用者可能已定義不同的工作階段持續時間。在主控台中切換角色時，您會取得角色工作階段持續時間上限或使用者工作階段中的剩餘時間 (以較短者為準)。您無法透過擔任角色來延長工作階段持續時間。

例如，假設為角色設定的最大工作階段持續時間為 10 小時。您決定切換至該角色時，已登入主控台 8 小時。使用者工作階段還剩餘 4 小時，因此允許的角色工作階段持續時間為 4 小時，而不是工作階段持續時間上限 10 小時。下表顯示在主控台中切換角色時如何判斷 IAM 使用者的工作階段持續時間。


| IAM 使用者工作階段剩餘時間為... | 角色工作階段持續時間為… | 
| --- | --- | 
| 小於角色最大工作階段持續時間 | 使用者工作階段中的剩餘時間 | 
| 大於角色最大工作階段持續時間 | 最大工作階段持續時間值 | 
| 等於角色最大工作階段持續時間 | 最大工作階段持續時間值 (近似值) | 

使用來自一個角色的憑證來擔任不同的角色稱為[角色鏈結](id_roles.md#iam-term-role-chaining)。使用角色鏈結時，無論為個別角色設定的工作階段持續時間上限為何，工作階段持續時間都將限制為一小時。這適用於 AWS 管理主控台 角色切換 AWS CLI和 API 操作。

**注意**  
有些 AWS 服務主控台可以在角色工作階段過期時自動續約，而無需您採取任何動作。有些主控台可能會提示您重新載入瀏覽器頁面以重新驗證您的工作階段。

## 考量事項
<a name="id_roles_iam_user-switch-role-considerations"></a>
+ 如果您以 身分登入，則無法切換角色 AWS 帳戶根使用者。
+ 必須授予使用者依政策切換角色的許可。如需說明，請參閱[向使用者授予切換角色的許可](id_roles_use_permissions-to-switch.md)。
+ 您無法將 中的角色切換 AWS 管理主控台 為需要 [ExternalId](id_roles_common-scenarios_third-party.md#id_roles_third-party_external-id) 值的角色。您只能透過呼叫支援 `ExternalId` 參數的 [https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) API 來切換到此類角色。

## 若要切換至角色
<a name="id_roles_iam_user-switch-role-console-procedure"></a>

1. 按照 *AWS 登入 User Guide* 中的 [Sign in to the AWS 管理主控台](https://docs.aws.amazon.com/signin/latest/userguide/how-to-sign-in.html) 中適合使用者類型的登入程序操作。

1. 在 中 AWS 管理主控台，選擇右上角導覽列上的使用者名稱。它通常如下：***username*@*account\$1ID\$1number\$1or\$1alias***。

1. 選取下列其中一種方法來切換角色：
   + 選擇**切換角色**。
   + 若已選擇加入多工作階段支援，請選擇**新增工作階段**，然後選取**切換角色**。
**注意**  
您可以在 AWS 管理主控台中的單一 Web 瀏覽器中同時登入最多五個不同的身分。如需詳細資訊，請參閱 *AWS 管理主控台 Getting Started Guide* 中的 [Signing in to multiple accounts](https://docs.aws.amazon.com/awsconsolehelpdocs/latest/gsg/multisession.html)。

1. 在 **Switch Role (切換角色)** 頁面上，輸入帳戶 ID 號碼或帳戶別名以及管理員提供的角色名稱。
**注意**  
如果管理員已使用路徑 (例如 `division_abc/subdivision_efg/roleToDoX`) 建立角色，則必須在 **Role (角色)** ）方塊中輸入該完整路徑和名稱。如果僅輸入角色名稱，或者組合的 `Path` 和 `RoleName` 超過 64 個字元，則角色切換失敗。這是存放角色名稱的瀏覽器 cookie 的限制。如果發生這種情況，請聯絡您的管理員，並要求他們減小路徑和角色名稱的大小。

1. (選用) 您可以輸入顯示名稱，然後選取在主控台導覽列中反白顯示角色的顯示顏色。
   + 在**顯示名稱**欄位中，鍵入當此角色處於作用中時，要在導覽列上顯示之用以取代使用者名稱的文字。根據帳戶和角色資訊建議使用名稱，但您可以將其變更為對您有意義的任何名稱。
   + 在**顯示顏色**欄位中，選取顏色以反白顯示顯示名稱。

   名稱和顏色有助於在此角色處於作用中時提醒您，這會變更您的許可。例如，對於允許您存取測試環境的角色，您可以指定 **Test** 的 **Display name** (顯示名稱) 並在 **Color** (顏色)中選擇綠色。對於允許您存取生產的角色，您可以指定 **Production** 的 **Display name** (顯示名稱) 並在 **Color** (顏色)中選擇紅色。

1. 選擇 **Switch Role** (切換角色)。顯示名稱和顏色將替換導覽列上的使用者名稱，您可以開始使用該角色授予您的許可。

1. 完成需要 IAM 角色的任務後，您可以切換回原始工作階段。這將移除角色提供的額外許可，並讓您返回標準許可。

   1. 在 IAM 主控台中，選擇導覽列右上角的角色 **Display Name** (顯示名稱)。

   1. 選擇**切換回**。

      例如，假設您使用使用者名稱 `123456789012` 登入到帳戶編號 `Richard`。使用過 `admin-role` 角色後，您想要停止使用該角色並傳回您的原始許可。若要停止使用角色，請選擇 **admin-role @ 123456789012**，然後選擇**切換回**。  
![\[圖形定位切「換返回」函數，可停止使用 IAM 角色並返回原始使用者。\]](http://docs.aws.amazon.com/zh_tw/IAM/latest/UserGuide/images/role-stop-using.png)

**提示**  
您使用的最後幾個角色會顯示在選單。下次想要切換到其中一個角色時，您只需選擇所需的角色。如果角色未顯示在功能表上，則只需手動鍵入帳戶和角色資訊。

## 其他資源
<a name="id_roles_use_switch-role-console_additional_resources"></a>
+ [向使用者授予切換角色的許可](id_roles_use_permissions-to-switch.md)
+ [授予使用者將角色傳遞至 AWS 服務的許可](id_roles_use_passrole.md)
+ [建立角色以將許可授予 IAM 使用者](id_roles_create_for-user.md)
+ [建立角色以將許可委派給 AWS 服務](id_roles_create_for-service.md)
+ [IAM 角色疑難排解](troubleshoot_roles.md)

# 切換到 IAM 角色 (AWS CLI)
<a name="id_roles_use_switch-role-cli"></a>

「角色」**指定一組許可，您可以使用它來存取所需的 AWS 資源。從這個意義上說，類似於 [AWS Identity and Access Management中的使用者](https://docs.aws.amazon.com/IAM/latest/UserGuide/id.html) (IAM)。當您以使用者身分登入時，您將取得一組特定的許可。不過，您不登入角色，但以使用者身分登入後，就可以切換角色。這會暫時擱置了原始使用者許可，而不是為您提供指派給該角色的許可。該角色可以在您自己的帳戶或任何其他 AWS 帳戶中。如需有關角色、其優勢以及建立和設定方式的詳細資訊，請參閱 [IAM 角色](id_roles.md) 和 [IAM 角色建立](id_roles_create.md)。要了解在擔任角色時使用的各種方法，請參閱 [擔任角色的方法](id_roles_manage-assume.md)。

**重要**  
您的 IAM 使用者以及您擔任的任何角色的許可都不會累計。每次只有一組許可是作用中。當您擔任角色時，您會暫時放棄以前的使用者或角色許可，並使用指派給該角色的許可。當您退出角色後，您的使用者許可會自動恢復。

當您以 IAM 使用者身分登入時，您可以使用角色來執行 AWS CLI 命令。當您以已使用角色的[外部身分驗證使用者 ](id_roles_providers.md)([SAML](id_roles_providers_saml.md) 或 [OIDC](id_roles_providers_oidc.md)) 登入時，您也可以使用角色來執行 AWS CLI 命令。此外，您可以使用角色從 Amazon EC2 執行個體執行 AWS CLI 命令，而該執行個體透過執行個體描述檔連接到角色。當您以 AWS 帳戶根使用者身分登入時，則無法擔任該角色。

[**角色鏈結**](id_roles.md#iam-term-role-chaining) – 您也可以使用角色鏈結，以使用角色的許可來存取第二個角色。

在預設情況下，您的角色工作階段持續一小時。使用 `assume-role*` CLI 操作擔任此角色時，可以為 `duration-seconds` 參數指定值。此值的範圍可以從 900 秒 (15 分鐘) 到角色的最大工作階段持續時間設定的值。如果在主控台中切換角色，您工作階段的持續時間會限制為最多一小時。若要了解如何檢視角色的最大值，請參閱 [更新角色的最大工作階段持續時間](id_roles_update-role-settings.md#id_roles_update-session-duration)。

如果使用角色鏈結時，則工作階段持續時間最多限制為一小時。如果您隨後使用 `duration-seconds` 參數提供大於一小時的值，則操作會失敗。

## 範例案例：切換到生產角色
<a name="switch-role-cli-scenario-prod-env"></a>

假設您是在開發環境中工作的 IAM 使用者。在此情況下，您偶爾需要透過 [AWS CLI](https://aws.amazon.com/cli/) 在命令列中使用生產環境。您已經有存取金鑰憑證組可供您使用。這可以是指派給標準 IAM 使用者的存取金鑰對。或者，如果您以 SAML 或 OIDC 聯合身分主體的身分登入，則它可以是最初指派給您的角色的存取金鑰對。如果您目前的許可授予您擔任特定 IAM 角色的能力，則可以在 AWS CLI 組態檔案中的「設定檔」中識別該角色。然後使用指定 IAM 角色的許可來執行該命令，而不是原始身分。請注意，當您在 AWS CLI 命令中指定該設定檔時，您正在使用新角色。在這種情況下，您無法同時在開發帳戶中使用原始許可。原因是一次只有一組許可有效。

**注意**  
基於安全考量，管理員可以[檢閱 AWS CloudTrail 日誌](cloudtrail-integration.md#cloudtrail-integration_signin-tempcreds)，以了解在其中執行動作的人員 AWS。當您擔任角色時，系統管理員可能需要您指定來源身分或角色工作階段名稱 。如需詳細資訊，請參閱[`sts:SourceIdentity`](reference_policies_iam-condition-keys.md#ck_sourceidentity)及[`sts:RoleSessionName`](reference_policies_iam-condition-keys.md#ck_rolesessionname)。

**切換到生產角色 (AWS CLI)**

1. <a name="step-configure-default"></a>如果您從未使用 AWS CLI，則必須先設定預設的 CLI 設定檔。開啟命令提示字元並設定您的 AWS CLI 安裝，以使用來自 IAM 使用者或聯合角色的存取金鑰。如需詳細資訊，請參閱《AWS Command Line Interface 使用者指南》**中的[設定 AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html#cli-quick-configuration)。

   執行 [aws configure](https://docs.aws.amazon.com/cli/latest/reference/configure/) 命令，如下所示：

   ```
   aws configure
   ```

   當出現提示時，請提供下列資訊：

   ```
   AWS Access Key ID [None]: AKIAIOSFODNN7EXAMPLE
   AWS Secret Access Key [None]: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
   Default region name [None]: us-east-2
   Default output format [None]: json
   ```

1. 在 Unix 或 Linux `.aws/config` 檔案中，或在 Windows `C:\Users\USERNAME\.aws\config` 檔案中建立角色的新描述檔。下列範例會建立稱為 `prodaccess` 的描述檔，以切換到 `ProductionAccessRole` 帳戶中的角色 `123456789012`。您從建立角色的帳戶管理員處取得角色 ARN。叫用此設定檔時， AWS CLI 會使用 的登入資料`source_profile`來請求角色的登入資料。因此，做為 `source_profile` 參考的身分必須具有 `sts:AssumeRole` 中指定角色的 `role_arn` 許可。

   ```
   [profile prodaccess]
       role_arn = arn:aws:iam::123456789012:role/ProductionAccessRole
       source_profile = default
   ```

1. 建立新設定檔之後，指定 參數的任何 AWS CLI 命令都會在連接到 IAM 角色的許可下`--profile prodaccess`執行，`ProductionAccessRole`而不是預設使用者。

   ```
   aws iam list-users --profile prodaccess
   ```

   如果指派給 `ProductionAccessRole` 的許可啟用列出目前 AWS 帳戶中的使用者，則此命令有效。

1. 若要傳回原始憑證授予的許可，請執行不帶 `--profile` 參數的命令。會使用您在 中設定的預設設定檔中的登入資料 AWS CLI 還原至 [Step 1](#step-configure-default)。

如需詳細資訊，請參閱《AWS Command Line Interface 使用者指南》**中的[擔任角色](https://docs.aws.amazon.com/cli/latest/userguide/cli-roles.html)。

## 範例案例：允許執行個體描述檔角色來切換到另一個帳戶中的角色
<a name="switch-role-cli-scenario-ec2-instance"></a>

假設您使用兩個 AWS 帳戶，並且您想要允許在 Amazon EC2 執行個體上執行的應用程式在兩個帳戶中執行[AWS CLI](https://aws.amazon.com/cli/)命令。假設 EC2 執行個體存在於帳戶 `111111111111`。該執行個體包含 `abcd` 執行個體描述檔角色，該角色會允許應用程式在相同 `111111111111` 帳戶中對 `amzn-s3-demo-bucket1` 儲存貯體執行唯讀 Amazon S3 任務。不過，也必須允許應用程式擔任 `efgh` 跨帳戶角色來在帳戶 `222222222222` 中執行任務。若要執行此操作，`abcd` EC2 執行個體描述檔角色必須有以下許可政策：

***帳戶 111111111111 `abcd` 角色許可政策***

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "AllowAccountLevelS3Actions",
            "Effect": "Allow",
            "Action": [
                "s3:GetBucketLocation",
                "s3:GetAccountPublicAccessBlock",
                "s3:ListAccessPoints",
                "s3:ListAllMyBuckets"
            ],
            "Resource": "arn:aws:s3:::*"
        },
        {
            "Sid": "AllowListAndReadS3ActionOnMyBucket",
            "Effect": "Allow",
            "Action": [
                "s3:Get*",
                "s3:List*"
            ],
            "Resource": [
                "arn:aws:s3:::amzn-s3-demo-bucket1/*",
                "arn:aws:s3:::amzn-s3-demo-bucket1"
            ]
        },
        {
            "Sid": "AllowIPToAssumeCrossAccountRole",
            "Effect": "Allow",
            "Action": "sts:AssumeRole",
            "Resource": "arn:aws:iam::222222222222:role/efgh"
        }
    ]
}
```

------

假設 `efgh` 跨帳戶角色允許在相同 `222222222222` 帳戶中對 `amzn-s3-demo-bucket2` 儲存貯體的唯讀 Amazon S3 任務。若要執行此操作，`efgh` 跨帳戶角色必須有以下許可政策：

***帳戶 222222222222 `efgh` 角色許可政策***

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "AllowAccountLevelS3Actions",
            "Effect": "Allow",
            "Action": [
                "s3:GetBucketLocation",
                "s3:GetAccountPublicAccessBlock",
                "s3:ListAccessPoints",
                "s3:ListAllMyBuckets"
            ],
            "Resource": "arn:aws:s3:::*"
        },
        {
            "Sid": "AllowListAndReadS3ActionOnMyBucket",
            "Effect": "Allow",
            "Action": [
                "s3:Get*",
                "s3:List*"
            ],
            "Resource": [
                "arn:aws:s3:::amzn-s3-demo-bucket2/*",
                "arn:aws:s3:::amzn-s3-demo-bucket2"
            ]
        }
    ]
}
```

------

`efgh` 角色必須允許 `abcd` 執行個體設定檔角色擔任該角色。若要執行此操作，`efgh` 角色必須有以下信任政策：

***帳戶 222222222222 `efgh` 角色信任政策***

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "efghTrustPolicy",
            "Effect": "Allow",
            "Action": "sts:AssumeRole",
            "Principal": {"AWS": "arn:aws:iam::111111111111:role/abcd"}
        }
    ]
}
```

------

若要接著在帳戶 中執行 AWS CLI 命令`222222222222`，您必須更新 CLI 組態檔案。在 AWS CLI 組態檔案中，將 `efgh` 角色識別為「描述檔」且 `abcd` EC2 執行個體描述檔角色識別為「憑證來源」。然後，使用 `efgh` 角色 (而不是原始 `abcd` 角色) 的許可執行 CLI 命令。

**注意**  
基於安全考量，您可以使用 AWS CloudTrail 來稽核帳戶中角色的使用。若要在 CloudTrail 日誌中的不同主體使用角色時區分角色工作階段，您可以使用角色工作階段名稱。當 依本主題所述代表使用者 AWS CLI 擔任角色時，角色工作階段名稱會自動建立為 `AWS-CLI-session-nnnnnnnn`。以下 *nnnnnnnn* 是整數，代表 [Unix epoch 時間](http://wikipedia.org/wiki/Unix_time)中的時間 (自 1970 年 1 月 1 日午夜 UTC 的秒數)。如需詳細資訊，請參閱《AWS CloudTrail 使用者指南》**中的 [CloudTrail 事件參考](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/eventreference.html)。

**讓 EC2 執行個體設定檔角色切換到跨帳戶角色 (AWS CLI)**

1. 您不需要設定預設 CLI 描述檔。您反而可以從 EC2 執行個體描述檔中繼資料載入憑證。在 `.aws/config` 檔案中為角色建立新的設定檔。下列範例會建立 `instancecrossaccount` 的描述檔，以切換到 `efgh` 帳戶中的角色 `222222222222`。呼叫此描述檔時， AWS CLI 會使用 EC2 執行個體描述檔中繼資料的憑證來請求角色的憑證。因此，EC2 執行個體設定檔角色必須具有在 `sts:AssumeRole` 中指定角色的 `role_arn` 許可。

   ```
   [profile instancecrossaccount]
   role_arn = arn:aws:iam::222222222222:role/efgh
   credential_source = Ec2InstanceMetadata
   ```

1. 建立新設定檔之後，指定 參數的任何 AWS CLI 命令都會在連接到帳戶 中`efgh`角色的許可下`--profile instancecrossaccount`執行`222222222222`。

   ```
   aws s3 ls amzn-s3-demo-bucket2 --profile instancecrossaccount
   ```

   如果指派給 `efgh` 角色的許可允許列出目前 AWS 帳戶中的使用者，則此命令有效。

1. 若要在帳戶 `111111111111` 中返回原始 EC2 執行個體設定檔許可，在不使用 `--profile` 參數的情形下執行 CLI 命令。

如需詳細資訊，請參閱《AWS Command Line Interface 使用者指南》**中的[擔任角色](https://docs.aws.amazon.com/cli/latest/userguide/cli-roles.html)。

# 切換至 IAM 角色 (Tools for Windows PowerShell)
<a name="id_roles_use_switch-role-twp"></a>

「角色」**指定一組許可，您可以使用它來存取所需的 AWS 資源。從這個意義上說，類似於 [AWS Identity and Access Management中的使用者](https://docs.aws.amazon.com/IAM/latest/UserGuide/id.html) (IAM)。當您以使用者身分登入時，您將取得一組特定的許可。不過，您不登入角色，但一旦登入後就可以切換角色。這會暫時擱置了原始使用者許可，而不是為您提供指派給該角色的許可。該角色可以在您自己的帳戶或任何其他 AWS 帳戶中。如需有關角色、其優勢以及建立和設定方式的詳細資訊，請參閱 [IAM 角色](id_roles.md) 和 [IAM 角色建立](id_roles_create.md)。

**重要**  
您的 IAM 使用者以及您切換到任何角色的許可都不會累計。每次只有一組許可是作用中。當您切換角色時，您會暫時放棄使用者許可並使用指派給該角色的許可。當您退出角色後，您的使用者許可會自動恢復。

本節說明在 AWS Tools for Windows PowerShell命令列中如何切換角色。

假設您在開發環境中有一個帳戶，偶爾需要使用 [Tools for Windows PowerShell](https://aws.amazon.com/powershell/) 在命令列中使用生產環境。您已經有一個存取金鑰憑證組可供您使用。這些可以是指派給標準 IAM 使用者的存取金鑰對。或者，如果您以 SAML 或 OIDC 聯合身分主體身分登入，則它們可以是最初指派給您的角色的存取金鑰對。您可以使用這些憑證來執行 `Use-STSRole` cmdlet，該 cmdlet 將新角色的 ARN 做為參數傳送。該命令傳回所請求角色的臨時安全憑證。然後，您可以在後續 PowerShell 命令中使用這些憑證，並使用角色的許可存取生產中的資源。使用該角色時，您無法在開發帳戶中使用您的使用者許可，因為一次只能有一組許可有效。

**注意**  
基於安全考量，管理員可以[檢閱 AWS CloudTrail 日誌](cloudtrail-integration.md#cloudtrail-integration_signin-tempcreds)，以了解在其中執行動作的人員 AWS。當您擔任角色時，系統管理員可能需要您指定來源身分或角色工作階段名稱 。如需詳細資訊，請參閱[`sts:SourceIdentity`](reference_policies_iam-condition-keys.md#ck_sourceidentity)及[`sts:RoleSessionName`](reference_policies_iam-condition-keys.md#ck_rolesessionname)。

請注意，所有存取金鑰和權杖僅為範例，不能如下所示般使用。以您實際環境中的適當值取代。

**切換至角色 (Tools for Windows PowerShell)**

1. 開啟 PowerShell 命令提示字元並設定預設設定檔以使用來自目前 IAM 使用者或聯合身分角色的存取金鑰。如果您之前已使用 Tools for Windows PowerShell，則可能已經完成。請注意，只有在以 IAM 使用者身分 (而非 AWS 帳戶根使用者) 登入時才能切換角色。

   ```
   PS C:\> Set-AWSCredentials -AccessKey AKIAIOSFODNN7EXAMPLE -SecretKey wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY -StoreAs MyMainUserProfile
   PS C:\> Initialize-AWSDefaults -ProfileName MyMainUserProfile -Region us-east-2
   ```

   如需詳細資訊，請參閱*AWS Tools for PowerShell 《 使用者指南*》中的[使用 AWS 登入](https://docs.aws.amazon.com/powershell/latest/userguide/specifying-your-aws-credentials.html)資料。

1. 若要擷取新角色的憑證，請執行下列命令以切換到 123456789012 帳戶中的 `RoleName` 角色。您從建立角色的帳戶管理員處取得角色 ARN。此命令還需要您提供工作階段名稱。您可以為此選擇任何文字。以下命令請求憑證，然後從傳回的結果物件中擷取 `Credentials` 屬性物件，並將其存放在 `$Creds` 變數中。

   ```
   PS C:\> $Creds = (Use-STSRole -RoleArn "arn:aws:iam::123456789012:role/RoleName" -RoleSessionName "MyRoleSessionName").Credentials
   ```

   `$Creds` 是一個物件，現在包含您在下列步驟中所需的 `AccessKeyId`、 `SecretAccessKey` 和 `SessionToken` 元素。以下範例命令說明典型的值：

   ```
   PS C:\> $Creds.AccessKeyId
   AKIAIOSFODNN7EXAMPLE
   
   PS C:\> $Creds.SecretAccessKey
   wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
   
   PS C:\> $Creds.SessionToken
   AQoDYXdzEGcaEXAMPLE2gsYULo+Im5ZEXAMPLEeYjs1M2FUIgIJx9tQqNMBEXAMPLECvSRyh0FW7jEXAMPLEW+vE/7s1HRp
   XviG7b+qYf4nD00EXAMPLEmj4wxS04L/uZEXAMPLECihzFB5lTYLto9dyBgSDyEXAMPLE9/g7QRUhZp4bqbEXAMPLENwGPy
   Oj59pFA4lNKCIkVgkREXAMPLEjlzxQ7y52gekeVEXAMPLEDiB9ST3UuysgsKdEXAMPLE1TVastU1A0SKFEXAMPLEiywCC/C
   s8EXAMPLEpZgOs+6hz4AP4KEXAMPLERbASP+4eZScEXAMPLEsnf87eNhyDHq6ikBQ==
   
   PS C:\> $Creds.Expiration
   Thursday, June 18, 2018 2:28:31 PM
   ```

1. 若要將這些憑證用於任何後續命令，請將它們包含在 `-Credential` 參數中。例如，以下命令使用角色中的憑證，僅在角色被授予 `iam:ListRoles` 許可且因此可以執行 `Get-IAMRoles` cmdlet 時才起作用：

   ```
           PS C:\> get-iamroles -Credential $Creds
   ```

1. 若要傳回原始憑證，只需停止使用 `-Credentials $Creds` 參數，並允許 PowerShell 恢復存放在預設設定檔中的憑證。

# 切換到 IAM 角色 (AWS API)
<a name="id_roles_use_switch-role-api"></a>

「角色」**指定一組許可，您可以使用它來存取 AWS 資源。從這個意義上說，類似於 [IAM 使用者](https://docs.aws.amazon.com/IAM/latest/UserGuide/id.html)。委託人 （人員或應用程式） 擔任角色來接收臨時許可，以執行必要的任務並與 AWS 資源互動。該角色可以在您自己的帳戶或任何其他 AWS 帳戶中。如需有關角色、其優勢以及建立和設定方式的詳細資訊，請參閱 [IAM 角色](id_roles.md) 和 [IAM 角色建立](id_roles_create.md)。要了解在擔任角色時使用的各種方法，請參閱 [擔任角色的方法](id_roles_manage-assume.md)。

**重要**  
您的 IAM 使用者以及您擔任的任何角色的許可都不會累計。每次只有一組許可是作用中。當您擔任角色時，您會暫時放棄以前的使用者或角色許可，並使用指派給該角色的許可。當您退出角色後，原本的許可會自動恢復。

若要擔任角色，應用程式會 AWS STS [https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html)呼叫 API 操作，並傳遞要使用的角色 ARN。此操作會建立使用臨時憑證的新工作階段。此工作階段的許可，即為以身分為基礎的政策指派給角色的許可。

當您呼叫 [https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) 時，您可以選擇性地傳遞內嵌或受管[工作階段政策](access_policies.md#policies_session)。工作階段政策是一種進階政策，且您會在以程式設計方式建立角色或聯合身分使用者工作階段的臨時憑證工作階段時，以參數方式傳遞。您可以使用 `Policy` 參數傳遞單一 JSON 內嵌工作階段政策文件。您可以使用 `PolicyArns` 參數，指定多達 10 個受管工作階段政策。所產生工作階段的許可會是實體的身分類型政策和工作階段政策的交集。當您需要將角色的臨時憑證提供給某人時，工作階段政策便可派上用場。他們可以在後續 AWS API 呼叫中，使用角色的臨時憑證來存取擁有該角色的帳戶中的資源。您無法使用工作階段政策來授予超出即將以身分為基礎政策所允許的許可。若要進一步了解 如何 AWS 決定角色的有效許可，請參閱 [政策評估邏輯](reference_policies_evaluation-logic.md)。

![\[PermissionsWhenPassingRoles_Diagram\]](http://docs.aws.amazon.com/zh_tw/IAM/latest/UserGuide/images/role_passed_policy_permissions.png)


當您以 IAM 使用者身分登入，或者作為已使用角色的[外部身分驗證使用者](id_roles_providers.md) ([SAML](id_roles_providers_saml.md) 或 [OIDC](id_roles_providers_oidc.md)) 登入時，可以呼叫 `AssumeRole`。您還可以使用[*角色鏈結*](id_roles.md#iam-term-role-chaining)，它使用角色來擔任第二個角色。當您以 AWS 帳戶根使用者身分登入時，則無法擔任該角色。

在預設情況下，您的角色工作階段持續一小時。當您使用 AWS STS [https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) API 操作擔任此角色時，您可以指定 `DurationSeconds` 參數的值。此值的範圍可以從 900 秒 (15 分鐘) 到角色的最大工作階段持續時間設定的值。若要了解如何檢視角色的最大值，請參閱 [更新角色的最大工作階段持續時間](id_roles_update-role-settings.md#id_roles_update-session-duration)。

如果使用角色鏈結時，則工作階段最多限制為一小時。如果您隨後使用 `DurationSeconds` 參數提供大於一小時的值，則操作會失敗。

**注意**  
基於安全考量，管理員可以[檢閱 AWS CloudTrail 日誌](cloudtrail-integration.md#cloudtrail-integration_signin-tempcreds)，以了解在其中執行動作的人員 AWS。當您擔任角色時，系統管理員可能需要您指定來源身分或角色工作階段名稱 。如需詳細資訊，請參閱[`sts:SourceIdentity`](reference_policies_iam-condition-keys.md#ck_sourceidentity)及[`sts:RoleSessionName`](reference_policies_iam-condition-keys.md#ck_rolesessionname)。

下列程式碼範例示範如何建立使用者並擔任角色。

**警告**  
為避免安全風險，在開發專用軟體或使用真實資料時，請勿使用 IAM 使用者進行身分驗證。相反地，搭配使用聯合功能和身分提供者，例如 [AWS IAM Identity Center](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html)。
+ 建立沒有許可的使用者。
+ 建立一個可授予許可的角色，以列出帳戶的 Amazon S3 儲存貯體。
+ 新增政策，讓使用者擔任該角色。
+ 使用暫時憑證，擔任角色並列出 S3 儲存貯體，然後清理資源。

------
#### [ .NET ]

**適用於 .NET 的 SDK**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/IAM#code-examples)中設定和執行。

```
global using Amazon.IdentityManagement;
global using Amazon.S3;
global using Amazon.SecurityToken;
global using IAMActions;
global using IamScenariosCommon;
global using Microsoft.Extensions.DependencyInjection;
global using Microsoft.Extensions.Hosting;
global using Microsoft.Extensions.Logging;
global using Microsoft.Extensions.Logging.Console;
global using Microsoft.Extensions.Logging.Debug;


namespace IAMActions;

public class IAMWrapper
{
    private readonly IAmazonIdentityManagementService _IAMService;

    /// <summary>
    /// Constructor for the IAMWrapper class.
    /// </summary>
    /// <param name="IAMService">An IAM client object.</param>
    public IAMWrapper(IAmazonIdentityManagementService IAMService)
    {
        _IAMService = IAMService;
    }

    /// <summary>
    /// Attach an IAM policy to a role.
    /// </summary>
    /// <param name="policyArn">The policy to attach.</param>
    /// <param name="roleName">The role that the policy will be attached to.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> AttachRolePolicyAsync(string policyArn, string roleName)
    {
        var response = await _IAMService.AttachRolePolicyAsync(new AttachRolePolicyRequest
        {
            PolicyArn = policyArn,
            RoleName = roleName,
        });

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }


    /// <summary>
    /// Create an IAM access key for a user.
    /// </summary>
    /// <param name="userName">The username for which to create the IAM access
    /// key.</param>
    /// <returns>The AccessKey.</returns>
    public async Task<AccessKey> CreateAccessKeyAsync(string userName)
    {
        var response = await _IAMService.CreateAccessKeyAsync(new CreateAccessKeyRequest
        {
            UserName = userName,
        });

        return response.AccessKey;

    }


    /// <summary>
    /// Create an IAM policy.
    /// </summary>
    /// <param name="policyName">The name to give the new IAM policy.</param>
    /// <param name="policyDocument">The policy document for the new policy.</param>
    /// <returns>The new IAM policy object.</returns>
    public async Task<ManagedPolicy> CreatePolicyAsync(string policyName, string policyDocument)
    {
        var response = await _IAMService.CreatePolicyAsync(new CreatePolicyRequest
        {
            PolicyDocument = policyDocument,
            PolicyName = policyName,
        });

        return response.Policy;
    }


    /// <summary>
    /// Create a new IAM role.
    /// </summary>
    /// <param name="roleName">The name of the IAM role.</param>
    /// <param name="rolePolicyDocument">The name of the IAM policy document
    /// for the new role.</param>
    /// <returns>The Amazon Resource Name (ARN) of the role.</returns>
    public async Task<string> CreateRoleAsync(string roleName, string rolePolicyDocument)
    {
        var request = new CreateRoleRequest
        {
            RoleName = roleName,
            AssumeRolePolicyDocument = rolePolicyDocument,
        };

        var response = await _IAMService.CreateRoleAsync(request);
        return response.Role.Arn;
    }


    /// <summary>
    /// Create an IAM service-linked role.
    /// </summary>
    /// <param name="serviceName">The name of the AWS Service.</param>
    /// <param name="description">A description of the IAM service-linked role.</param>
    /// <returns>The IAM role that was created.</returns>
    public async Task<Role> CreateServiceLinkedRoleAsync(string serviceName, string description)
    {
        var request = new CreateServiceLinkedRoleRequest
        {
            AWSServiceName = serviceName,
            Description = description
        };

        var response = await _IAMService.CreateServiceLinkedRoleAsync(request);
        return response.Role;
    }


    /// <summary>
    /// Create an IAM user.
    /// </summary>
    /// <param name="userName">The username for the new IAM user.</param>
    /// <returns>The IAM user that was created.</returns>
    public async Task<User> CreateUserAsync(string userName)
    {
        var response = await _IAMService.CreateUserAsync(new CreateUserRequest { UserName = userName });
        return response.User;
    }


    /// <summary>
    /// Delete an IAM user's access key.
    /// </summary>
    /// <param name="accessKeyId">The Id for the IAM access key.</param>
    /// <param name="userName">The username of the user that owns the IAM
    /// access key.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteAccessKeyAsync(string accessKeyId, string userName)
    {
        var response = await _IAMService.DeleteAccessKeyAsync(new DeleteAccessKeyRequest
        {
            AccessKeyId = accessKeyId,
            UserName = userName,
        });

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }


    /// <summary>
    /// Delete an IAM policy.
    /// </summary>
    /// <param name="policyArn">The Amazon Resource Name (ARN) of the policy to
    /// delete.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeletePolicyAsync(string policyArn)
    {
        var response = await _IAMService.DeletePolicyAsync(new DeletePolicyRequest { PolicyArn = policyArn });
        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }


    /// <summary>
    /// Delete an IAM role.
    /// </summary>
    /// <param name="roleName">The name of the IAM role to delete.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteRoleAsync(string roleName)
    {
        var response = await _IAMService.DeleteRoleAsync(new DeleteRoleRequest { RoleName = roleName });
        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }


    /// <summary>
    /// Delete an IAM role policy.
    /// </summary>
    /// <param name="roleName">The name of the IAM role.</param>
    /// <param name="policyName">The name of the IAM role policy to delete.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteRolePolicyAsync(string roleName, string policyName)
    {
        var response = await _IAMService.DeleteRolePolicyAsync(new DeleteRolePolicyRequest
        {
            PolicyName = policyName,
            RoleName = roleName,
        });

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }


    /// <summary>
    /// Delete an IAM user.
    /// </summary>
    /// <param name="userName">The username of the IAM user to delete.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteUserAsync(string userName)
    {
        var response = await _IAMService.DeleteUserAsync(new DeleteUserRequest { UserName = userName });

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }


    /// <summary>
    /// Delete an IAM user policy.
    /// </summary>
    /// <param name="policyName">The name of the IAM policy to delete.</param>
    /// <param name="userName">The username of the IAM user.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteUserPolicyAsync(string policyName, string userName)
    {
        var response = await _IAMService.DeleteUserPolicyAsync(new DeleteUserPolicyRequest { PolicyName = policyName, UserName = userName });

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }


    /// <summary>
    /// Detach an IAM policy from an IAM role.
    /// </summary>
    /// <param name="policyArn">The Amazon Resource Name (ARN) of the IAM policy.</param>
    /// <param name="roleName">The name of the IAM role.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DetachRolePolicyAsync(string policyArn, string roleName)
    {
        var response = await _IAMService.DetachRolePolicyAsync(new DetachRolePolicyRequest
        {
            PolicyArn = policyArn,
            RoleName = roleName,
        });

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }


    /// <summary>
    /// Gets the IAM password policy for an AWS account.
    /// </summary>
    /// <returns>The PasswordPolicy for the AWS account.</returns>
    public async Task<PasswordPolicy> GetAccountPasswordPolicyAsync()
    {
        var response = await _IAMService.GetAccountPasswordPolicyAsync(new GetAccountPasswordPolicyRequest());
        return response.PasswordPolicy;
    }


    /// <summary>
    /// Get information about an IAM policy.
    /// </summary>
    /// <param name="policyArn">The IAM policy to retrieve information for.</param>
    /// <returns>The IAM policy.</returns>
    public async Task<ManagedPolicy> GetPolicyAsync(string policyArn)
    {

        var response = await _IAMService.GetPolicyAsync(new GetPolicyRequest { PolicyArn = policyArn });
        return response.Policy;
    }


    /// <summary>
    /// Get information about an IAM role.
    /// </summary>
    /// <param name="roleName">The name of the IAM role to retrieve information
    /// for.</param>
    /// <returns>The IAM role that was retrieved.</returns>
    public async Task<Role> GetRoleAsync(string roleName)
    {
        var response = await _IAMService.GetRoleAsync(new GetRoleRequest
        {
            RoleName = roleName,
        });

        return response.Role;
    }


    /// <summary>
    /// Get information about an IAM user.
    /// </summary>
    /// <param name="userName">The username of the user.</param>
    /// <returns>An IAM user object.</returns>
    public async Task<User> GetUserAsync(string userName)
    {
        var response = await _IAMService.GetUserAsync(new GetUserRequest { UserName = userName });
        return response.User;
    }


    /// <summary>
    /// List the IAM role policies that are attached to an IAM role.
    /// </summary>
    /// <param name="roleName">The IAM role to list IAM policies for.</param>
    /// <returns>A list of the IAM policies attached to the IAM role.</returns>
    public async Task<List<AttachedPolicyType>> ListAttachedRolePoliciesAsync(string roleName)
    {
        var attachedPolicies = new List<AttachedPolicyType>();
        var attachedRolePoliciesPaginator = _IAMService.Paginators.ListAttachedRolePolicies(new ListAttachedRolePoliciesRequest { RoleName = roleName });

        await foreach (var response in attachedRolePoliciesPaginator.Responses)
        {
            attachedPolicies.AddRange(response.AttachedPolicies);
        }

        return attachedPolicies;
    }


    /// <summary>
    /// List IAM groups.
    /// </summary>
    /// <returns>A list of IAM groups.</returns>
    public async Task<List<Group>> ListGroupsAsync()
    {
        var groupsPaginator = _IAMService.Paginators.ListGroups(new ListGroupsRequest());
        var groups = new List<Group>();

        await foreach (var response in groupsPaginator.Responses)
        {
            groups.AddRange(response.Groups);
        }

        return groups;
    }


    /// <summary>
    /// List IAM policies.
    /// </summary>
    /// <returns>A list of the IAM policies.</returns>
    public async Task<List<ManagedPolicy>> ListPoliciesAsync()
    {
        var listPoliciesPaginator = _IAMService.Paginators.ListPolicies(new ListPoliciesRequest());
        var policies = new List<ManagedPolicy>();

        await foreach (var response in listPoliciesPaginator.Responses)
        {
            policies.AddRange(response.Policies);
        }

        return policies;
    }


    /// <summary>
    /// List IAM role policies.
    /// </summary>
    /// <param name="roleName">The IAM role for which to list IAM policies.</param>
    /// <returns>A list of IAM policy names.</returns>
    public async Task<List<string>> ListRolePoliciesAsync(string roleName)
    {
        var listRolePoliciesPaginator = _IAMService.Paginators.ListRolePolicies(new ListRolePoliciesRequest { RoleName = roleName });
        var policyNames = new List<string>();

        await foreach (var response in listRolePoliciesPaginator.Responses)
        {
            policyNames.AddRange(response.PolicyNames);
        }

        return policyNames;
    }


    /// <summary>
    /// List IAM roles.
    /// </summary>
    /// <returns>A list of IAM roles.</returns>
    public async Task<List<Role>> ListRolesAsync()
    {
        var listRolesPaginator = _IAMService.Paginators.ListRoles(new ListRolesRequest());
        var roles = new List<Role>();

        await foreach (var response in listRolesPaginator.Responses)
        {
            roles.AddRange(response.Roles);
        }

        return roles;
    }


    /// <summary>
    /// List SAML authentication providers.
    /// </summary>
    /// <returns>A list of SAML providers.</returns>
    public async Task<List<SAMLProviderListEntry>> ListSAMLProvidersAsync()
    {
        var response = await _IAMService.ListSAMLProvidersAsync(new ListSAMLProvidersRequest());
        return response.SAMLProviderList;
    }


    /// <summary>
    /// List IAM users.
    /// </summary>
    /// <returns>A list of IAM users.</returns>
    public async Task<List<User>> ListUsersAsync()
    {
        var listUsersPaginator = _IAMService.Paginators.ListUsers(new ListUsersRequest());
        var users = new List<User>();

        await foreach (var response in listUsersPaginator.Responses)
        {
            users.AddRange(response.Users);
        }

        return users;
    }


    /// <summary>
    /// Update the inline policy document embedded in a role.
    /// </summary>
    /// <param name="policyName">The name of the policy to embed.</param>
    /// <param name="roleName">The name of the role to update.</param>
    /// <param name="policyDocument">The policy document that defines the role.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> PutRolePolicyAsync(string policyName, string roleName, string policyDocument)
    {
        var request = new PutRolePolicyRequest
        {
            PolicyName = policyName,
            RoleName = roleName,
            PolicyDocument = policyDocument
        };

        var response = await _IAMService.PutRolePolicyAsync(request);
        return response.HttpStatusCode == HttpStatusCode.OK;
    }


    /// <summary>
    /// Add or update an inline policy document that is embedded in an IAM user.
    /// </summary>
    /// <param name="userName">The name of the IAM user.</param>
    /// <param name="policyName">The name of the IAM policy.</param>
    /// <param name="policyDocument">The policy document defining the IAM policy.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> PutUserPolicyAsync(string userName, string policyName, string policyDocument)
    {
        var request = new PutUserPolicyRequest
        {
            UserName = userName,
            PolicyName = policyName,
            PolicyDocument = policyDocument
        };

        var response = await _IAMService.PutUserPolicyAsync(request);
        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }

    /// <summary>
    /// Wait for a new access key to be ready to use.
    /// </summary>
    /// <param name="accessKeyId">The Id of the access key.</param>
    /// <returns>A boolean value indicating the success of the action.</returns>
    public async Task<bool> WaitUntilAccessKeyIsReady(string accessKeyId)
    {
        var keyReady = false;

        do
        {
            try
            {
                var response = await _IAMService.GetAccessKeyLastUsedAsync(
                    new GetAccessKeyLastUsedRequest { AccessKeyId = accessKeyId });
                if (response.UserName is not null)
                {
                    keyReady = true;
                }
            }
            catch (NoSuchEntityException)
            {
                keyReady = false;
            }
        } while (!keyReady);

        return keyReady;
    }
}



using Microsoft.Extensions.Configuration;

namespace IAMBasics;

public class IAMBasics
{
    private static ILogger logger = null!;

    static async Task Main(string[] args)
    {
        // Set up dependency injection for the AWS service.
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logging =>
                logging.AddFilter("System", LogLevel.Debug)
                    .AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information)
                    .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace))
            .ConfigureServices((_, services) =>
            services.AddAWSService<IAmazonIdentityManagementService>()
            .AddTransient<IAMWrapper>()
            .AddTransient<UIWrapper>()
            )
            .Build();

        logger = LoggerFactory.Create(builder => { builder.AddConsole(); })
            .CreateLogger<IAMBasics>();


        IConfiguration configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("settings.json") // Load test settings from .json file.
            .AddJsonFile("settings.local.json",
                true) // Optionally load local settings.
            .Build();

        // Values needed for user, role, and policies.
        string userName = configuration["UserName"]!;
        string s3PolicyName = configuration["S3PolicyName"]!;
        string roleName = configuration["RoleName"]!;


        var iamWrapper = host.Services.GetRequiredService<IAMWrapper>();
        var uiWrapper = host.Services.GetRequiredService<UIWrapper>();

        uiWrapper.DisplayBasicsOverview();
        uiWrapper.PressEnter();

        // First create a user. By default, the new user has
        // no permissions.
        uiWrapper.DisplayTitle("Create User");
        Console.WriteLine($"Creating a new user with user name: {userName}.");
        var user = await iamWrapper.CreateUserAsync(userName);
        var userArn = user.Arn;

        Console.WriteLine($"Successfully created user: {userName} with ARN: {userArn}.");
        uiWrapper.WaitABit(15, "Now let's wait for the user to be ready for use.");

        // Define a role policy document that allows the new user
        // to assume the role.
        string assumeRolePolicyDocument = "{" +
          "\"Version\": \"2012-10-17\"," +
          "\"Statement\": [{" +
              "\"Effect\": \"Allow\"," +
              "\"Principal\": {" +
              $"	\"AWS\": \"{userArn}\"" +
              "}," +
              "\"Action\": \"sts:AssumeRole\"" +
          "}]" +
        "}";

        // Permissions to list all buckets.
        string policyDocument = "{" +
            "\"Version\": \"2012-10-17\"," +
            "	\"Statement\" : [{" +
                "	\"Action\" : [\"s3:ListAllMyBuckets\"]," +
                "	\"Effect\" : \"Allow\"," +
                "	\"Resource\" : \"*\"" +
            "}]" +
        "}";

        // Create an AccessKey for the user.
        uiWrapper.DisplayTitle("Create access key");
        Console.WriteLine("Now let's create an access key for the new user.");
        var accessKey = await iamWrapper.CreateAccessKeyAsync(userName);

        var accessKeyId = accessKey.AccessKeyId;
        var secretAccessKey = accessKey.SecretAccessKey;

        Console.WriteLine($"We have created the access key with Access key id: {accessKeyId}.");

        Console.WriteLine("Now let's wait until the IAM access key is ready to use.");
        var keyReady = await iamWrapper.WaitUntilAccessKeyIsReady(accessKeyId);

        // Now try listing the Amazon Simple Storage Service (Amazon S3)
        // buckets. This should fail at this point because the user doesn't
        // have permissions to perform this task.
        uiWrapper.DisplayTitle("Try to display Amazon S3 buckets");
        Console.WriteLine("Now let's try to display a list of the user's Amazon S3 buckets.");
        var s3Client1 = new AmazonS3Client(accessKeyId, secretAccessKey);
        var stsClient1 = new AmazonSecurityTokenServiceClient(accessKeyId, secretAccessKey);

        var s3Wrapper = new S3Wrapper(s3Client1, stsClient1);
        var buckets = await s3Wrapper.ListMyBucketsAsync();

        Console.WriteLine(buckets is null
            ? "As expected, the call to list the buckets has returned a null list."
            : "Something went wrong. This shouldn't have worked.");

        uiWrapper.PressEnter();

        uiWrapper.DisplayTitle("Create IAM role");
        Console.WriteLine($"Creating the role: {roleName}");

        // Creating an IAM role to allow listing the S3 buckets. A role name
        // is not case sensitive and must be unique to the account for which it
        // is created.
        var roleArn = await iamWrapper.CreateRoleAsync(roleName, assumeRolePolicyDocument);

        uiWrapper.PressEnter();

        // Create a policy with permissions to list S3 buckets.
        uiWrapper.DisplayTitle("Create IAM policy");
        Console.WriteLine($"Creating the policy: {s3PolicyName}");
        Console.WriteLine("with permissions to list the Amazon S3 buckets for the account.");
        var policy = await iamWrapper.CreatePolicyAsync(s3PolicyName, policyDocument);

        // Wait 15 seconds for the IAM policy to be available.
        uiWrapper.WaitABit(15, "Waiting for the policy to be available.");

        // Attach the policy to the role you created earlier.
        uiWrapper.DisplayTitle("Attach new IAM policy");
        Console.WriteLine("Now let's attach the policy to the role.");
        await iamWrapper.AttachRolePolicyAsync(policy.Arn, roleName);

        // Wait 15 seconds for the role to be updated.
        Console.WriteLine();
        uiWrapper.WaitABit(15, "Waiting for the policy to be attached.");

        // Use the AWS Security Token Service (AWS STS) to have the user
        // assume the role we created.
        var stsClient2 = new AmazonSecurityTokenServiceClient(accessKeyId, secretAccessKey);

        // Wait for the new credentials to become valid.
        uiWrapper.WaitABit(10, "Waiting for the credentials to be valid.");

        var assumedRoleCredentials = await s3Wrapper.AssumeS3RoleAsync("temporary-session", roleArn);

        // Try again to list the buckets using the client created with
        // the new user's credentials. This time, it should work.
        var s3Client2 = new AmazonS3Client(assumedRoleCredentials);

        s3Wrapper.UpdateClients(s3Client2, stsClient2);

        buckets = await s3Wrapper.ListMyBucketsAsync();

        uiWrapper.DisplayTitle("List Amazon S3 buckets");
        Console.WriteLine("This time we should have buckets to list.");
        if (buckets is not null)
        {
            buckets.ForEach(bucket =>
            {
                Console.WriteLine($"{bucket.BucketName} created: {bucket.CreationDate}");
            });
        }

        uiWrapper.PressEnter();

        // Now clean up all the resources used in the example.
        uiWrapper.DisplayTitle("Clean up resources");
        Console.WriteLine("Thank you for watching. The IAM Basics demo is complete.");
        Console.WriteLine("Please wait while we clean up the resources we created.");

        await iamWrapper.DetachRolePolicyAsync(policy.Arn, roleName);

        await iamWrapper.DeletePolicyAsync(policy.Arn);

        await iamWrapper.DeleteRoleAsync(roleName);

        await iamWrapper.DeleteAccessKeyAsync(accessKeyId, userName);

        await iamWrapper.DeleteUserAsync(userName);

        uiWrapper.PressEnter();

        Console.WriteLine("All done cleaning up our resources. Thank you for your patience.");
    }
}


namespace IamScenariosCommon;

using System.Net;

/// <summary>
/// A class to perform Amazon Simple Storage Service (Amazon S3) actions for
/// the IAM Basics scenario.
/// </summary>
public class S3Wrapper
{
    private IAmazonS3 _s3Service;
    private IAmazonSecurityTokenService _stsService;

    /// <summary>
    /// Constructor for the S3Wrapper class.
    /// </summary>
    /// <param name="s3Service">An Amazon S3 client object.</param>
    /// <param name="stsService">An AWS Security Token Service (AWS STS)
    /// client object.</param>
    public S3Wrapper(IAmazonS3 s3Service, IAmazonSecurityTokenService stsService)
    {
        _s3Service = s3Service;
        _stsService = stsService;
    }

    /// <summary>
    /// Assumes an AWS Identity and Access Management (IAM) role that allows
    /// Amazon S3 access for the current session.
    /// </summary>
    /// <param name="roleSession">A string representing the current session.</param>
    /// <param name="roleToAssume">The name of the IAM role to assume.</param>
    /// <returns>Credentials for the newly assumed IAM role.</returns>
    public async Task<Credentials> AssumeS3RoleAsync(string roleSession, string roleToAssume)
    {
        // Create the request to use with the AssumeRoleAsync call.
        var request = new AssumeRoleRequest()
        {
            RoleSessionName = roleSession,
            RoleArn = roleToAssume,
        };

        var response = await _stsService.AssumeRoleAsync(request);

        return response.Credentials;
    }


    /// <summary>
    /// Delete an S3 bucket.
    /// </summary>
    /// <param name="bucketName">Name of the S3 bucket to delete.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteBucketAsync(string bucketName)
    {
        var result = await _s3Service.DeleteBucketAsync(new DeleteBucketRequest { BucketName = bucketName });
        return result.HttpStatusCode == HttpStatusCode.OK;
    }

    /// <summary>
    /// List the buckets that are owned by the user's account.
    /// </summary>
    /// <returns>Async Task.</returns>
    public async Task<List<S3Bucket>?> ListMyBucketsAsync()
    {
        try
        {
            // Get the list of buckets accessible by the new user.
            var response = await _s3Service.ListBucketsAsync();

            return response.Buckets;
        }
        catch (AmazonS3Exception ex)
        {
            // Something else went wrong. Display the error message.
            Console.WriteLine($"Error: {ex.Message}");
            return null;
        }
    }

    /// <summary>
    /// Create a new S3 bucket.
    /// </summary>
    /// <param name="bucketName">The name for the new bucket.</param>
    /// <returns>A Boolean value indicating whether the action completed
    /// successfully.</returns>
    public async Task<bool> PutBucketAsync(string bucketName)
    {
        var response = await _s3Service.PutBucketAsync(new PutBucketRequest { BucketName = bucketName });
        return response.HttpStatusCode == HttpStatusCode.OK;
    }

    /// <summary>
    /// Update the client objects with new client objects. This is available
    /// because the scenario uses the methods of this class without and then
    /// with the proper permissions to list S3 buckets.
    /// </summary>
    /// <param name="s3Service">The Amazon S3 client object.</param>
    /// <param name="stsService">The AWS STS client object.</param>
    public void UpdateClients(IAmazonS3 s3Service, IAmazonSecurityTokenService stsService)
    {
        _s3Service = s3Service;
        _stsService = stsService;
    }
}


namespace IamScenariosCommon;

public class UIWrapper
{
    public readonly string SepBar = new('-', Console.WindowWidth);

    /// <summary>
    /// Show information about the IAM Groups scenario.
    /// </summary>
    public void DisplayGroupsOverview()
    {
        Console.Clear();

        DisplayTitle("Welcome to the IAM Groups Demo");
        Console.WriteLine("This example application does the following:");
        Console.WriteLine("\t1. Creates an Amazon Identity and Access Management (IAM) group.");
        Console.WriteLine("\t2. Adds an IAM policy to the IAM group giving it full access to Amazon S3.");
        Console.WriteLine("\t3. Creates a new IAM user.");
        Console.WriteLine("\t4. Creates an IAM access key for the user.");
        Console.WriteLine("\t5. Adds the user to the IAM group.");
        Console.WriteLine("\t6. Lists the buckets on the account.");
        Console.WriteLine("\t7. Proves that the user has full Amazon S3 access by creating a bucket.");
        Console.WriteLine("\t8. List the buckets again to show the new bucket.");
        Console.WriteLine("\t9. Cleans up all the resources created.");
    }

    /// <summary>
    /// Show information about the IAM Basics scenario.
    /// </summary>
    public void DisplayBasicsOverview()
    {
        Console.Clear();

        DisplayTitle("Welcome to IAM Basics");
        Console.WriteLine("This example application does the following:");
        Console.WriteLine("\t1. Creates a user with no permissions.");
        Console.WriteLine("\t2. Creates a role and policy that grant s3:ListAllMyBuckets permission.");
        Console.WriteLine("\t3. Grants the user permission to assume the role.");
        Console.WriteLine("\t4. Creates an S3 client object as the user and tries to list buckets (this will fail).");
        Console.WriteLine("\t5. Gets temporary credentials by assuming the role.");
        Console.WriteLine("\t6. Creates a new S3 client object with the temporary credentials and lists the buckets (this will succeed).");
        Console.WriteLine("\t7. Deletes all the resources.");
    }

    /// <summary>
    /// Display a message and wait until the user presses enter.
    /// </summary>
    public void PressEnter()
    {
        Console.Write("\nPress <Enter> to continue. ");
        _ = Console.ReadLine();
        Console.WriteLine();
    }

    /// <summary>
    /// Pad a string with spaces to center it on the console display.
    /// </summary>
    /// <param name="strToCenter">The string to be centered.</param>
    /// <returns>The padded string.</returns>
    public string CenterString(string strToCenter)
    {
        var padAmount = (Console.WindowWidth - strToCenter.Length) / 2;
        var leftPad = new string(' ', padAmount);
        return $"{leftPad}{strToCenter}";
    }

    /// <summary>
    /// Display a line of hyphens, the centered text of the title, and another
    /// line of hyphens.
    /// </summary>
    /// <param name="strTitle">The string to be displayed.</param>
    public void DisplayTitle(string strTitle)
    {
        Console.WriteLine(SepBar);
        Console.WriteLine(CenterString(strTitle));
        Console.WriteLine(SepBar);
    }

    /// <summary>
    /// Display a countdown and wait for a number of seconds.
    /// </summary>
    /// <param name="numSeconds">The number of seconds to wait.</param>
    public void WaitABit(int numSeconds, string msg)
    {
        Console.WriteLine(msg);

        // Wait for the requested number of seconds.
        for (int i = numSeconds; i > 0; i--)
        {
            System.Threading.Thread.Sleep(1000);
            Console.Write($"{i}...");
        }

        PressEnter();
    }
}
```
+ 如需 API 詳細資訊，請參閱《*適用於 .NET 的 AWS SDK API 參考*》中的下列主題。
  + [AttachRolePolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/AttachRolePolicy)
  + [CreateAccessKey](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/CreateAccessKey)
  + [CreatePolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/CreatePolicy)
  + [CreateRole](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/CreateRole)
  + [CreateUser](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/CreateUser)
  + [DeleteAccessKey](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DeleteAccessKey)
  + [DeletePolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DeletePolicy)
  + [DeleteRole](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DeleteRole)
  + [DeleteUser](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DeleteUser)
  + [DeleteUserPolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DeleteUserPolicy)
  + [DetachRolePolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DetachRolePolicy)
  + [PutUserPolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/PutUserPolicy)

------
#### [ Bash ]

**AWS CLI 使用 Bash 指令碼**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/iam#code-examples)中設定和執行。

```
###############################################################################
# function iam_create_user_assume_role
#
# Scenario to create an IAM user, create an IAM role, and apply the role to the user.
#
#     "IAM access" permissions are needed to run this code.
#     "STS assume role" permissions are needed to run this code. (Note: It might be necessary to
#           create a custom policy).
#
# Returns:
#       0 - If successful.
#       1 - If an error occurred.
###############################################################################
function iam_create_user_assume_role() {
  {
    if [ "$IAM_OPERATIONS_SOURCED" != "True" ]; then

      source ./iam_operations.sh
    fi
  }

  echo_repeat "*" 88
  echo "Welcome to the IAM create user and assume role demo."
  echo
  echo "This demo will create an IAM user, create an IAM role, and apply the role to the user."
  echo_repeat "*" 88
  echo

  echo -n "Enter a name for a new IAM user: "
  get_input
  user_name=$get_input_result

  local user_arn
  user_arn=$(iam_create_user -u "$user_name")

  # shellcheck disable=SC2181
  if [[ ${?} == 0 ]]; then
    echo "Created demo IAM user named $user_name"
  else
    errecho "$user_arn"
    errecho "The user failed to create. This demo will exit."
    return 1
  fi

  local access_key_response
  access_key_response=$(iam_create_user_access_key -u "$user_name")
  # shellcheck disable=SC2181
  if [[ ${?} != 0 ]]; then
    errecho "The access key failed to create. This demo will exit."
    clean_up "$user_name"
    return 1
  fi

  IFS=$'\t ' read -r -a access_key_values <<<"$access_key_response"
  local key_name=${access_key_values[0]}
  local key_secret=${access_key_values[1]}

  echo "Created access key named $key_name"

  echo "Wait 10 seconds for the user to be ready."
  sleep 10
  echo_repeat "*" 88
  echo

  local iam_role_name
  iam_role_name=$(generate_random_name "test-role")
  echo "Creating a role named $iam_role_name with user $user_name as the principal."

  local assume_role_policy_document="{
    \"Version\": \"2012-10-17\",
    \"Statement\": [{
        \"Effect\": \"Allow\",
        \"Principal\": {\"AWS\": \"$user_arn\"},
        \"Action\": \"sts:AssumeRole\"
        }]
    }"

  local role_arn
  role_arn=$(iam_create_role -n "$iam_role_name" -p "$assume_role_policy_document")

  # shellcheck disable=SC2181
  if [ ${?} == 0 ]; then
    echo "Created IAM role named $iam_role_name"
  else
    errecho "The role failed to create. This demo will exit."
    clean_up "$user_name" "$key_name"
    return 1
  fi

  local policy_name
  policy_name=$(generate_random_name "test-policy")
  local policy_document="{
                \"Version\": \"2012-10-17\",
                \"Statement\": [{
                    \"Effect\": \"Allow\",
                    \"Action\": \"s3:ListAllMyBuckets\",
                    \"Resource\": \"arn:aws:s3:::*\"}]}"

  local policy_arn
  policy_arn=$(iam_create_policy -n "$policy_name" -p "$policy_document")
  # shellcheck disable=SC2181
  if [[ ${?} == 0 ]]; then
    echo "Created  IAM policy named $policy_name"
  else
    errecho "The policy failed to create."
    clean_up "$user_name" "$key_name" "$iam_role_name"
    return 1
  fi

  if (iam_attach_role_policy -n "$iam_role_name" -p "$policy_arn"); then
    echo "Attached policy $policy_arn to role $iam_role_name"
  else
    errecho "The policy failed to attach."
    clean_up "$user_name" "$key_name" "$iam_role_name" "$policy_arn"
    return 1
  fi

  local assume_role_policy_document="{
                \"Version\": \"2012-10-17\",
                \"Statement\": [{
                    \"Effect\": \"Allow\",
                    \"Action\": \"sts:AssumeRole\",
                    \"Resource\": \"$role_arn\"}]}"

  local assume_role_policy_name
  assume_role_policy_name=$(generate_random_name "test-assume-role-")

  # shellcheck disable=SC2181
  local assume_role_policy_arn
  assume_role_policy_arn=$(iam_create_policy -n "$assume_role_policy_name" -p "$assume_role_policy_document")
  # shellcheck disable=SC2181
  if [ ${?} == 0 ]; then
    echo "Created  IAM policy named $assume_role_policy_name for sts assume role"
  else
    errecho "The policy failed to create."
    clean_up "$user_name" "$key_name" "$iam_role_name" "$policy_arn" "$policy_arn"
    return 1
  fi

  echo "Wait 10 seconds to give AWS time to propagate these new resources and connections."
  sleep 10
  echo_repeat "*" 88
  echo

  echo "Try to list buckets without the new user assuming the role."
  echo_repeat "*" 88
  echo

  # Set the environment variables for the created user.
  # bashsupport disable=BP2001
  export AWS_ACCESS_KEY_ID=$key_name
  # bashsupport disable=BP2001
  export AWS_SECRET_ACCESS_KEY=$key_secret

  local buckets
  buckets=$(s3_list_buckets)

  # shellcheck disable=SC2181
  if [ ${?} == 0 ]; then
    local bucket_count
    bucket_count=$(echo "$buckets" | wc -w | xargs)
    echo "There are $bucket_count buckets in the account. This should not have happened."
  else
    errecho "Because the role with permissions has not been assumed, listing buckets failed."
  fi

  echo
  echo_repeat "*" 88
  echo "Now assume the role $iam_role_name and list the buckets."
  echo_repeat "*" 88
  echo

  local credentials

  credentials=$(sts_assume_role -r "$role_arn" -n "AssumeRoleDemoSession")
  # shellcheck disable=SC2181
  if [ ${?} == 0 ]; then
    echo "Assumed role $iam_role_name"
  else
    errecho "Failed to assume role."
    export AWS_ACCESS_KEY_ID=""
    export AWS_SECRET_ACCESS_KEY=""
    clean_up "$user_name" "$key_name" "$iam_role_name" "$policy_arn" "$policy_arn" "$assume_role_policy_arn"
    return 1
  fi

  IFS=$'\t ' read -r -a credentials <<<"$credentials"

  export AWS_ACCESS_KEY_ID=${credentials[0]}
  export AWS_SECRET_ACCESS_KEY=${credentials[1]}
  # bashsupport disable=BP2001
  export AWS_SESSION_TOKEN=${credentials[2]}

  buckets=$(s3_list_buckets)

  # shellcheck disable=SC2181
  if [ ${?} == 0 ]; then
    local bucket_count
    bucket_count=$(echo "$buckets" | wc -w | xargs)
    echo "There are $bucket_count buckets in the account. Listing buckets succeeded because of "
    echo "the assumed role."
  else
    errecho "Failed to list buckets. This should not happen."
    export AWS_ACCESS_KEY_ID=""
    export AWS_SECRET_ACCESS_KEY=""
    export AWS_SESSION_TOKEN=""
    clean_up "$user_name" "$key_name" "$iam_role_name" "$policy_arn" "$policy_arn" "$assume_role_policy_arn"
    return 1
  fi

  local result=0
  export AWS_ACCESS_KEY_ID=""
  export AWS_SECRET_ACCESS_KEY=""

  echo
  echo_repeat "*" 88
  echo "The created resources will now be deleted."
  echo_repeat "*" 88
  echo

  clean_up "$user_name" "$key_name" "$iam_role_name" "$policy_arn" "$policy_arn" "$assume_role_policy_arn"

  # shellcheck disable=SC2181
  if [[ ${?} -ne 0 ]]; then
    result=1
  fi

  return $result
}
```
此案例中使用的 IAM 函數。  

```
###############################################################################
# function iam_user_exists
#
# This function checks to see if the specified AWS Identity and Access Management (IAM) user already exists.
#
# Parameters:
#       $1 - The name of the IAM user to check.
#
# Returns:
#       0 - If the user already exists.
#       1 - If the user doesn't exist.
###############################################################################
function iam_user_exists() {
  local user_name
  user_name=$1

  # Check whether the IAM user already exists.
  # We suppress all output - we're interested only in the return code.

  local errors
  errors=$(aws iam get-user \
    --user-name "$user_name" 2>&1 >/dev/null)

  local error_code=${?}

  if [[ $error_code -eq 0 ]]; then
    return 0 # 0 in Bash script means true.
  else
    if [[ $errors != *"error"*"(NoSuchEntity)"* ]]; then
      aws_cli_error_log $error_code
      errecho "Error calling iam get-user $errors"
    fi

    return 1 # 1 in Bash script means false.
  fi
}

###############################################################################
# function iam_create_user
#
# This function creates the specified IAM user, unless
# it already exists.
#
# Parameters:
#       -u user_name  -- The name of the user to create.
#
# Returns:
#       The ARN of the user.
#     And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_create_user() {
  local user_name response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_create_user"
    echo "Creates an AWS Identity and Access Management (IAM) user. You must supply a username:"
    echo "  -u user_name    The name of the user. It must be unique within the account."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "u:h" option; do
    case "${option}" in
      u) user_name="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$user_name" ]]; then
    errecho "ERROR: You must provide a username with the -u parameter."
    usage
    return 1
  fi

  iecho "Parameters:\n"
  iecho "    User name:   $user_name"
  iecho ""

  # If the user already exists, we don't want to try to create it.
  if (iam_user_exists "$user_name"); then
    errecho "ERROR: A user with that name already exists in the account."
    return 1
  fi

  response=$(aws iam create-user --user-name "$user_name" \
    --output text \
    --query 'User.Arn')

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports create-user operation failed.$response"
    return 1
  fi

  echo "$response"

  return 0
}

###############################################################################
# function iam_create_user_access_key
#
# This function creates an IAM access key for the specified user.
#
# Parameters:
#       -u user_name -- The name of the IAM user.
#       [-f file_name] -- The optional file name for the access key output.
#
# Returns:
#       [access_key_id access_key_secret]
#     And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_create_user_access_key() {
  local user_name file_name response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_create_user_access_key"
    echo "Creates an AWS Identity and Access Management (IAM) key pair."
    echo "  -u user_name   The name of the IAM user."
    echo "  [-f file_name]   Optional file name for the access key output."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "u:f:h" option; do
    case "${option}" in
      u) user_name="${OPTARG}" ;;
      f) file_name="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$user_name" ]]; then
    errecho "ERROR: You must provide a username with the -u parameter."
    usage
    return 1
  fi

  response=$(aws iam create-access-key \
    --user-name "$user_name" \
    --output text)

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports create-access-key operation failed.$response"
    return 1
  fi

  if [[ -n "$file_name" ]]; then
    echo "$response" >"$file_name"
  fi

  local key_id key_secret
  # shellcheck disable=SC2086
  key_id=$(echo $response | cut -f 2 -d ' ')
  # shellcheck disable=SC2086
  key_secret=$(echo $response | cut -f 4 -d ' ')

  echo "$key_id $key_secret"

  return 0
}

###############################################################################
# function iam_create_role
#
# This function creates an IAM role.
#
# Parameters:
#       -n role_name -- The name of the IAM role.
#       -p policy_json -- The assume role policy document.
#
# Returns:
#       The ARN of the role.
#     And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_create_role() {
  local role_name policy_document response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_create_user_access_key"
    echo "Creates an AWS Identity and Access Management (IAM) role."
    echo "  -n role_name   The name of the IAM role."
    echo "  -p policy_json -- The assume role policy document."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:p:h" option; do
    case "${option}" in
      n) role_name="${OPTARG}" ;;
      p) policy_document="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$role_name" ]]; then
    errecho "ERROR: You must provide a role name with the -n parameter."
    usage
    return 1
  fi

  if [[ -z "$policy_document" ]]; then
    errecho "ERROR: You must provide a policy document with the -p parameter."
    usage
    return 1
  fi

  response=$(aws iam create-role \
    --role-name "$role_name" \
    --assume-role-policy-document "$policy_document" \
    --output text \
    --query Role.Arn)

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports create-role operation failed.\n$response"
    return 1
  fi

  echo "$response"

  return 0
}

###############################################################################
# function iam_create_policy
#
# This function creates an IAM policy.
#
# Parameters:
#       -n policy_name -- The name of the IAM policy.
#       -p policy_json -- The policy document.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_create_policy() {
  local policy_name policy_document response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_create_policy"
    echo "Creates an AWS Identity and Access Management (IAM) policy."
    echo "  -n policy_name   The name of the IAM policy."
    echo "  -p policy_json -- The policy document."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:p:h" option; do
    case "${option}" in
      n) policy_name="${OPTARG}" ;;
      p) policy_document="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$policy_name" ]]; then
    errecho "ERROR: You must provide a policy name with the -n parameter."
    usage
    return 1
  fi

  if [[ -z "$policy_document" ]]; then
    errecho "ERROR: You must provide a policy document with the -p parameter."
    usage
    return 1
  fi

  response=$(aws iam create-policy \
    --policy-name "$policy_name" \
    --policy-document "$policy_document" \
    --output text \
    --query Policy.Arn)

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports create-policy operation failed.\n$response"
    return 1
  fi

  echo "$response"
}

###############################################################################
# function iam_attach_role_policy
#
# This function attaches an IAM policy to a tole.
#
# Parameters:
#       -n role_name -- The name of the IAM role.
#       -p policy_ARN -- The IAM policy document ARN..
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_attach_role_policy() {
  local role_name policy_arn response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_attach_role_policy"
    echo "Attaches an AWS Identity and Access Management (IAM) policy to an IAM role."
    echo "  -n role_name   The name of the IAM role."
    echo "  -p policy_ARN -- The IAM policy document ARN."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:p:h" option; do
    case "${option}" in
      n) role_name="${OPTARG}" ;;
      p) policy_arn="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$role_name" ]]; then
    errecho "ERROR: You must provide a role name with the -n parameter."
    usage
    return 1
  fi

  if [[ -z "$policy_arn" ]]; then
    errecho "ERROR: You must provide a policy ARN with the -p parameter."
    usage
    return 1
  fi

  response=$(aws iam attach-role-policy \
    --role-name "$role_name" \
    --policy-arn "$policy_arn")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports attach-role-policy operation failed.\n$response"
    return 1
  fi

  echo "$response"

  return 0
}

###############################################################################
# function iam_detach_role_policy
#
# This function detaches an IAM policy to a tole.
#
# Parameters:
#       -n role_name -- The name of the IAM role.
#       -p policy_ARN -- The IAM policy document ARN..
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_detach_role_policy() {
  local role_name policy_arn response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_detach_role_policy"
    echo "Detaches an AWS Identity and Access Management (IAM) policy to an IAM role."
    echo "  -n role_name   The name of the IAM role."
    echo "  -p policy_ARN -- The IAM policy document ARN."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:p:h" option; do
    case "${option}" in
      n) role_name="${OPTARG}" ;;
      p) policy_arn="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$role_name" ]]; then
    errecho "ERROR: You must provide a role name with the -n parameter."
    usage
    return 1
  fi

  if [[ -z "$policy_arn" ]]; then
    errecho "ERROR: You must provide a policy ARN with the -p parameter."
    usage
    return 1
  fi

  response=$(aws iam detach-role-policy \
    --role-name "$role_name" \
    --policy-arn "$policy_arn")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports detach-role-policy operation failed.\n$response"
    return 1
  fi

  echo "$response"

  return 0
}

###############################################################################
# function iam_delete_policy
#
# This function deletes an IAM policy.
#
# Parameters:
#       -n policy_arn -- The name of the IAM policy arn.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_delete_policy() {
  local policy_arn response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_delete_policy"
    echo "Deletes an AWS Identity and Access Management (IAM) policy"
    echo "  -n policy_arn -- The name of the IAM policy arn."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:h" option; do
    case "${option}" in
      n) policy_arn="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$policy_arn" ]]; then
    errecho "ERROR: You must provide a policy arn with the -n parameter."
    usage
    return 1
  fi

  iecho "Parameters:\n"
  iecho "    Policy arn:  $policy_arn"
  iecho ""

  response=$(aws iam delete-policy \
    --policy-arn "$policy_arn")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports delete-policy operation failed.\n$response"
    return 1
  fi

  iecho "delete-policy response:$response"
  iecho

  return 0
}

###############################################################################
# function iam_delete_role
#
# This function deletes an IAM role.
#
# Parameters:
#       -n role_name -- The name of the IAM role.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_delete_role() {
  local role_name response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_delete_role"
    echo "Deletes an AWS Identity and Access Management (IAM) role"
    echo "  -n role_name -- The name of the IAM role."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:h" option; do
    case "${option}" in
      n) role_name="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  echo "role_name:$role_name"
  if [[ -z "$role_name" ]]; then
    errecho "ERROR: You must provide a role name with the -n parameter."
    usage
    return 1
  fi

  iecho "Parameters:\n"
  iecho "    Role name:  $role_name"
  iecho ""

  response=$(aws iam delete-role \
    --role-name "$role_name")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports delete-role operation failed.\n$response"
    return 1
  fi

  iecho "delete-role response:$response"
  iecho

  return 0
}

###############################################################################
# function iam_delete_access_key
#
# This function deletes an IAM access key for the specified IAM user.
#
# Parameters:
#       -u user_name  -- The name of the user.
#       -k access_key -- The access key to delete.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_delete_access_key() {
  local user_name access_key response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_delete_access_key"
    echo "Deletes an AWS Identity and Access Management (IAM) access key for the specified IAM user"
    echo "  -u user_name    The name of the user."
    echo "  -k access_key   The access key to delete."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "u:k:h" option; do
    case "${option}" in
      u) user_name="${OPTARG}" ;;
      k) access_key="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$user_name" ]]; then
    errecho "ERROR: You must provide a username with the -u parameter."
    usage
    return 1
  fi

  if [[ -z "$access_key" ]]; then
    errecho "ERROR: You must provide an access key with the -k parameter."
    usage
    return 1
  fi

  iecho "Parameters:\n"
  iecho "    Username:   $user_name"
  iecho "    Access key:   $access_key"
  iecho ""

  response=$(aws iam delete-access-key \
    --user-name "$user_name" \
    --access-key-id "$access_key")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports delete-access-key operation failed.\n$response"
    return 1
  fi

  iecho "delete-access-key response:$response"
  iecho

  return 0
}

###############################################################################
# function iam_delete_user
#
# This function deletes the specified IAM user.
#
# Parameters:
#       -u user_name  -- The name of the user to create.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_delete_user() {
  local user_name response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_delete_user"
    echo "Deletes an AWS Identity and Access Management (IAM) user. You must supply a username:"
    echo "  -u user_name    The name of the user."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "u:h" option; do
    case "${option}" in
      u) user_name="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$user_name" ]]; then
    errecho "ERROR: You must provide a username with the -u parameter."
    usage
    return 1
  fi

  iecho "Parameters:\n"
  iecho "    User name:   $user_name"
  iecho ""

  # If the user does not exist, we don't want to try to delete it.
  if (! iam_user_exists "$user_name"); then
    errecho "ERROR: A user with that name does not exist in the account."
    return 1
  fi

  response=$(aws iam delete-user \
    --user-name "$user_name")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports delete-user operation failed.$response"
    return 1
  fi

  iecho "delete-user response:$response"
  iecho

  return 0
}
```
+ 如需 API 詳細資訊，請參閱《*AWS CLI 命令參考*》中的下列主題。
  + [AttachRolePolicy](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/AttachRolePolicy)
  + [CreateAccessKey](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/CreateAccessKey)
  + [CreatePolicy](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/CreatePolicy)
  + [CreateRole](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/CreateRole)
  + [CreateUser](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/CreateUser)
  + [DeleteAccessKey](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/DeleteAccessKey)
  + [DeletePolicy](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/DeletePolicy)
  + [DeleteRole](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/DeleteRole)
  + [DeleteUser](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/DeleteUser)
  + [DeleteUserPolicy](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/DeleteUserPolicy)
  + [DetachRolePolicy](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/DetachRolePolicy)
  + [PutUserPolicy](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/PutUserPolicy)

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iam#code-examples)中設定和執行。

```
namespace AwsDoc {
    namespace IAM {
  
        //! Cleanup by deleting created entities.
        /*!
          \sa DeleteCreatedEntities
          \param client: IAM client.
          \param role: IAM role.
          \param user: IAM user.
          \param policy: IAM policy.
        */
        static bool DeleteCreatedEntities(const Aws::IAM::IAMClient &client,
                                          const Aws::IAM::Model::Role &role,
                                          const Aws::IAM::Model::User &user,
                                          const Aws::IAM::Model::Policy &policy);
    }

    static const int LIST_BUCKETS_WAIT_SEC = 20;

    static const char ALLOCATION_TAG[] = "example_code";
}

//! Scenario to create an IAM user, create an IAM role, and apply the role to the user.
// "IAM access" permissions are needed to run this code.
// "STS assume role" permissions are needed to run this code. (Note: It might be necessary to
//    create a custom policy).
/*!
  \sa iamCreateUserAssumeRoleScenario
  \param clientConfig: Aws client configuration.
  \return bool: Successful completion.
*/
bool AwsDoc::IAM::iamCreateUserAssumeRoleScenario(
        const Aws::Client::ClientConfiguration &clientConfig) {

    Aws::IAM::IAMClient client(clientConfig);
    Aws::IAM::Model::User user;
    Aws::IAM::Model::Role role;
    Aws::IAM::Model::Policy policy;

    // 1. Create a user.
    {
        Aws::IAM::Model::CreateUserRequest request;
        Aws::String uuid = Aws::Utils::UUID::RandomUUID();
        Aws::String userName = "iam-demo-user-" +
                               Aws::Utils::StringUtils::ToLower(uuid.c_str());
        request.SetUserName(userName);

        Aws::IAM::Model::CreateUserOutcome outcome = client.CreateUser(request);
        if (!outcome.IsSuccess()) {
            std::cout << "Error creating IAM user " << userName << ":" <<
                      outcome.GetError().GetMessage() << std::endl;
            return false;
        }
        else {
            std::cout << "Successfully created IAM user " << userName << std::endl;
        }

        user = outcome.GetResult().GetUser();
    }

    // 2. Create a role.
    {
        // Get the IAM user for the current client in order to access its ARN.
        Aws::String iamUserArn;
        {
            Aws::IAM::Model::GetUserRequest request;
            Aws::IAM::Model::GetUserOutcome outcome = client.GetUser(request);
            if (!outcome.IsSuccess()) {
                std::cerr << "Error getting Iam user. " <<
                          outcome.GetError().GetMessage() << std::endl;

                DeleteCreatedEntities(client, role, user, policy);
                return false;
            }
            else {
                std::cout << "Successfully retrieved Iam user "
                          << outcome.GetResult().GetUser().GetUserName()
                          << std::endl;
            }

            iamUserArn = outcome.GetResult().GetUser().GetArn();
        }

        Aws::IAM::Model::CreateRoleRequest request;

        Aws::String uuid = Aws::Utils::UUID::RandomUUID();
        Aws::String roleName = "iam-demo-role-" +
                               Aws::Utils::StringUtils::ToLower(uuid.c_str());
        request.SetRoleName(roleName);

        // Build policy document for role.
        Aws::Utils::Document jsonStatement;
        jsonStatement.WithString("Effect", "Allow");

        Aws::Utils::Document jsonPrincipal;
        jsonPrincipal.WithString("AWS", iamUserArn);
        jsonStatement.WithObject("Principal", jsonPrincipal);
        jsonStatement.WithString("Action", "sts:AssumeRole");
        jsonStatement.WithObject("Condition", Aws::Utils::Document());

        Aws::Utils::Document policyDocument;
        policyDocument.WithString("Version", "2012-10-17");

        Aws::Utils::Array<Aws::Utils::Document> statements(1);
        statements[0] = jsonStatement;
        policyDocument.WithArray("Statement", statements);

        std::cout << "Setting policy for role\n   "
                  << policyDocument.View().WriteCompact() << std::endl;

        // Set role policy document as JSON string.
        request.SetAssumeRolePolicyDocument(policyDocument.View().WriteCompact());

        Aws::IAM::Model::CreateRoleOutcome outcome = client.CreateRole(request);
        if (!outcome.IsSuccess()) {
            std::cerr << "Error creating role. " <<
                      outcome.GetError().GetMessage() << std::endl;

            DeleteCreatedEntities(client, role, user, policy);
            return false;
        }
        else {
            std::cout << "Successfully created a role with name " << roleName
                      << std::endl;
        }

        role = outcome.GetResult().GetRole();
    }

    // 3. Create an IAM policy.
    {
        Aws::IAM::Model::CreatePolicyRequest request;
        Aws::String uuid = Aws::Utils::UUID::RandomUUID();
        Aws::String policyName = "iam-demo-policy-" +
                                 Aws::Utils::StringUtils::ToLower(uuid.c_str());
        request.SetPolicyName(policyName);

        // Build IAM policy document.
        Aws::Utils::Document jsonStatement;
        jsonStatement.WithString("Effect", "Allow");
        jsonStatement.WithString("Action", "s3:ListAllMyBuckets");
        jsonStatement.WithString("Resource", "arn:aws:s3:::*");

        Aws::Utils::Document policyDocument;
        policyDocument.WithString("Version", "2012-10-17");

        Aws::Utils::Array<Aws::Utils::Document> statements(1);
        statements[0] = jsonStatement;
        policyDocument.WithArray("Statement", statements);

        std::cout << "Creating a policy.\n   " << policyDocument.View().WriteCompact()
                  << std::endl;

        // Set IAM policy document as JSON string.
        request.SetPolicyDocument(policyDocument.View().WriteCompact());

        Aws::IAM::Model::CreatePolicyOutcome outcome = client.CreatePolicy(request);
        if (!outcome.IsSuccess()) {
            std::cerr << "Error creating policy. " <<
                      outcome.GetError().GetMessage() << std::endl;

            DeleteCreatedEntities(client, role, user, policy);
            return false;
        }
        else {
            std::cout << "Successfully created a policy with name, " << policyName <<
                      "." << std::endl;
        }

        policy = outcome.GetResult().GetPolicy();
    }

    // 4. Assume the new role using the AWS Security Token Service (STS).
    Aws::STS::Model::Credentials credentials;
    {
        Aws::STS::STSClient stsClient(clientConfig);

        Aws::STS::Model::AssumeRoleRequest request;
        request.SetRoleArn(role.GetArn());
        Aws::String uuid = Aws::Utils::UUID::RandomUUID();
        Aws::String roleSessionName = "iam-demo-role-session-" +
                                      Aws::Utils::StringUtils::ToLower(uuid.c_str());
        request.SetRoleSessionName(roleSessionName);

        Aws::STS::Model::AssumeRoleOutcome assumeRoleOutcome;

        // Repeatedly call AssumeRole, because there is often a delay
        // before the role is available to be assumed.
        // Repeat at most 20 times when access is denied.
        int count = 0;
        while (true) {
            assumeRoleOutcome = stsClient.AssumeRole(request);
            if (!assumeRoleOutcome.IsSuccess()) {
                if (count > 20 ||
                    assumeRoleOutcome.GetError().GetErrorType() !=
                    Aws::STS::STSErrors::ACCESS_DENIED) {
                    std::cerr << "Error assuming role after 20 tries. " <<
                              assumeRoleOutcome.GetError().GetMessage() << std::endl;

                    DeleteCreatedEntities(client, role, user, policy);
                    return false;
                }
                std::this_thread::sleep_for(std::chrono::seconds(1));
            }
            else {
                std::cout << "Successfully assumed the role after " << count
                          << " seconds." << std::endl;
                break;
            }
            count++;
        }

        credentials = assumeRoleOutcome.GetResult().GetCredentials();
    }


    // 5. List objects in the bucket (This should fail).
    {
        Aws::S3::S3Client s3Client(
                Aws::Auth::AWSCredentials(credentials.GetAccessKeyId(),
                                          credentials.GetSecretAccessKey(),
                                          credentials.GetSessionToken()),
                Aws::MakeShared<Aws::S3::S3EndpointProvider>(ALLOCATION_TAG),
                clientConfig);
        Aws::S3::Model::ListBucketsOutcome listBucketsOutcome = s3Client.ListBuckets();
        if (!listBucketsOutcome.IsSuccess()) {
            if (listBucketsOutcome.GetError().GetErrorType() !=
                Aws::S3::S3Errors::ACCESS_DENIED) {
                std::cerr << "Could not lists buckets. " <<
                          listBucketsOutcome.GetError().GetMessage() << std::endl;
            }
            else {
                std::cout
                        << "Access to list buckets denied because privileges have not been applied."
                        << std::endl;
            }
        }
        else {
            std::cerr
                    << "Successfully retrieved bucket lists when this should not happen."
                    << std::endl;
        }
    }

    // 6. Attach the policy to the role.
    {
        Aws::IAM::Model::AttachRolePolicyRequest request;
        request.SetRoleName(role.GetRoleName());
        request.WithPolicyArn(policy.GetArn());

        Aws::IAM::Model::AttachRolePolicyOutcome outcome = client.AttachRolePolicy(
                request);
        if (!outcome.IsSuccess()) {
            std::cerr << "Error creating policy. " <<
                      outcome.GetError().GetMessage() << std::endl;

            DeleteCreatedEntities(client, role, user, policy);
            return false;
        }
        else {
            std::cout << "Successfully attached the policy with name, "
                      << policy.GetPolicyName() <<
                      ", to the role, " << role.GetRoleName() << "." << std::endl;
        }
    }

    int count = 0;
    // 7. List objects in the bucket (this should succeed).
    // Repeatedly call ListBuckets, because there is often a delay
    // before the policy with ListBucket permissions has been applied to the role.
    // Repeat at most LIST_BUCKETS_WAIT_SEC times when access is denied.
    while (true) {
        Aws::S3::S3Client s3Client(
                Aws::Auth::AWSCredentials(credentials.GetAccessKeyId(),
                                          credentials.GetSecretAccessKey(),
                                          credentials.GetSessionToken()),
                Aws::MakeShared<Aws::S3::S3EndpointProvider>(ALLOCATION_TAG),
                clientConfig);
        Aws::S3::Model::ListBucketsOutcome listBucketsOutcome = s3Client.ListBuckets();
        if (!listBucketsOutcome.IsSuccess()) {
            if ((count > LIST_BUCKETS_WAIT_SEC) ||
                listBucketsOutcome.GetError().GetErrorType() !=
                Aws::S3::S3Errors::ACCESS_DENIED) {
                std::cerr << "Could not lists buckets after " << LIST_BUCKETS_WAIT_SEC << " seconds. " <<
                          listBucketsOutcome.GetError().GetMessage() << std::endl;
                DeleteCreatedEntities(client, role, user, policy);
                return false;
            }

            std::this_thread::sleep_for(std::chrono::seconds(1));
        }
        else {

            std::cout << "Successfully retrieved bucket lists after " << count
                      << " seconds." << std::endl;
            break;
        }
        count++;
    }

    // 8. Delete all the created resources.
    return DeleteCreatedEntities(client, role, user, policy);
}

bool AwsDoc::IAM::DeleteCreatedEntities(const Aws::IAM::IAMClient &client,
                                        const Aws::IAM::Model::Role &role,
                                        const Aws::IAM::Model::User &user,
                                        const Aws::IAM::Model::Policy &policy) {
    bool result = true;
    if (policy.ArnHasBeenSet()) {
        // Detach the policy from the role.
        {
            Aws::IAM::Model::DetachRolePolicyRequest request;
            request.SetPolicyArn(policy.GetArn());
            request.SetRoleName(role.GetRoleName());

            Aws::IAM::Model::DetachRolePolicyOutcome outcome = client.DetachRolePolicy(
                    request);
            if (!outcome.IsSuccess()) {
                std::cerr << "Error Detaching policy from roles. " <<
                          outcome.GetError().GetMessage() << std::endl;
                result = false;
            }
            else {
                std::cout << "Successfully detached the policy with arn "
                          << policy.GetArn()
                          << " from role " << role.GetRoleName() << "." << std::endl;
            }
        }

        // Delete the policy.
        {
            Aws::IAM::Model::DeletePolicyRequest request;
            request.WithPolicyArn(policy.GetArn());

            Aws::IAM::Model::DeletePolicyOutcome outcome = client.DeletePolicy(request);
            if (!outcome.IsSuccess()) {
                std::cerr << "Error deleting policy. " <<
                          outcome.GetError().GetMessage() << std::endl;
                result = false;
            }
            else {
                std::cout << "Successfully deleted the policy with arn "
                          << policy.GetArn() << std::endl;
            }
        }

    }

    if (role.RoleIdHasBeenSet()) {
        // Delete the role.
        Aws::IAM::Model::DeleteRoleRequest request;
        request.SetRoleName(role.GetRoleName());

        Aws::IAM::Model::DeleteRoleOutcome outcome = client.DeleteRole(request);
        if (!outcome.IsSuccess()) {
            std::cerr << "Error deleting role. " <<
                      outcome.GetError().GetMessage() << std::endl;
            result = false;
        }
        else {
            std::cout << "Successfully deleted the role with name "
                      << role.GetRoleName() << std::endl;
        }
    }

    if (user.ArnHasBeenSet()) {
        // Delete the user.
        Aws::IAM::Model::DeleteUserRequest request;
        request.WithUserName(user.GetUserName());

        Aws::IAM::Model::DeleteUserOutcome outcome = client.DeleteUser(request);
        if (!outcome.IsSuccess()) {
            std::cerr << "Error deleting user. " <<
                      outcome.GetError().GetMessage() << std::endl;
            result = false;
        }
        else {
            std::cout << "Successfully deleted the user with name "
                      << user.GetUserName() << std::endl;
        }
    }

    return result;
}
```
+ 如需 API 詳細資訊，請參閱《*適用於 C\$1\$1 的 AWS SDK API 參考*》中的下列主題。
  + [AttachRolePolicy](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/AttachRolePolicy)
  + [CreateAccessKey](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/CreateAccessKey)
  + [CreatePolicy](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/CreatePolicy)
  + [CreateRole](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/CreateRole)
  + [CreateUser](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/CreateUser)
  + [DeleteAccessKey](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/DeleteAccessKey)
  + [DeletePolicy](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/DeletePolicy)
  + [DeleteRole](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/DeleteRole)
  + [DeleteUser](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/DeleteUser)
  + [DeleteUserPolicy](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/DeleteUserPolicy)
  + [DetachRolePolicy](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/DetachRolePolicy)
  + [PutUserPolicy](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/PutUserPolicy)

------
#### [ Go ]

**SDK for Go V2**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/iam#code-examples)中設定和執行。
在命令提示中執行互動式案例。  

```
import (
	"context"
	"errors"
	"fmt"
	"log"
	"math/rand"
	"strings"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/credentials"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/aws/aws-sdk-go-v2/service/sts"
	"github.com/aws/smithy-go"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/demotools"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/iam/actions"
)

// AssumeRoleScenario shows you how to use the AWS Identity and Access Management (IAM)
// service to perform the following actions:
//
//  1. Create a user who has no permissions.
//  2. Create a role that grants permission to list Amazon Simple Storage Service
//     (Amazon S3) buckets for the account.
//  3. Add a policy to let the user assume the role.
//  4. Try and fail to list buckets without permissions.
//  5. Assume the role and list S3 buckets using temporary credentials.
//  6. Delete the policy, role, and user.
type AssumeRoleScenario struct {
	sdkConfig      aws.Config
	accountWrapper actions.AccountWrapper
	policyWrapper  actions.PolicyWrapper
	roleWrapper    actions.RoleWrapper
	userWrapper    actions.UserWrapper
	questioner     demotools.IQuestioner
	helper         IScenarioHelper
	isTestRun      bool
}

// NewAssumeRoleScenario constructs an AssumeRoleScenario instance from a configuration.
// It uses the specified config to get an IAM client and create wrappers for the actions
// used in the scenario.
func NewAssumeRoleScenario(sdkConfig aws.Config, questioner demotools.IQuestioner,
	helper IScenarioHelper) AssumeRoleScenario {
	iamClient := iam.NewFromConfig(sdkConfig)
	return AssumeRoleScenario{
		sdkConfig:      sdkConfig,
		accountWrapper: actions.AccountWrapper{IamClient: iamClient},
		policyWrapper:  actions.PolicyWrapper{IamClient: iamClient},
		roleWrapper:    actions.RoleWrapper{IamClient: iamClient},
		userWrapper:    actions.UserWrapper{IamClient: iamClient},
		questioner:     questioner,
		helper:         helper,
	}
}

// addTestOptions appends the API options specified in the original configuration to
// another configuration. This is used to attach the middleware stubber to clients
// that are constructed during the scenario, which is needed for unit testing.
func (scenario AssumeRoleScenario) addTestOptions(scenarioConfig *aws.Config) {
	if scenario.isTestRun {
		scenarioConfig.APIOptions = append(scenarioConfig.APIOptions, scenario.sdkConfig.APIOptions...)
	}
}

// Run runs the interactive scenario.
func (scenario AssumeRoleScenario) Run(ctx context.Context) {
	defer func() {
		if r := recover(); r != nil {
			log.Printf("Something went wrong with the demo.\n")
			log.Println(r)
		}
	}()

	log.Println(strings.Repeat("-", 88))
	log.Println("Welcome to the AWS Identity and Access Management (IAM) assume role demo.")
	log.Println(strings.Repeat("-", 88))

	user := scenario.CreateUser(ctx)
	accessKey := scenario.CreateAccessKey(ctx, user)
	role := scenario.CreateRoleAndPolicies(ctx, user)
	noPermsConfig := scenario.ListBucketsWithoutPermissions(ctx, accessKey)
	scenario.ListBucketsWithAssumedRole(ctx, noPermsConfig, role)
	scenario.Cleanup(ctx, user, role)

	log.Println(strings.Repeat("-", 88))
	log.Println("Thanks for watching!")
	log.Println(strings.Repeat("-", 88))
}

// CreateUser creates a new IAM user. This user has no permissions.
func (scenario AssumeRoleScenario) CreateUser(ctx context.Context) *types.User {
	log.Println("Let's create an example user with no permissions.")
	userName := scenario.questioner.Ask("Enter a name for the example user:", demotools.NotEmpty{})
	user, err := scenario.userWrapper.GetUser(ctx, userName)
	if err != nil {
		panic(err)
	}
	if user == nil {
		user, err = scenario.userWrapper.CreateUser(ctx, userName)
		if err != nil {
			panic(err)
		}
		log.Printf("Created user %v.\n", *user.UserName)
	} else {
		log.Printf("User %v already exists.\n", *user.UserName)
	}
	log.Println(strings.Repeat("-", 88))
	return user
}

// CreateAccessKey creates an access key for the user.
func (scenario AssumeRoleScenario) CreateAccessKey(ctx context.Context, user *types.User) *types.AccessKey {
	accessKey, err := scenario.userWrapper.CreateAccessKeyPair(ctx, *user.UserName)
	if err != nil {
		panic(err)
	}
	log.Printf("Created access key %v for your user.", *accessKey.AccessKeyId)
	log.Println("Waiting a few seconds for your user to be ready...")
	scenario.helper.Pause(10)
	log.Println(strings.Repeat("-", 88))
	return accessKey
}

// CreateRoleAndPolicies creates a policy that grants permission to list S3 buckets for
// the current account and attaches the policy to a newly created role. It also adds an
// inline policy to the specified user that grants the user permission to assume the role.
func (scenario AssumeRoleScenario) CreateRoleAndPolicies(ctx context.Context, user *types.User) *types.Role {
	log.Println("Let's create a role and policy that grant permission to list S3 buckets.")
	scenario.questioner.Ask("Press Enter when you're ready.")
	listBucketsRole, err := scenario.roleWrapper.CreateRole(ctx, scenario.helper.GetName(), *user.Arn)
	if err != nil {
		panic(err)
	}
	log.Printf("Created role %v.\n", *listBucketsRole.RoleName)
	listBucketsPolicy, err := scenario.policyWrapper.CreatePolicy(
		ctx, scenario.helper.GetName(), []string{"s3:ListAllMyBuckets"}, "arn:aws:s3:::*")
	if err != nil {
		panic(err)
	}
	log.Printf("Created policy %v.\n", *listBucketsPolicy.PolicyName)
	err = scenario.roleWrapper.AttachRolePolicy(ctx, *listBucketsPolicy.Arn, *listBucketsRole.RoleName)
	if err != nil {
		panic(err)
	}
	log.Printf("Attached policy %v to role %v.\n", *listBucketsPolicy.PolicyName,
		*listBucketsRole.RoleName)
	err = scenario.userWrapper.CreateUserPolicy(ctx, *user.UserName, scenario.helper.GetName(),
		[]string{"sts:AssumeRole"}, *listBucketsRole.Arn)
	if err != nil {
		panic(err)
	}
	log.Printf("Created an inline policy for user %v that lets the user assume the role.\n",
		*user.UserName)
	log.Println("Let's give AWS a few seconds to propagate these new resources and connections...")
	scenario.helper.Pause(10)
	log.Println(strings.Repeat("-", 88))
	return listBucketsRole
}

// ListBucketsWithoutPermissions creates an Amazon S3 client from the user's access key
// credentials and tries to list buckets for the account. Because the user does not have
// permission to perform this action, the action fails.
func (scenario AssumeRoleScenario) ListBucketsWithoutPermissions(ctx context.Context, accessKey *types.AccessKey) *aws.Config {
	log.Println("Let's try to list buckets without permissions. This should return an AccessDenied error.")
	scenario.questioner.Ask("Press Enter when you're ready.")
	noPermsConfig, err := config.LoadDefaultConfig(ctx,
		config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(
			*accessKey.AccessKeyId, *accessKey.SecretAccessKey, ""),
		))
	if err != nil {
		panic(err)
	}

	// Add test options if this is a test run. This is needed only for testing purposes.
	scenario.addTestOptions(&noPermsConfig)

	s3Client := s3.NewFromConfig(noPermsConfig)
	_, err = s3Client.ListBuckets(ctx, &s3.ListBucketsInput{})
	if err != nil {
		// The SDK for Go does not model the AccessDenied error, so check ErrorCode directly.
		var ae smithy.APIError
		if errors.As(err, &ae) {
			switch ae.ErrorCode() {
			case "AccessDenied":
				log.Println("Got AccessDenied error, which is the expected result because\n" +
					"the ListBuckets call was made without permissions.")
			default:
				log.Println("Expected AccessDenied, got something else.")
				panic(err)
			}
		}
	} else {
		log.Println("Expected AccessDenied error when calling ListBuckets without permissions,\n" +
			"but the call succeeded. Continuing the example anyway...")
	}
	log.Println(strings.Repeat("-", 88))
	return &noPermsConfig
}

// ListBucketsWithAssumedRole performs the following actions:
//
//  1. Creates an AWS Security Token Service (AWS STS) client from the config created from
//     the user's access key credentials.
//  2. Gets temporary credentials by assuming the role that grants permission to list the
//     buckets.
//  3. Creates an Amazon S3 client from the temporary credentials.
//  4. Lists buckets for the account. Because the temporary credentials are generated by
//     assuming the role that grants permission, the action succeeds.
func (scenario AssumeRoleScenario) ListBucketsWithAssumedRole(ctx context.Context, noPermsConfig *aws.Config, role *types.Role) {
	log.Println("Let's assume the role that grants permission to list buckets and try again.")
	scenario.questioner.Ask("Press Enter when you're ready.")
	stsClient := sts.NewFromConfig(*noPermsConfig)
	tempCredentials, err := stsClient.AssumeRole(ctx, &sts.AssumeRoleInput{
		RoleArn:         role.Arn,
		RoleSessionName: aws.String("AssumeRoleExampleSession"),
		DurationSeconds: aws.Int32(900),
	})
	if err != nil {
		log.Printf("Couldn't assume role %v.\n", *role.RoleName)
		panic(err)
	}
	log.Printf("Assumed role %v, got temporary credentials.\n", *role.RoleName)
	assumeRoleConfig, err := config.LoadDefaultConfig(ctx,
		config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(
			*tempCredentials.Credentials.AccessKeyId,
			*tempCredentials.Credentials.SecretAccessKey,
			*tempCredentials.Credentials.SessionToken),
		),
	)
	if err != nil {
		panic(err)
	}

	// Add test options if this is a test run. This is needed only for testing purposes.
	scenario.addTestOptions(&assumeRoleConfig)

	s3Client := s3.NewFromConfig(assumeRoleConfig)
	result, err := s3Client.ListBuckets(ctx, &s3.ListBucketsInput{})
	if err != nil {
		log.Println("Couldn't list buckets with assumed role credentials.")
		panic(err)
	}
	log.Println("Successfully called ListBuckets with assumed role credentials, \n" +
		"here are some of them:")
	for i := 0; i < len(result.Buckets) && i < 5; i++ {
		log.Printf("\t%v\n", *result.Buckets[i].Name)
	}
	log.Println(strings.Repeat("-", 88))
}

// Cleanup deletes all resources created for the scenario.
func (scenario AssumeRoleScenario) Cleanup(ctx context.Context, user *types.User, role *types.Role) {
	if scenario.questioner.AskBool(
		"Do you want to delete the resources created for this example? (y/n)", "y",
	) {
		policies, err := scenario.roleWrapper.ListAttachedRolePolicies(ctx, *role.RoleName)
		if err != nil {
			panic(err)
		}
		for _, policy := range policies {
			err = scenario.roleWrapper.DetachRolePolicy(ctx, *role.RoleName, *policy.PolicyArn)
			if err != nil {
				panic(err)
			}
			err = scenario.policyWrapper.DeletePolicy(ctx, *policy.PolicyArn)
			if err != nil {
				panic(err)
			}
			log.Printf("Detached policy %v from role %v and deleted the policy.\n",
				*policy.PolicyName, *role.RoleName)
		}
		err = scenario.roleWrapper.DeleteRole(ctx, *role.RoleName)
		if err != nil {
			panic(err)
		}
		log.Printf("Deleted role %v.\n", *role.RoleName)

		userPols, err := scenario.userWrapper.ListUserPolicies(ctx, *user.UserName)
		if err != nil {
			panic(err)
		}
		for _, userPol := range userPols {
			err = scenario.userWrapper.DeleteUserPolicy(ctx, *user.UserName, userPol)
			if err != nil {
				panic(err)
			}
			log.Printf("Deleted policy %v from user %v.\n", userPol, *user.UserName)
		}
		keys, err := scenario.userWrapper.ListAccessKeys(ctx, *user.UserName)
		if err != nil {
			panic(err)
		}
		for _, key := range keys {
			err = scenario.userWrapper.DeleteAccessKey(ctx, *user.UserName, *key.AccessKeyId)
			if err != nil {
				panic(err)
			}
			log.Printf("Deleted access key %v from user %v.\n", *key.AccessKeyId, *user.UserName)
		}
		err = scenario.userWrapper.DeleteUser(ctx, *user.UserName)
		if err != nil {
			panic(err)
		}
		log.Printf("Deleted user %v.\n", *user.UserName)
		log.Println(strings.Repeat("-", 88))
	}

}

// IScenarioHelper abstracts input and wait functions from a scenario so that they
// can be mocked for unit testing.
type IScenarioHelper interface {
	GetName() string
	Pause(secs int)
}

const rMax = 100000

type ScenarioHelper struct {
	Prefix string
	Random *rand.Rand
}

// GetName returns a unique name formed of a prefix and a random number.
func (helper *ScenarioHelper) GetName() string {
	return fmt.Sprintf("%v%v", helper.Prefix, helper.Random.Intn(rMax))
}

// Pause waits for the specified number of seconds.
func (helper ScenarioHelper) Pause(secs int) {
	time.Sleep(time.Duration(secs) * time.Second)
}
```
定義包裝帳號動作的結構。  

```
import (
	"context"
	"log"

	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

// AccountWrapper encapsulates AWS Identity and Access Management (IAM) account actions
// used in the examples.
// It contains an IAM service client that is used to perform account actions.
type AccountWrapper struct {
	IamClient *iam.Client
}



// GetAccountPasswordPolicy gets the account password policy for the current account.
// If no policy has been set, a NoSuchEntityException is error is returned.
func (wrapper AccountWrapper) GetAccountPasswordPolicy(ctx context.Context) (*types.PasswordPolicy, error) {
	var pwPolicy *types.PasswordPolicy
	result, err := wrapper.IamClient.GetAccountPasswordPolicy(ctx,
		&iam.GetAccountPasswordPolicyInput{})
	if err != nil {
		log.Printf("Couldn't get account password policy. Here's why: %v\n", err)
	} else {
		pwPolicy = result.PasswordPolicy
	}
	return pwPolicy, err
}



// ListSAMLProviders gets the SAML providers for the account.
func (wrapper AccountWrapper) ListSAMLProviders(ctx context.Context) ([]types.SAMLProviderListEntry, error) {
	var providers []types.SAMLProviderListEntry
	result, err := wrapper.IamClient.ListSAMLProviders(ctx, &iam.ListSAMLProvidersInput{})
	if err != nil {
		log.Printf("Couldn't list SAML providers. Here's why: %v\n", err)
	} else {
		providers = result.SAMLProviderList
	}
	return providers, err
}
```
定義包裝政策動作的結構。  

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

// PolicyWrapper encapsulates AWS Identity and Access Management (IAM) policy actions
// used in the examples.
// It contains an IAM service client that is used to perform policy actions.
type PolicyWrapper struct {
	IamClient *iam.Client
}



// ListPolicies gets up to maxPolicies policies.
func (wrapper PolicyWrapper) ListPolicies(ctx context.Context, maxPolicies int32) ([]types.Policy, error) {
	var policies []types.Policy
	result, err := wrapper.IamClient.ListPolicies(ctx, &iam.ListPoliciesInput{
		MaxItems: aws.Int32(maxPolicies),
	})
	if err != nil {
		log.Printf("Couldn't list policies. Here's why: %v\n", err)
	} else {
		policies = result.Policies
	}
	return policies, err
}



// PolicyDocument defines a policy document as a Go struct that can be serialized
// to JSON.
type PolicyDocument struct {
	Version   string
	Statement []PolicyStatement
}

// PolicyStatement defines a statement in a policy document.
type PolicyStatement struct {
	Effect    string
	Action    []string
	Principal map[string]string `json:",omitempty"`
	Resource  *string           `json:",omitempty"`
}

// CreatePolicy creates a policy that grants a list of actions to the specified resource.
// PolicyDocument shows how to work with a policy document as a data structure and
// serialize it to JSON by using Go's JSON marshaler.
func (wrapper PolicyWrapper) CreatePolicy(ctx context.Context, policyName string, actions []string,
	resourceArn string) (*types.Policy, error) {
	var policy *types.Policy
	policyDoc := PolicyDocument{
		Version: "2012-10-17",
		Statement: []PolicyStatement{{
			Effect:   "Allow",
			Action:   actions,
			Resource: aws.String(resourceArn),
		}},
	}
	policyBytes, err := json.Marshal(policyDoc)
	if err != nil {
		log.Printf("Couldn't create policy document for %v. Here's why: %v\n", resourceArn, err)
		return nil, err
	}
	result, err := wrapper.IamClient.CreatePolicy(ctx, &iam.CreatePolicyInput{
		PolicyDocument: aws.String(string(policyBytes)),
		PolicyName:     aws.String(policyName),
	})
	if err != nil {
		log.Printf("Couldn't create policy %v. Here's why: %v\n", policyName, err)
	} else {
		policy = result.Policy
	}
	return policy, err
}



// GetPolicy gets data about a policy.
func (wrapper PolicyWrapper) GetPolicy(ctx context.Context, policyArn string) (*types.Policy, error) {
	var policy *types.Policy
	result, err := wrapper.IamClient.GetPolicy(ctx, &iam.GetPolicyInput{
		PolicyArn: aws.String(policyArn),
	})
	if err != nil {
		log.Printf("Couldn't get policy %v. Here's why: %v\n", policyArn, err)
	} else {
		policy = result.Policy
	}
	return policy, err
}



// DeletePolicy deletes a policy.
func (wrapper PolicyWrapper) DeletePolicy(ctx context.Context, policyArn string) error {
	_, err := wrapper.IamClient.DeletePolicy(ctx, &iam.DeletePolicyInput{
		PolicyArn: aws.String(policyArn),
	})
	if err != nil {
		log.Printf("Couldn't delete policy %v. Here's why: %v\n", policyArn, err)
	}
	return err
}
```
定義包裝角色動作的結構。  

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

// RoleWrapper encapsulates AWS Identity and Access Management (IAM) role actions
// used in the examples.
// It contains an IAM service client that is used to perform role actions.
type RoleWrapper struct {
	IamClient *iam.Client
}



// ListRoles gets up to maxRoles roles.
func (wrapper RoleWrapper) ListRoles(ctx context.Context, maxRoles int32) ([]types.Role, error) {
	var roles []types.Role
	result, err := wrapper.IamClient.ListRoles(ctx,
		&iam.ListRolesInput{MaxItems: aws.Int32(maxRoles)},
	)
	if err != nil {
		log.Printf("Couldn't list roles. Here's why: %v\n", err)
	} else {
		roles = result.Roles
	}
	return roles, err
}



// CreateRole creates a role that trusts a specified user. The trusted user can assume
// the role to acquire its permissions.
// PolicyDocument shows how to work with a policy document as a data structure and
// serialize it to JSON by using Go's JSON marshaler.
func (wrapper RoleWrapper) CreateRole(ctx context.Context, roleName string, trustedUserArn string) (*types.Role, error) {
	var role *types.Role
	trustPolicy := PolicyDocument{
		Version: "2012-10-17",
		Statement: []PolicyStatement{{
			Effect:    "Allow",
			Principal: map[string]string{"AWS": trustedUserArn},
			Action:    []string{"sts:AssumeRole"},
		}},
	}
	policyBytes, err := json.Marshal(trustPolicy)
	if err != nil {
		log.Printf("Couldn't create trust policy for %v. Here's why: %v\n", trustedUserArn, err)
		return nil, err
	}
	result, err := wrapper.IamClient.CreateRole(ctx, &iam.CreateRoleInput{
		AssumeRolePolicyDocument: aws.String(string(policyBytes)),
		RoleName:                 aws.String(roleName),
	})
	if err != nil {
		log.Printf("Couldn't create role %v. Here's why: %v\n", roleName, err)
	} else {
		role = result.Role
	}
	return role, err
}



// GetRole gets data about a role.
func (wrapper RoleWrapper) GetRole(ctx context.Context, roleName string) (*types.Role, error) {
	var role *types.Role
	result, err := wrapper.IamClient.GetRole(ctx,
		&iam.GetRoleInput{RoleName: aws.String(roleName)})
	if err != nil {
		log.Printf("Couldn't get role %v. Here's why: %v\n", roleName, err)
	} else {
		role = result.Role
	}
	return role, err
}



// CreateServiceLinkedRole creates a service-linked role that is owned by the specified service.
func (wrapper RoleWrapper) CreateServiceLinkedRole(ctx context.Context, serviceName string, description string) (
	*types.Role, error) {
	var role *types.Role
	result, err := wrapper.IamClient.CreateServiceLinkedRole(ctx, &iam.CreateServiceLinkedRoleInput{
		AWSServiceName: aws.String(serviceName),
		Description:    aws.String(description),
	})
	if err != nil {
		log.Printf("Couldn't create service-linked role %v. Here's why: %v\n", serviceName, err)
	} else {
		role = result.Role
	}
	return role, err
}



// DeleteServiceLinkedRole deletes a service-linked role.
func (wrapper RoleWrapper) DeleteServiceLinkedRole(ctx context.Context, roleName string) error {
	_, err := wrapper.IamClient.DeleteServiceLinkedRole(ctx, &iam.DeleteServiceLinkedRoleInput{
		RoleName: aws.String(roleName)},
	)
	if err != nil {
		log.Printf("Couldn't delete service-linked role %v. Here's why: %v\n", roleName, err)
	}
	return err
}



// AttachRolePolicy attaches a policy to a role.
func (wrapper RoleWrapper) AttachRolePolicy(ctx context.Context, policyArn string, roleName string) error {
	_, err := wrapper.IamClient.AttachRolePolicy(ctx, &iam.AttachRolePolicyInput{
		PolicyArn: aws.String(policyArn),
		RoleName:  aws.String(roleName),
	})
	if err != nil {
		log.Printf("Couldn't attach policy %v to role %v. Here's why: %v\n", policyArn, roleName, err)
	}
	return err
}



// ListAttachedRolePolicies lists the policies that are attached to the specified role.
func (wrapper RoleWrapper) ListAttachedRolePolicies(ctx context.Context, roleName string) ([]types.AttachedPolicy, error) {
	var policies []types.AttachedPolicy
	result, err := wrapper.IamClient.ListAttachedRolePolicies(ctx, &iam.ListAttachedRolePoliciesInput{
		RoleName: aws.String(roleName),
	})
	if err != nil {
		log.Printf("Couldn't list attached policies for role %v. Here's why: %v\n", roleName, err)
	} else {
		policies = result.AttachedPolicies
	}
	return policies, err
}



// DetachRolePolicy detaches a policy from a role.
func (wrapper RoleWrapper) DetachRolePolicy(ctx context.Context, roleName string, policyArn string) error {
	_, err := wrapper.IamClient.DetachRolePolicy(ctx, &iam.DetachRolePolicyInput{
		PolicyArn: aws.String(policyArn),
		RoleName:  aws.String(roleName),
	})
	if err != nil {
		log.Printf("Couldn't detach policy from role %v. Here's why: %v\n", roleName, err)
	}
	return err
}



// ListRolePolicies lists the inline policies for a role.
func (wrapper RoleWrapper) ListRolePolicies(ctx context.Context, roleName string) ([]string, error) {
	var policies []string
	result, err := wrapper.IamClient.ListRolePolicies(ctx, &iam.ListRolePoliciesInput{
		RoleName: aws.String(roleName),
	})
	if err != nil {
		log.Printf("Couldn't list policies for role %v. Here's why: %v\n", roleName, err)
	} else {
		policies = result.PolicyNames
	}
	return policies, err
}



// DeleteRole deletes a role. All attached policies must be detached before a
// role can be deleted.
func (wrapper RoleWrapper) DeleteRole(ctx context.Context, roleName string) error {
	_, err := wrapper.IamClient.DeleteRole(ctx, &iam.DeleteRoleInput{
		RoleName: aws.String(roleName),
	})
	if err != nil {
		log.Printf("Couldn't delete role %v. Here's why: %v\n", roleName, err)
	}
	return err
}
```
定義包裝使用者動作的結構。  

```
import (
	"context"
	"encoding/json"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
	"github.com/aws/smithy-go"
)

// UserWrapper encapsulates user actions used in the examples.
// It contains an IAM service client that is used to perform user actions.
type UserWrapper struct {
	IamClient *iam.Client
}



// ListUsers gets up to maxUsers number of users.
func (wrapper UserWrapper) ListUsers(ctx context.Context, maxUsers int32) ([]types.User, error) {
	var users []types.User
	result, err := wrapper.IamClient.ListUsers(ctx, &iam.ListUsersInput{
		MaxItems: aws.Int32(maxUsers),
	})
	if err != nil {
		log.Printf("Couldn't list users. Here's why: %v\n", err)
	} else {
		users = result.Users
	}
	return users, err
}



// GetUser gets data about a user.
func (wrapper UserWrapper) GetUser(ctx context.Context, userName string) (*types.User, error) {
	var user *types.User
	result, err := wrapper.IamClient.GetUser(ctx, &iam.GetUserInput{
		UserName: aws.String(userName),
	})
	if err != nil {
		var apiError smithy.APIError
		if errors.As(err, &apiError) {
			switch apiError.(type) {
			case *types.NoSuchEntityException:
				log.Printf("User %v does not exist.\n", userName)
				err = nil
			default:
				log.Printf("Couldn't get user %v. Here's why: %v\n", userName, err)
			}
		}
	} else {
		user = result.User
	}
	return user, err
}



// CreateUser creates a new user with the specified name.
func (wrapper UserWrapper) CreateUser(ctx context.Context, userName string) (*types.User, error) {
	var user *types.User
	result, err := wrapper.IamClient.CreateUser(ctx, &iam.CreateUserInput{
		UserName: aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't create user %v. Here's why: %v\n", userName, err)
	} else {
		user = result.User
	}
	return user, err
}



// CreateUserPolicy adds an inline policy to a user. This example creates a policy that
// grants a list of actions on a specified role.
// PolicyDocument shows how to work with a policy document as a data structure and
// serialize it to JSON by using Go's JSON marshaler.
func (wrapper UserWrapper) CreateUserPolicy(ctx context.Context, userName string, policyName string, actions []string,
	roleArn string) error {
	policyDoc := PolicyDocument{
		Version: "2012-10-17",
		Statement: []PolicyStatement{{
			Effect:   "Allow",
			Action:   actions,
			Resource: aws.String(roleArn),
		}},
	}
	policyBytes, err := json.Marshal(policyDoc)
	if err != nil {
		log.Printf("Couldn't create policy document for %v. Here's why: %v\n", roleArn, err)
		return err
	}
	_, err = wrapper.IamClient.PutUserPolicy(ctx, &iam.PutUserPolicyInput{
		PolicyDocument: aws.String(string(policyBytes)),
		PolicyName:     aws.String(policyName),
		UserName:       aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't create policy for user %v. Here's why: %v\n", userName, err)
	}
	return err
}



// ListUserPolicies lists the inline policies for the specified user.
func (wrapper UserWrapper) ListUserPolicies(ctx context.Context, userName string) ([]string, error) {
	var policies []string
	result, err := wrapper.IamClient.ListUserPolicies(ctx, &iam.ListUserPoliciesInput{
		UserName: aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't list policies for user %v. Here's why: %v\n", userName, err)
	} else {
		policies = result.PolicyNames
	}
	return policies, err
}



// DeleteUserPolicy deletes an inline policy from a user.
func (wrapper UserWrapper) DeleteUserPolicy(ctx context.Context, userName string, policyName string) error {
	_, err := wrapper.IamClient.DeleteUserPolicy(ctx, &iam.DeleteUserPolicyInput{
		PolicyName: aws.String(policyName),
		UserName:   aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't delete policy from user %v. Here's why: %v\n", userName, err)
	}
	return err
}



// DeleteUser deletes a user.
func (wrapper UserWrapper) DeleteUser(ctx context.Context, userName string) error {
	_, err := wrapper.IamClient.DeleteUser(ctx, &iam.DeleteUserInput{
		UserName: aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't delete user %v. Here's why: %v\n", userName, err)
	}
	return err
}



// CreateAccessKeyPair creates an access key for a user. The returned access key contains
// the ID and secret credentials needed to use the key.
func (wrapper UserWrapper) CreateAccessKeyPair(ctx context.Context, userName string) (*types.AccessKey, error) {
	var key *types.AccessKey
	result, err := wrapper.IamClient.CreateAccessKey(ctx, &iam.CreateAccessKeyInput{
		UserName: aws.String(userName)})
	if err != nil {
		log.Printf("Couldn't create access key pair for user %v. Here's why: %v\n", userName, err)
	} else {
		key = result.AccessKey
	}
	return key, err
}



// DeleteAccessKey deletes an access key from a user.
func (wrapper UserWrapper) DeleteAccessKey(ctx context.Context, userName string, keyId string) error {
	_, err := wrapper.IamClient.DeleteAccessKey(ctx, &iam.DeleteAccessKeyInput{
		AccessKeyId: aws.String(keyId),
		UserName:    aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't delete access key %v. Here's why: %v\n", keyId, err)
	}
	return err
}



// ListAccessKeys lists the access keys for the specified user.
func (wrapper UserWrapper) ListAccessKeys(ctx context.Context, userName string) ([]types.AccessKeyMetadata, error) {
	var keys []types.AccessKeyMetadata
	result, err := wrapper.IamClient.ListAccessKeys(ctx, &iam.ListAccessKeysInput{
		UserName: aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't list access keys for user %v. Here's why: %v\n", userName, err)
	} else {
		keys = result.AccessKeyMetadata
	}
	return keys, err
}
```
+ 如需 API 詳細資訊，請參閱《*適用於 Go 的 AWS SDK API 參考*》中的下列主題。
  + [AttachRolePolicy](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.AttachRolePolicy)
  + [CreateAccessKey](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.CreateAccessKey)
  + [CreatePolicy](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.CreatePolicy)
  + [CreateRole](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.CreateRole)
  + [CreateUser](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.CreateUser)
  + [DeleteAccessKey](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.DeleteAccessKey)
  + [DeletePolicy](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.DeletePolicy)
  + [DeleteRole](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.DeleteRole)
  + [DeleteUser](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.DeleteUser)
  + [DeleteUserPolicy](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.DeleteUserPolicy)
  + [DetachRolePolicy](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.DetachRolePolicy)
  + [PutUserPolicy](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.PutUserPolicy)

------
#### [ Java ]

**SDK for Java 2.x**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iam#code-examples)中設定和執行。
建立可包裝 IAM 使用者動作的函數。  

```
/*
  To run this Java V2 code example, set up your development environment, including your credentials.

  For information, see this documentation topic:

  https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html

  This example performs these operations:

  1. Creates a user that has no permissions.
  2. Creates a role and policy that grants Amazon S3 permissions.
  3. Creates a role.
  4. Grants the user permissions.
  5. Gets temporary credentials by assuming the role.  Creates an Amazon S3 Service client object with the temporary credentials.
  6. Deletes the resources.
 */

public class IAMScenario {
    public static final String DASHES = new String(new char[80]).replace("\0", "-");
    public static final String PolicyDocument = "{" +
            "  \"Version\": \"2012-10-17\"," +
            "  \"Statement\": [" +
            "    {" +
            "        \"Effect\": \"Allow\"," +
            "        \"Action\": [" +
            "            \"s3:*\"" +
            "       ]," +
            "       \"Resource\": \"*\"" +
            "    }" +
            "   ]" +
            "}";

    public static String userArn;

    public static void main(String[] args) throws Exception {

        final String usage = """

                Usage:
                    <username> <policyName> <roleName> <roleSessionName> <bucketName>\s

                Where:
                    username - The name of the IAM user to create.\s
                    policyName - The name of the policy to create.\s
                    roleName - The name of the role to create.\s
                    roleSessionName - The name of the session required for the assumeRole operation.\s
                    bucketName - The name of the Amazon S3 bucket from which objects are read.\s
                """;

        if (args.length != 5) {
            System.out.println(usage);
            System.exit(1);
        }

        String userName = args[0];
        String policyName = args[1];
        String roleName = args[2];
        String roleSessionName = args[3];
        String bucketName = args[4];

        Region region = Region.AWS_GLOBAL;
        IamClient iam = IamClient.builder()
                .region(region)
                .build();

        System.out.println(DASHES);
        System.out.println("Welcome to the AWS IAM example scenario.");
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println(" 1. Create the IAM user.");
        User createUser = createIAMUser(iam, userName);

        System.out.println(DASHES);
        userArn = createUser.arn();

        AccessKey myKey = createIAMAccessKey(iam, userName);
        String accessKey = myKey.accessKeyId();
        String secretKey = myKey.secretAccessKey();
        String assumeRolePolicyDocument = "{" +
                "\"Version\": \"2012-10-17\"," +
                "\"Statement\": [{" +
                "\"Effect\": \"Allow\"," +
                "\"Principal\": {" +
                "	\"AWS\": \"" + userArn + "\"" +
                "}," +
                "\"Action\": \"sts:AssumeRole\"" +
                "}]" +
                "}";

        System.out.println(assumeRolePolicyDocument);
        System.out.println(userName + " was successfully created.");
        System.out.println(DASHES);
        System.out.println("2. Creates a policy.");
        String polArn = createIAMPolicy(iam, policyName);
        System.out.println("The policy " + polArn + " was successfully created.");
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("3. Creates a role.");
        TimeUnit.SECONDS.sleep(30);
        String roleArn = createIAMRole(iam, roleName, assumeRolePolicyDocument);
        System.out.println(roleArn + " was successfully created.");
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("4. Grants the user permissions.");
        attachIAMRolePolicy(iam, roleName, polArn);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("*** Wait for 30 secs so the resource is available");
        TimeUnit.SECONDS.sleep(30);
        System.out.println("5. Gets temporary credentials by assuming the role.");
        System.out.println("Perform an Amazon S3 Service operation using the temporary credentials.");
        assumeRole(roleArn, roleSessionName, bucketName, accessKey, secretKey);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("6 Getting ready to delete the AWS resources");
        deleteKey(iam, userName, accessKey);
        deleteRole(iam, roleName, polArn);
        deleteIAMUser(iam, userName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("This IAM Scenario has successfully completed");
        System.out.println(DASHES);
    }

    public static AccessKey createIAMAccessKey(IamClient iam, String user) {
        try {
            CreateAccessKeyRequest request = CreateAccessKeyRequest.builder()
                    .userName(user)
                    .build();

            CreateAccessKeyResponse response = iam.createAccessKey(request);
            return response.accessKey();

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return null;
    }

    public static User createIAMUser(IamClient iam, String username) {
        try {
            // Create an IamWaiter object
            IamWaiter iamWaiter = iam.waiter();
            CreateUserRequest request = CreateUserRequest.builder()
                    .userName(username)
                    .build();

            // Wait until the user is created.
            CreateUserResponse response = iam.createUser(request);
            GetUserRequest userRequest = GetUserRequest.builder()
                    .userName(response.user().userName())
                    .build();

            WaiterResponse<GetUserResponse> waitUntilUserExists = iamWaiter.waitUntilUserExists(userRequest);
            waitUntilUserExists.matched().response().ifPresent(System.out::println);
            return response.user();

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return null;
    }

    public static String createIAMRole(IamClient iam, String rolename, String json) {

        try {
            CreateRoleRequest request = CreateRoleRequest.builder()
                    .roleName(rolename)
                    .assumeRolePolicyDocument(json)
                    .description("Created using the AWS SDK for Java")
                    .build();

            CreateRoleResponse response = iam.createRole(request);
            System.out.println("The ARN of the role is " + response.role().arn());
            return response.role().arn();

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }

    public static String createIAMPolicy(IamClient iam, String policyName) {
        try {
            // Create an IamWaiter object.
            IamWaiter iamWaiter = iam.waiter();
            CreatePolicyRequest request = CreatePolicyRequest.builder()
                    .policyName(policyName)
                    .policyDocument(PolicyDocument).build();

            CreatePolicyResponse response = iam.createPolicy(request);
            GetPolicyRequest polRequest = GetPolicyRequest.builder()
                    .policyArn(response.policy().arn())
                    .build();

            WaiterResponse<GetPolicyResponse> waitUntilPolicyExists = iamWaiter.waitUntilPolicyExists(polRequest);
            waitUntilPolicyExists.matched().response().ifPresent(System.out::println);
            return response.policy().arn();

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }

    public static void attachIAMRolePolicy(IamClient iam, String roleName, String policyArn) {
        try {
            ListAttachedRolePoliciesRequest request = ListAttachedRolePoliciesRequest.builder()
                    .roleName(roleName)
                    .build();

            ListAttachedRolePoliciesResponse response = iam.listAttachedRolePolicies(request);
            List<AttachedPolicy> attachedPolicies = response.attachedPolicies();
            String polArn;
            for (AttachedPolicy policy : attachedPolicies) {
                polArn = policy.policyArn();
                if (polArn.compareTo(policyArn) == 0) {
                    System.out.println(roleName + " policy is already attached to this role.");
                    return;
                }
            }

            AttachRolePolicyRequest attachRequest = AttachRolePolicyRequest.builder()
                    .roleName(roleName)
                    .policyArn(policyArn)
                    .build();

            iam.attachRolePolicy(attachRequest);
            System.out.println("Successfully attached policy " + policyArn + " to role " + roleName);

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    // Invoke an Amazon S3 operation using the Assumed Role.
    public static void assumeRole(String roleArn, String roleSessionName, String bucketName, String keyVal,
            String keySecret) {

        // Use the creds of the new IAM user that was created in this code example.
        AwsBasicCredentials credentials = AwsBasicCredentials.create(keyVal, keySecret);
        StsClient stsClient = StsClient.builder()
                .region(Region.US_EAST_1)
                .credentialsProvider(StaticCredentialsProvider.create(credentials))
                .build();

        try {
            AssumeRoleRequest roleRequest = AssumeRoleRequest.builder()
                    .roleArn(roleArn)
                    .roleSessionName(roleSessionName)
                    .build();

            AssumeRoleResponse roleResponse = stsClient.assumeRole(roleRequest);
            Credentials myCreds = roleResponse.credentials();
            String key = myCreds.accessKeyId();
            String secKey = myCreds.secretAccessKey();
            String secToken = myCreds.sessionToken();

            // List all objects in an Amazon S3 bucket using the temp creds retrieved by
            // invoking assumeRole.
            Region region = Region.US_EAST_1;
            S3Client s3 = S3Client.builder()
                    .credentialsProvider(
                            StaticCredentialsProvider.create(AwsSessionCredentials.create(key, secKey, secToken)))
                    .region(region)
                    .build();

            System.out.println("Created a S3Client using temp credentials.");
            System.out.println("Listing objects in " + bucketName);
            ListObjectsRequest listObjects = ListObjectsRequest.builder()
                    .bucket(bucketName)
                    .build();

            ListObjectsResponse res = s3.listObjects(listObjects);
            List<S3Object> objects = res.contents();
            for (S3Object myValue : objects) {
                System.out.println("The name of the key is " + myValue.key());
                System.out.println("The owner is " + myValue.owner());
            }

        } catch (StsException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    public static void deleteRole(IamClient iam, String roleName, String polArn) {

        try {
            // First the policy needs to be detached.
            DetachRolePolicyRequest rolePolicyRequest = DetachRolePolicyRequest.builder()
                    .policyArn(polArn)
                    .roleName(roleName)
                    .build();

            iam.detachRolePolicy(rolePolicyRequest);

            // Delete the policy.
            DeletePolicyRequest request = DeletePolicyRequest.builder()
                    .policyArn(polArn)
                    .build();

            iam.deletePolicy(request);
            System.out.println("*** Successfully deleted " + polArn);

            // Delete the role.
            DeleteRoleRequest roleRequest = DeleteRoleRequest.builder()
                    .roleName(roleName)
                    .build();

            iam.deleteRole(roleRequest);
            System.out.println("*** Successfully deleted " + roleName);

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void deleteKey(IamClient iam, String username, String accessKey) {
        try {
            DeleteAccessKeyRequest request = DeleteAccessKeyRequest.builder()
                    .accessKeyId(accessKey)
                    .userName(username)
                    .build();

            iam.deleteAccessKey(request);
            System.out.println("Successfully deleted access key " + accessKey +
                    " from user " + username);

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void deleteIAMUser(IamClient iam, String userName) {
        try {
            DeleteUserRequest request = DeleteUserRequest.builder()
                    .userName(userName)
                    .build();

            iam.deleteUser(request);
            System.out.println("*** Successfully deleted " + userName);

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+ 如需 API 詳細資訊，請參閱《*AWS SDK for Java 2.x API 參考*》中的下列主題。
  + [AttachRolePolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/AttachRolePolicy)
  + [CreateAccessKey](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/CreateAccessKey)
  + [CreatePolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/CreatePolicy)
  + [CreateRole](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/CreateRole)
  + [CreateUser](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/CreateUser)
  + [DeleteAccessKey](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/DeleteAccessKey)
  + [DeletePolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/DeletePolicy)
  + [DeleteRole](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/DeleteRole)
  + [DeleteUser](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/DeleteUser)
  + [DeleteUserPolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/DeleteUserPolicy)
  + [DetachRolePolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/DetachRolePolicy)
  + [PutUserPolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/PutUserPolicy)

------
#### [ JavaScript ]

**SDK for JavaScript (v3)**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)中設定和執行。
建立一個可授予許可的 IAM 使用者和角色，以列出 Amazon S3 儲存貯體。使用者只有擔任該角色的權利。擔任角色後，請使用暫時性憑證列出該帳戶的儲存貯體。  

```
import {
  CreateUserCommand,
  GetUserCommand,
  CreateAccessKeyCommand,
  CreatePolicyCommand,
  CreateRoleCommand,
  AttachRolePolicyCommand,
  DeleteAccessKeyCommand,
  DeleteUserCommand,
  DeleteRoleCommand,
  DeletePolicyCommand,
  DetachRolePolicyCommand,
  IAMClient,
} from "@aws-sdk/client-iam";
import { ListBucketsCommand, S3Client } from "@aws-sdk/client-s3";
import { AssumeRoleCommand, STSClient } from "@aws-sdk/client-sts";
import { retry } from "@aws-doc-sdk-examples/lib/utils/util-timers.js";
import { ScenarioInput } from "@aws-doc-sdk-examples/lib/scenario/index.js";

// Set the parameters.
const iamClient = new IAMClient({});
const userName = "iam_basic_test_username";
const policyName = "iam_basic_test_policy";
const roleName = "iam_basic_test_role";

/**
 * Create a new IAM user. If the user already exists, give
 * the option to delete and re-create it.
 * @param {string} name
 */
export const createUser = async (name, confirmAll = false) => {
  try {
    const { User } = await iamClient.send(
      new GetUserCommand({ UserName: name }),
    );
    const input = new ScenarioInput(
      "deleteUser",
      "Do you want to delete and remake this user?",
      { type: "confirm" },
    );
    const deleteUser = await input.handle({}, { confirmAll });
    // If the user exists, and you want to delete it, delete the user
    // and then create it again.
    if (deleteUser) {
      await iamClient.send(new DeleteUserCommand({ UserName: User.UserName }));
      await iamClient.send(new CreateUserCommand({ UserName: name }));
    } else {
      console.warn(
        `${name} already exists. The scenario may not work as expected.`,
      );
      return User;
    }
  } catch (caught) {
    // If there is no user by that name, create one.
    if (caught instanceof Error && caught.name === "NoSuchEntityException") {
      const { User } = await iamClient.send(
        new CreateUserCommand({ UserName: name }),
      );
      return User;
    }
    throw caught;
  }
};

export const main = async (confirmAll = false) => {
  // Create a user. The user has no permissions by default.
  const User = await createUser(userName, confirmAll);

  if (!User) {
    throw new Error("User not created");
  }

  // Create an access key. This key is used to authenticate the new user to
  // Amazon Simple Storage Service (Amazon S3) and AWS Security Token Service (AWS STS).
  // It's not best practice to use access keys. For more information, see https://aws.amazon.com/iam/resources/best-practices/.
  const createAccessKeyResponse = await iamClient.send(
    new CreateAccessKeyCommand({ UserName: userName }),
  );

  if (
    !createAccessKeyResponse.AccessKey?.AccessKeyId ||
    !createAccessKeyResponse.AccessKey?.SecretAccessKey
  ) {
    throw new Error("Access key not created");
  }

  const {
    AccessKey: { AccessKeyId, SecretAccessKey },
  } = createAccessKeyResponse;

  let s3Client = new S3Client({
    credentials: {
      accessKeyId: AccessKeyId,
      secretAccessKey: SecretAccessKey,
    },
  });

  // Retry the list buckets operation until it succeeds. InvalidAccessKeyId is
  // thrown while the user and access keys are still stabilizing.
  await retry({ intervalInMs: 1000, maxRetries: 300 }, async () => {
    try {
      return await listBuckets(s3Client);
    } catch (err) {
      if (err instanceof Error && err.name === "InvalidAccessKeyId") {
        throw err;
      }
    }
  });

  // Retry the create role operation until it succeeds. A MalformedPolicyDocument error
  // is thrown while the user and access keys are still stabilizing.
  const { Role } = await retry(
    {
      intervalInMs: 2000,
      maxRetries: 60,
    },
    () =>
      iamClient.send(
        new CreateRoleCommand({
          AssumeRolePolicyDocument: JSON.stringify({
            Version: "2012-10-17",
            Statement: [
              {
                Effect: "Allow",
                Principal: {
                  // Allow the previously created user to assume this role.
                  AWS: User.Arn,
                },
                Action: "sts:AssumeRole",
              },
            ],
          }),
          RoleName: roleName,
        }),
      ),
  );

  if (!Role) {
    throw new Error("Role not created");
  }

  // Create a policy that allows the user to list S3 buckets.
  const { Policy: listBucketPolicy } = await iamClient.send(
    new CreatePolicyCommand({
      PolicyDocument: JSON.stringify({
        Version: "2012-10-17",
        Statement: [
          {
            Effect: "Allow",
            Action: ["s3:ListAllMyBuckets"],
            Resource: "*",
          },
        ],
      }),
      PolicyName: policyName,
    }),
  );

  if (!listBucketPolicy) {
    throw new Error("Policy not created");
  }

  // Attach the policy granting the 's3:ListAllMyBuckets' action to the role.
  await iamClient.send(
    new AttachRolePolicyCommand({
      PolicyArn: listBucketPolicy.Arn,
      RoleName: Role.RoleName,
    }),
  );

  // Assume the role.
  const stsClient = new STSClient({
    credentials: {
      accessKeyId: AccessKeyId,
      secretAccessKey: SecretAccessKey,
    },
  });

  // Retry the assume role operation until it succeeds.
  const { Credentials } = await retry(
    { intervalInMs: 2000, maxRetries: 60 },
    () =>
      stsClient.send(
        new AssumeRoleCommand({
          RoleArn: Role.Arn,
          RoleSessionName: `iamBasicScenarioSession-${Math.floor(
            Math.random() * 1000000,
          )}`,
          DurationSeconds: 900,
        }),
      ),
  );

  if (!Credentials?.AccessKeyId || !Credentials?.SecretAccessKey) {
    throw new Error("Credentials not created");
  }

  s3Client = new S3Client({
    credentials: {
      accessKeyId: Credentials.AccessKeyId,
      secretAccessKey: Credentials.SecretAccessKey,
      sessionToken: Credentials.SessionToken,
    },
  });

  // List the S3 buckets again.
  // Retry the list buckets operation until it succeeds. AccessDenied might
  // be thrown while the role policy is still stabilizing.
  await retry({ intervalInMs: 2000, maxRetries: 120 }, () =>
    listBuckets(s3Client),
  );

  // Clean up.
  await iamClient.send(
    new DetachRolePolicyCommand({
      PolicyArn: listBucketPolicy.Arn,
      RoleName: Role.RoleName,
    }),
  );

  await iamClient.send(
    new DeletePolicyCommand({
      PolicyArn: listBucketPolicy.Arn,
    }),
  );

  await iamClient.send(
    new DeleteRoleCommand({
      RoleName: Role.RoleName,
    }),
  );

  await iamClient.send(
    new DeleteAccessKeyCommand({
      UserName: userName,
      AccessKeyId,
    }),
  );

  await iamClient.send(
    new DeleteUserCommand({
      UserName: userName,
    }),
  );
};

/**
 *
 * @param {S3Client} s3Client
 */
const listBuckets = async (s3Client) => {
  const { Buckets } = await s3Client.send(new ListBucketsCommand({}));

  if (!Buckets) {
    throw new Error("Buckets not listed");
  }

  console.log(Buckets.map((bucket) => bucket.Name).join("\n"));
};
```
+ 如需 API 詳細資訊，請參閱《*適用於 JavaScript 的 AWS SDK API 參考*》中的下列主題。
  + [AttachRolePolicy](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/AttachRolePolicyCommand)
  + [CreateAccessKey](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/CreateAccessKeyCommand)
  + [CreatePolicy](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/CreatePolicyCommand)
  + [CreateRole](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/CreateRoleCommand)
  + [CreateUser](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/CreateUserCommand)
  + [DeleteAccessKey](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeleteAccessKeyCommand)
  + [DeletePolicy](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeletePolicyCommand)
  + [DeleteRole](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeleteRoleCommand)
  + [DeleteUser](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeleteUserCommand)
  + [DeleteUserPolicy](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeleteUserPolicyCommand)
  + [DetachRolePolicy](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DetachRolePolicyCommand)
  + [PutUserPolicy](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/PutUserPolicyCommand)

------
#### [ Kotlin ]

**SDK for Kotlin**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iam#code-examples)中設定和執行。
建立可包裝 IAM 使用者動作的函數。  

```
suspend fun main(args: Array<String>) {
    val usage = """
    Usage:
        <username> <policyName> <roleName> <roleSessionName> <fileLocation> <bucketName> 

    Where:
        username - The name of the IAM user to create. 
        policyName - The name of the policy to create. 
        roleName - The name of the role to create. 
        roleSessionName - The name of the session required for the assumeRole operation. 
        fileLocation - The file location to the JSON required to create the role (see Readme). 
        bucketName - The name of the Amazon S3 bucket from which objects are read. 
    """

    if (args.size != 6) {
        println(usage)
        exitProcess(1)
    }

    val userName = args[0]
    val policyName = args[1]
    val roleName = args[2]
    val roleSessionName = args[3]
    val fileLocation = args[4]
    val bucketName = args[5]

    createUser(userName)
    println("$userName was successfully created.")

    val polArn = createPolicy(policyName)
    println("The policy $polArn was successfully created.")

    val roleArn = createRole(roleName, fileLocation)
    println("$roleArn was successfully created.")
    attachRolePolicy(roleName, polArn)

    println("*** Wait for 1 MIN so the resource is available.")
    delay(60000)
    assumeGivenRole(roleArn, roleSessionName, bucketName)

    println("*** Getting ready to delete the AWS resources.")
    deleteRole(roleName, polArn)
    deleteUser(userName)
    println("This IAM Scenario has successfully completed.")
}

suspend fun createUser(usernameVal: String?): String? {
    val request =
        CreateUserRequest {
            userName = usernameVal
        }

    IamClient { region = "AWS_GLOBAL" }.use { iamClient ->
        val response = iamClient.createUser(request)
        return response.user?.userName
    }
}

suspend fun createPolicy(policyNameVal: String?): String {
    val policyDocumentValue = """
    {
        "Version":"2012-10-17",		 	 	 
        "Statement": [
            {
                "Effect": "Allow",
                "Action": [
                    "s3:*"
                ],
                "Resource": "*"
            }
        ]
    }
    """.trimIndent()

    val request =
        CreatePolicyRequest {
            policyName = policyNameVal
            policyDocument = policyDocumentValue
        }

    IamClient.fromEnvironment { region = "AWS_GLOBAL" }.use { iamClient ->
        val response = iamClient.createPolicy(request)
        return response.policy?.arn.toString()
    }
}

suspend fun createRole(
    rolenameVal: String?,
    fileLocation: String?,
): String? {
    val jsonObject = fileLocation?.let { readJsonSimpleDemo(it) } as JSONObject

    val request =
        CreateRoleRequest {
            roleName = rolenameVal
            assumeRolePolicyDocument = jsonObject.toJSONString()
            description = "Created using the AWS SDK for Kotlin"
        }

    IamClient { region = "AWS_GLOBAL" }.use { iamClient ->
        val response = iamClient.createRole(request)
        return response.role?.arn
    }
}

suspend fun attachRolePolicy(
    roleNameVal: String,
    policyArnVal: String,
) {
    val request =
        ListAttachedRolePoliciesRequest {
            roleName = roleNameVal
        }

    IamClient.fromEnvironment { region = "AWS_GLOBAL" }.use { iamClient ->
        val response = iamClient.listAttachedRolePolicies(request)
        val attachedPolicies = response.attachedPolicies

        // Ensure that the policy is not attached to this role.
        val checkStatus: Int
        if (attachedPolicies != null) {
            checkStatus = checkMyList(attachedPolicies, policyArnVal)
            if (checkStatus == -1) {
                return
            }
        }

        val policyRequest =
            AttachRolePolicyRequest {
                roleName = roleNameVal
                policyArn = policyArnVal
            }
        iamClient.attachRolePolicy(policyRequest)
        println("Successfully attached policy $policyArnVal to role $roleNameVal")
    }
}

fun checkMyList(
    attachedPolicies: List<AttachedPolicy>,
    policyArnVal: String,
): Int {
    for (policy in attachedPolicies) {
        val polArn = policy.policyArn.toString()

        if (polArn.compareTo(policyArnVal) == 0) {
            println("The policy is already attached to this role.")
            return -1
        }
    }
    return 0
}

suspend fun assumeGivenRole(
    roleArnVal: String?,
    roleSessionNameVal: String?,
    bucketName: String,
) {
    val stsClient = StsClient.fromEnvironment { region = "us-east-1" }
    val roleRequest =
        AssumeRoleRequest {
            roleArn = roleArnVal
            roleSessionName = roleSessionNameVal
        }

    val roleResponse = stsClient.assumeRole(roleRequest)
    val myCreds = roleResponse.credentials
    val key = myCreds?.accessKeyId
    val secKey = myCreds?.secretAccessKey
    val secToken = myCreds?.sessionToken

    val staticCredentials = StaticCredentialsProvider {
        accessKeyId = key
        secretAccessKey = secKey
        sessionToken = secToken
    }

    // List all objects in an Amazon S3 bucket using the temp creds.
    val s3 = S3Client.fromEnvironment {
        region = "us-east-1"
        credentialsProvider = staticCredentials
    }

    println("Created a S3Client using temp credentials.")
    println("Listing objects in $bucketName")

    val listObjects =
        ListObjectsRequest {
            bucket = bucketName
        }

    val response = s3.listObjects(listObjects)
    response.contents?.forEach { myObject ->
        println("The name of the key is ${myObject.key}")
        println("The owner is ${myObject.owner}")
    }
}

suspend fun deleteRole(
    roleNameVal: String,
    polArn: String,
) {
    val iam = IamClient.fromEnvironment { region = "AWS_GLOBAL" }

    // First the policy needs to be detached.
    val rolePolicyRequest =
        DetachRolePolicyRequest {
            policyArn = polArn
            roleName = roleNameVal
        }

    iam.detachRolePolicy(rolePolicyRequest)

    // Delete the policy.
    val request =
        DeletePolicyRequest {
            policyArn = polArn
        }

    iam.deletePolicy(request)
    println("*** Successfully deleted $polArn")

    // Delete the role.
    val roleRequest =
        DeleteRoleRequest {
            roleName = roleNameVal
        }

    iam.deleteRole(roleRequest)
    println("*** Successfully deleted $roleNameVal")
}

suspend fun deleteUser(userNameVal: String) {
    val iam = IamClient.fromEnvironment { region = "AWS_GLOBAL" }
    val request =
        DeleteUserRequest {
            userName = userNameVal
        }

    iam.deleteUser(request)
    println("*** Successfully deleted $userNameVal")
}

@Throws(java.lang.Exception::class)
fun readJsonSimpleDemo(filename: String): Any? {
    val reader = FileReader(filename)
    val jsonParser = JSONParser()
    return jsonParser.parse(reader)
}
```
+ 如需 API 詳細資訊，請參閱 *AWS SDK for Kotlin API reference* 中的下列主題。
  + [AttachRolePolicy](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [CreateAccessKey](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [CreatePolicy](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [CreateRole](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [CreateUser](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteAccessKey](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeletePolicy](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteRole](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteUser](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteUserPolicy](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DetachRolePolicy](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [PutUserPolicy](https://sdk.amazonaws.com/kotlin/api/latest/index.html)

------
#### [ PHP ]

**SDK for PHP**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/iam#code-examples)中設定和執行。

```
namespace Iam\Basics;

require 'vendor/autoload.php';

use Aws\Credentials\Credentials;
use Aws\S3\Exception\S3Exception;
use Aws\S3\S3Client;
use Aws\Sts\StsClient;
use Iam\IAMService;

echo("\n");
echo("--------------------------------------\n");
print("Welcome to the IAM getting started demo using PHP!\n");
echo("--------------------------------------\n");

$uuid = uniqid();
$service = new IAMService();

$user = $service->createUser("iam_demo_user_$uuid");
echo "Created user with the arn: {$user['Arn']}\n";

$key = $service->createAccessKey($user['UserName']);
$assumeRolePolicyDocument = "{
                \"Version\": \"2012-10-17\",
                \"Statement\": [{
                    \"Effect\": \"Allow\",
                    \"Principal\": {\"AWS\": \"{$user['Arn']}\"},
                    \"Action\": \"sts:AssumeRole\"
                }]
            }";
$assumeRoleRole = $service->createRole("iam_demo_role_$uuid", $assumeRolePolicyDocument);
echo "Created role: {$assumeRoleRole['RoleName']}\n";

$listAllBucketsPolicyDocument = "{
                \"Version\": \"2012-10-17\",
                \"Statement\": [{
                    \"Effect\": \"Allow\",
                    \"Action\": \"s3:ListAllMyBuckets\",
                    \"Resource\": \"arn:aws:s3:::*\"}]
}";
$listAllBucketsPolicy = $service->createPolicy("iam_demo_policy_$uuid", $listAllBucketsPolicyDocument);
echo "Created policy: {$listAllBucketsPolicy['PolicyName']}\n";

$service->attachRolePolicy($assumeRoleRole['RoleName'], $listAllBucketsPolicy['Arn']);

$inlinePolicyDocument = "{
                \"Version\": \"2012-10-17\",
                \"Statement\": [{
                    \"Effect\": \"Allow\",
                    \"Action\": \"sts:AssumeRole\",
                    \"Resource\": \"{$assumeRoleRole['Arn']}\"}]
}";
$inlinePolicy = $service->createUserPolicy("iam_demo_inline_policy_$uuid", $inlinePolicyDocument, $user['UserName']);
//First, fail to list the buckets with the user
$credentials = new Credentials($key['AccessKeyId'], $key['SecretAccessKey']);
$s3Client = new S3Client(['region' => 'us-west-2', 'version' => 'latest', 'credentials' => $credentials]);
try {
    $s3Client->listBuckets([
    ]);
    echo "this should not run";
} catch (S3Exception $exception) {
    echo "successfully failed!\n";
}

$stsClient = new StsClient(['region' => 'us-west-2', 'version' => 'latest', 'credentials' => $credentials]);
sleep(10);
$assumedRole = $stsClient->assumeRole([
    'RoleArn' => $assumeRoleRole['Arn'],
    'RoleSessionName' => "DemoAssumeRoleSession_$uuid",
]);
$assumedCredentials = [
    'key' => $assumedRole['Credentials']['AccessKeyId'],
    'secret' => $assumedRole['Credentials']['SecretAccessKey'],
    'token' => $assumedRole['Credentials']['SessionToken'],
];
$s3Client = new S3Client(['region' => 'us-west-2', 'version' => 'latest', 'credentials' => $assumedCredentials]);
try {
    $s3Client->listBuckets([]);
    echo "this should now run!\n";
} catch (S3Exception $exception) {
    echo "this should now not fail\n";
}

$service->detachRolePolicy($assumeRoleRole['RoleName'], $listAllBucketsPolicy['Arn']);
$deletePolicy = $service->deletePolicy($listAllBucketsPolicy['Arn']);
echo "Delete policy: {$listAllBucketsPolicy['PolicyName']}\n";
$deletedRole = $service->deleteRole($assumeRoleRole['Arn']);
echo "Deleted role: {$assumeRoleRole['RoleName']}\n";
$deletedKey = $service->deleteAccessKey($key['AccessKeyId'], $user['UserName']);
$deletedUser = $service->deleteUser($user['UserName']);
echo "Delete user: {$user['UserName']}\n";
```
+ 如需 API 詳細資訊，請參閱《*適用於 PHP 的 AWS SDK API 參考*》中的下列主題。
  + [AttachRolePolicy](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/AttachRolePolicy)
  + [CreateAccessKey](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/CreateAccessKey)
  + [CreatePolicy](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/CreatePolicy)
  + [CreateRole](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/CreateRole)
  + [CreateUser](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/CreateUser)
  + [DeleteAccessKey](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/DeleteAccessKey)
  + [DeletePolicy](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/DeletePolicy)
  + [DeleteRole](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/DeleteRole)
  + [DeleteUser](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/DeleteUser)
  + [DeleteUserPolicy](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/DeleteUserPolicy)
  + [DetachRolePolicy](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/DetachRolePolicy)
  + [PutUserPolicy](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/PutUserPolicy)

------
#### [ Python ]

**SDK for Python (Boto3)**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)中設定和執行。
建立一個可授予許可的 IAM 使用者和角色，以列出 Amazon S3 儲存貯體。使用者只有擔任該角色的權利。擔任角色後，請使用暫時性憑證列出該帳戶的儲存貯體。  

```
import json
import sys
import time
from uuid import uuid4

import boto3
from botocore.exceptions import ClientError


def progress_bar(seconds):
    """Shows a simple progress bar in the command window."""
    for _ in range(seconds):
        time.sleep(1)
        print(".", end="")
        sys.stdout.flush()
    print()


def setup(iam_resource):
    """
    Creates a new user with no permissions.
    Creates an access key pair for the user.
    Creates a role with a policy that lets the user assume the role.
    Creates a policy that allows listing Amazon S3 buckets.
    Attaches the policy to the role.
    Creates an inline policy for the user that lets the user assume the role.

    :param iam_resource: A Boto3 AWS Identity and Access Management (IAM) resource
                         that has permissions to create users, roles, and policies
                         in the account.
    :return: The newly created user, user key, and role.
    """
    try:
        user = iam_resource.create_user(UserName=f"demo-user-{uuid4()}")
        print(f"Created user {user.name}.")
    except ClientError as error:
        print(
            f"Couldn't create a user for the demo. Here's why: "
            f"{error.response['Error']['Message']}"
        )
        raise

    try:
        user_key = user.create_access_key_pair()
        print(f"Created access key pair for user.")
    except ClientError as error:
        print(
            f"Couldn't create access keys for user {user.name}. Here's why: "
            f"{error.response['Error']['Message']}"
        )
        raise

    print(f"Wait for user to be ready.", end="")
    progress_bar(10)

    try:
        role = iam_resource.create_role(
            RoleName=f"demo-role-{uuid4()}",
            AssumeRolePolicyDocument=json.dumps(
                {
                    "Version":"2012-10-17",		 	 	 
                    "Statement": [
                        {
                            "Effect": "Allow",
                            "Principal": {"AWS": user.arn},
                            "Action": "sts:AssumeRole",
                        }
                    ],
                }
            ),
        )
        print(f"Created role {role.name}.")
    except ClientError as error:
        print(
            f"Couldn't create a role for the demo. Here's why: "
            f"{error.response['Error']['Message']}"
        )
        raise

    try:
        policy = iam_resource.create_policy(
            PolicyName=f"demo-policy-{uuid4()}",
            PolicyDocument=json.dumps(
                {
                    "Version":"2012-10-17",		 	 	 
                    "Statement": [
                        {
                            "Effect": "Allow",
                            "Action": "s3:ListAllMyBuckets",
                            "Resource": "arn:aws:s3:::*",
                        }
                    ],
                }
            ),
        )
        role.attach_policy(PolicyArn=policy.arn)
        print(f"Created policy {policy.policy_name} and attached it to the role.")
    except ClientError as error:
        print(
            f"Couldn't create a policy and attach it to role {role.name}. Here's why: "
            f"{error.response['Error']['Message']}"
        )
        raise

    try:
        user.create_policy(
            PolicyName=f"demo-user-policy-{uuid4()}",
            PolicyDocument=json.dumps(
                {
                    "Version":"2012-10-17",		 	 	 
                    "Statement": [
                        {
                            "Effect": "Allow",
                            "Action": "sts:AssumeRole",
                            "Resource": role.arn,
                        }
                    ],
                }
            ),
        )
        print(
            f"Created an inline policy for {user.name} that lets the user assume "
            f"the role."
        )
    except ClientError as error:
        print(
            f"Couldn't create an inline policy for user {user.name}. Here's why: "
            f"{error.response['Error']['Message']}"
        )
        raise

    print("Give AWS time to propagate these new resources and connections.", end="")
    progress_bar(10)

    return user, user_key, role


def show_access_denied_without_role(user_key):
    """
    Shows that listing buckets without first assuming the role is not allowed.

    :param user_key: The key of the user created during setup. This user does not
                     have permission to list buckets in the account.
    """
    print(f"Try to list buckets without first assuming the role.")
    s3_denied_resource = boto3.resource(
        "s3", aws_access_key_id=user_key.id, aws_secret_access_key=user_key.secret
    )
    try:
        for bucket in s3_denied_resource.buckets.all():
            print(bucket.name)
        raise RuntimeError("Expected to get AccessDenied error when listing buckets!")
    except ClientError as error:
        if error.response["Error"]["Code"] == "AccessDenied":
            print("Attempt to list buckets with no permissions: AccessDenied.")
        else:
            raise


def list_buckets_from_assumed_role(user_key, assume_role_arn, session_name):
    """
    Assumes a role that grants permission to list the Amazon S3 buckets in the account.
    Uses the temporary credentials from the role to list the buckets that are owned
    by the assumed role's account.

    :param user_key: The access key of a user that has permission to assume the role.
    :param assume_role_arn: The Amazon Resource Name (ARN) of the role that
                            grants access to list the other account's buckets.
    :param session_name: The name of the STS session.
    """
    sts_client = boto3.client(
        "sts", aws_access_key_id=user_key.id, aws_secret_access_key=user_key.secret
    )
    try:
        response = sts_client.assume_role(
            RoleArn=assume_role_arn, RoleSessionName=session_name
        )
        temp_credentials = response["Credentials"]
        print(f"Assumed role {assume_role_arn} and got temporary credentials.")
    except ClientError as error:
        print(
            f"Couldn't assume role {assume_role_arn}. Here's why: "
            f"{error.response['Error']['Message']}"
        )
        raise

    # Create an S3 resource that can access the account with the temporary credentials.
    s3_resource = boto3.resource(
        "s3",
        aws_access_key_id=temp_credentials["AccessKeyId"],
        aws_secret_access_key=temp_credentials["SecretAccessKey"],
        aws_session_token=temp_credentials["SessionToken"],
    )
    print(f"Listing buckets for the assumed role's account:")
    try:
        for bucket in s3_resource.buckets.all():
            print(bucket.name)
    except ClientError as error:
        print(
            f"Couldn't list buckets for the account. Here's why: "
            f"{error.response['Error']['Message']}"
        )
        raise




def teardown(user, role):
    """
    Removes all resources created during setup.

    :param user: The demo user.
    :param role: The demo role.
    """
    try:
        for attached in role.attached_policies.all():
            policy_name = attached.policy_name
            role.detach_policy(PolicyArn=attached.arn)
            attached.delete()
            print(f"Detached and deleted {policy_name}.")
        role.delete()
        print(f"Deleted {role.name}.")
    except ClientError as error:
        print(
            "Couldn't detach policy, delete policy, or delete role. Here's why: "
            f"{error.response['Error']['Message']}"
        )
        raise

    try:
        for user_pol in user.policies.all():
            user_pol.delete()
            print("Deleted inline user policy.")
        for key in user.access_keys.all():
            key.delete()
            print("Deleted user's access key.")
        user.delete()
        print(f"Deleted {user.name}.")
    except ClientError as error:
        print(
            "Couldn't delete user policy or delete user. Here's why: "
            f"{error.response['Error']['Message']}"
        )


def usage_demo():
    """Drives the demonstration."""
    print("-" * 88)
    print(f"Welcome to the IAM create user and assume role demo.")
    print("-" * 88)
    iam_resource = boto3.resource("iam")
    user = None
    role = None
    try:
        user, user_key, role = setup(iam_resource)
        print(f"Created {user.name} and {role.name}.")
        show_access_denied_without_role(user_key)
        list_buckets_from_assumed_role(user_key, role.arn, "AssumeRoleDemoSession")
    except Exception:
        print("Something went wrong!")
    finally:
        if user is not None and role is not None:
            teardown(user, role)
        print("Thanks for watching!")


if __name__ == "__main__":
    usage_demo()
```
+ 如需 API 的詳細資訊，請參閱 *AWS SDK for Python (Boto3) API Reference* 中的下列主題。
  + [AttachRolePolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/AttachRolePolicy)
  + [CreateAccessKey](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreateAccessKey)
  + [CreatePolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreatePolicy)
  + [CreateRole](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreateRole)
  + [CreateUser](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreateUser)
  + [DeleteAccessKey](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeleteAccessKey)
  + [DeletePolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeletePolicy)
  + [DeleteRole](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeleteRole)
  + [DeleteUser](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeleteUser)
  + [DeleteUserPolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeleteUserPolicy)
  + [DetachRolePolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DetachRolePolicy)
  + [PutUserPolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/PutUserPolicy)

------
#### [ Ruby ]

**SDK for Ruby**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)中設定和執行。
建立一個可授予許可的 IAM 使用者和角色，以列出 Amazon S3 儲存貯體。使用者只有擔任該角色的權利。擔任角色後，請使用暫時性憑證列出該帳戶的儲存貯體。  

```
# Wraps the scenario actions.
class ScenarioCreateUserAssumeRole
  attr_reader :iam_client

  # @param [Aws::IAM::Client] iam_client: The AWS IAM client.
  def initialize(iam_client, logger: Logger.new($stdout))
    @iam_client = iam_client
    @logger = logger
  end

  # Waits for the specified number of seconds.
  #
  # @param duration [Integer] The number of seconds to wait.
  def wait(duration)
    puts('Give AWS time to propagate resources...')
    sleep(duration)
  end

  # Creates a user.
  #
  # @param user_name [String] The name to give the user.
  # @return [Aws::IAM::User] The newly created user.
  def create_user(user_name)
    user = @iam_client.create_user(user_name: user_name).user
    @logger.info("Created demo user named #{user.user_name}.")
  rescue Aws::Errors::ServiceError => e
    @logger.info('Tried and failed to create demo user.')
    @logger.info("\t#{e.code}: #{e.message}")
    @logger.info("\nCan't continue the demo without a user!")
    raise
  else
    user
  end

  # Creates an access key for a user.
  #
  # @param user [Aws::IAM::User] The user that owns the key.
  # @return [Aws::IAM::AccessKeyPair] The newly created access key.
  def create_access_key_pair(user)
    user_key = @iam_client.create_access_key(user_name: user.user_name).access_key
    @logger.info("Created accesskey pair for user #{user.user_name}.")
  rescue Aws::Errors::ServiceError => e
    @logger.info("Couldn't create access keys for user #{user.user_name}.")
    @logger.info("\t#{e.code}: #{e.message}")
    raise
  else
    user_key
  end

  # Creates a role that can be assumed by a user.
  #
  # @param role_name [String] The name to give the role.
  # @param user [Aws::IAM::User] The user who is granted permission to assume the role.
  # @return [Aws::IAM::Role] The newly created role.
  def create_role(role_name, user)
    trust_policy = {
      Version: '2012-10-17',
      Statement: [{
        Effect: 'Allow',
        Principal: { 'AWS': user.arn },
        Action: 'sts:AssumeRole'
      }]
    }.to_json
    role = @iam_client.create_role(
      role_name: role_name,
      assume_role_policy_document: trust_policy
    ).role
    @logger.info("Created role #{role.role_name}.")
  rescue Aws::Errors::ServiceError => e
    @logger.info("Couldn't create a role for the demo. Here's why: ")
    @logger.info("\t#{e.code}: #{e.message}")
    raise
  else
    role
  end

  # Creates a policy that grants permission to list S3 buckets in the account, and
  # then attaches the policy to a role.
  #
  # @param policy_name [String] The name to give the policy.
  # @param role [Aws::IAM::Role] The role that the policy is attached to.
  # @return [Aws::IAM::Policy] The newly created policy.
  def create_and_attach_role_policy(policy_name, role)
    policy_document = {
      Version: '2012-10-17',
      Statement: [{
        Effect: 'Allow',
        Action: 's3:ListAllMyBuckets',
        Resource: 'arn:aws:s3:::*'
      }]
    }.to_json
    policy = @iam_client.create_policy(
      policy_name: policy_name,
      policy_document: policy_document
    ).policy
    @iam_client.attach_role_policy(
      role_name: role.role_name,
      policy_arn: policy.arn
    )
    @logger.info("Created policy #{policy.policy_name} and attached it to role #{role.role_name}.")
  rescue Aws::Errors::ServiceError => e
    @logger.info("Couldn't create a policy and attach it to role #{role.role_name}. Here's why: ")
    @logger.info("\t#{e.code}: #{e.message}")
    raise
  end

  # Creates an inline policy for a user that lets the user assume a role.
  #
  # @param policy_name [String] The name to give the policy.
  # @param user [Aws::IAM::User] The user that owns the policy.
  # @param role [Aws::IAM::Role] The role that can be assumed.
  # @return [Aws::IAM::UserPolicy] The newly created policy.
  def create_user_policy(policy_name, user, role)
    policy_document = {
      Version: '2012-10-17',
      Statement: [{
        Effect: 'Allow',
        Action: 'sts:AssumeRole',
        Resource: role.arn
      }]
    }.to_json
    @iam_client.put_user_policy(
      user_name: user.user_name,
      policy_name: policy_name,
      policy_document: policy_document
    )
    puts("Created an inline policy for #{user.user_name} that lets the user assume role #{role.role_name}.")
  rescue Aws::Errors::ServiceError => e
    @logger.info("Couldn't create an inline policy for user #{user.user_name}. Here's why: ")
    @logger.info("\t#{e.code}: #{e.message}")
    raise
  end

  # Creates an Amazon S3 resource with specified credentials. This is separated into a
  # factory function so that it can be mocked for unit testing.
  #
  # @param credentials [Aws::Credentials] The credentials used by the Amazon S3 resource.
  def create_s3_resource(credentials)
    Aws::S3::Resource.new(client: Aws::S3::Client.new(credentials: credentials))
  end

  # Lists the S3 buckets for the account, using the specified Amazon S3 resource.
  # Because the resource uses credentials with limited access, it may not be able to
  # list the S3 buckets.
  #
  # @param s3_resource [Aws::S3::Resource] An Amazon S3 resource.
  def list_buckets(s3_resource)
    count = 10
    s3_resource.buckets.each do |bucket|
      @logger.info "\t#{bucket.name}"
      count -= 1
      break if count.zero?
    end
  rescue Aws::Errors::ServiceError => e
    if e.code == 'AccessDenied'
      puts('Attempt to list buckets with no permissions: AccessDenied.')
    else
      @logger.info("Couldn't list buckets for the account. Here's why: ")
      @logger.info("\t#{e.code}: #{e.message}")
      raise
    end
  end

  # Creates an AWS Security Token Service (AWS STS) client with specified credentials.
  # This is separated into a factory function so that it can be mocked for unit testing.
  #
  # @param key_id [String] The ID of the access key used by the STS client.
  # @param key_secret [String] The secret part of the access key used by the STS client.
  def create_sts_client(key_id, key_secret)
    Aws::STS::Client.new(access_key_id: key_id, secret_access_key: key_secret)
  end

  # Gets temporary credentials that can be used to assume a role.
  #
  # @param role_arn [String] The ARN of the role that is assumed when these credentials
  #                          are used.
  # @param sts_client [AWS::STS::Client] An AWS STS client.
  # @return [Aws::AssumeRoleCredentials] The credentials that can be used to assume the role.
  def assume_role(role_arn, sts_client)
    credentials = Aws::AssumeRoleCredentials.new(
      client: sts_client,
      role_arn: role_arn,
      role_session_name: 'create-use-assume-role-scenario'
    )
    @logger.info("Assumed role '#{role_arn}', got temporary credentials.")
    credentials
  end

  # Deletes a role. If the role has policies attached, they are detached and
  # deleted before the role is deleted.
  #
  # @param role_name [String] The name of the role to delete.
  def delete_role(role_name)
    @iam_client.list_attached_role_policies(role_name: role_name).attached_policies.each do |policy|
      @iam_client.detach_role_policy(role_name: role_name, policy_arn: policy.policy_arn)
      @iam_client.delete_policy(policy_arn: policy.policy_arn)
      @logger.info("Detached and deleted policy #{policy.policy_name}.")
    end
    @iam_client.delete_role({ role_name: role_name })
    @logger.info("Role deleted: #{role_name}.")
  rescue Aws::Errors::ServiceError => e
    @logger.info("Couldn't detach policies and delete role #{role.name}. Here's why:")
    @logger.info("\t#{e.code}: #{e.message}")
    raise
  end

  # Deletes a user. If the user has inline policies or access keys, they are deleted
  # before the user is deleted.
  #
  # @param user [Aws::IAM::User] The user to delete.
  def delete_user(user_name)
    user = @iam_client.list_access_keys(user_name: user_name).access_key_metadata
    user.each do |key|
      @iam_client.delete_access_key({ access_key_id: key.access_key_id, user_name: user_name })
      @logger.info("Deleted access key #{key.access_key_id} for user '#{user_name}'.")
    end

    @iam_client.delete_user(user_name: user_name)
    @logger.info("Deleted user '#{user_name}'.")
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error deleting user '#{user_name}': #{e.message}")
  end
end

# Runs the IAM create a user and assume a role scenario.
def run_scenario(scenario)
  puts('-' * 88)
  puts('Welcome to the IAM create a user and assume a role demo!')
  puts('-' * 88)
  user = scenario.create_user("doc-example-user-#{Random.uuid}")
  user_key = scenario.create_access_key_pair(user)
  scenario.wait(10)
  role = scenario.create_role("doc-example-role-#{Random.uuid}", user)
  scenario.create_and_attach_role_policy("doc-example-role-policy-#{Random.uuid}", role)
  scenario.create_user_policy("doc-example-user-policy-#{Random.uuid}", user, role)
  scenario.wait(10)
  puts('Try to list buckets with credentials for a user who has no permissions.')
  puts('Expect AccessDenied from this call.')
  scenario.list_buckets(
    scenario.create_s3_resource(Aws::Credentials.new(user_key.access_key_id, user_key.secret_access_key))
  )
  puts('Now, assume the role that grants permission.')
  temp_credentials = scenario.assume_role(
    role.arn, scenario.create_sts_client(user_key.access_key_id, user_key.secret_access_key)
  )
  puts('Here are your buckets:')
  scenario.list_buckets(scenario.create_s3_resource(temp_credentials))
  puts("Deleting role '#{role.role_name}' and attached policies.")
  scenario.delete_role(role.role_name)
  puts("Deleting user '#{user.user_name}', policies, and keys.")
  scenario.delete_user(user.user_name)
  puts('Thanks for watching!')
  puts('-' * 88)
rescue Aws::Errors::ServiceError => e
  puts('Something went wrong with the demo.')
  puts("\t#{e.code}: #{e.message}")
end

run_scenario(ScenarioCreateUserAssumeRole.new(Aws::IAM::Client.new)) if $PROGRAM_NAME == __FILE__
```
+ 如需 API 詳細資訊，請參閱《*適用於 Ruby 的 AWS SDK API 參考*》中的下列主題。
  + [AttachRolePolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/AttachRolePolicy)
  + [CreateAccessKey](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/CreateAccessKey)
  + [CreatePolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/CreatePolicy)
  + [CreateRole](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/CreateRole)
  + [CreateUser](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/CreateUser)
  + [DeleteAccessKey](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/DeleteAccessKey)
  + [DeletePolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/DeletePolicy)
  + [DeleteRole](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/DeleteRole)
  + [DeleteUser](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/DeleteUser)
  + [DeleteUserPolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/DeleteUserPolicy)
  + [DetachRolePolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/DetachRolePolicy)
  + [PutUserPolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/PutUserPolicy)

------
#### [ Rust ]

**SDK for Rust**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/iam#code-examples)中設定和執行。

```
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_iam::Error as iamError;
use aws_sdk_iam::{config::Credentials as iamCredentials, config::Region, Client as iamClient};
use aws_sdk_s3::Client as s3Client;
use aws_sdk_sts::Client as stsClient;
use tokio::time::{sleep, Duration};
use uuid::Uuid;

#[tokio::main]
async fn main() -> Result<(), iamError> {
    let (client, uuid, list_all_buckets_policy_document, inline_policy_document) =
        initialize_variables().await;

    if let Err(e) = run_iam_operations(
        client,
        uuid,
        list_all_buckets_policy_document,
        inline_policy_document,
    )
    .await
    {
        println!("{:?}", e);
    };

    Ok(())
}

async fn initialize_variables() -> (iamClient, String, String, String) {
    let region_provider = RegionProviderChain::first_try(Region::new("us-west-2"));

    let shared_config = aws_config::from_env().region(region_provider).load().await;
    let client = iamClient::new(&shared_config);
    let uuid = Uuid::new_v4().to_string();

    let list_all_buckets_policy_document = "{
                \"Version\": \"2012-10-17\",
                \"Statement\": [{
                    \"Effect\": \"Allow\",
                    \"Action\": \"s3:ListAllMyBuckets\",
                    \"Resource\": \"arn:aws:s3:::*\"}]
    }"
    .to_string();
    let inline_policy_document = "{
                \"Version\": \"2012-10-17\",
                \"Statement\": [{
                    \"Effect\": \"Allow\",
                    \"Action\": \"sts:AssumeRole\",
                    \"Resource\": \"{}\"}]
    }"
    .to_string();

    (
        client,
        uuid,
        list_all_buckets_policy_document,
        inline_policy_document,
    )
}

async fn run_iam_operations(
    client: iamClient,
    uuid: String,
    list_all_buckets_policy_document: String,
    inline_policy_document: String,
) -> Result<(), iamError> {
    let user = iam_service::create_user(&client, &format!("{}{}", "iam_demo_user_", uuid)).await?;
    println!("Created the user with the name: {}", user.user_name());
    let key = iam_service::create_access_key(&client, user.user_name()).await?;

    let assume_role_policy_document = "{
        \"Version\": \"2012-10-17\",
                \"Statement\": [{
                    \"Effect\": \"Allow\",
                    \"Principal\": {\"AWS\": \"{}\"},
                    \"Action\": \"sts:AssumeRole\"
                }]
            }"
    .to_string()
    .replace("{}", user.arn());

    let assume_role_role = iam_service::create_role(
        &client,
        &format!("{}{}", "iam_demo_role_", uuid),
        &assume_role_policy_document,
    )
    .await?;
    println!("Created the role with the ARN: {}", assume_role_role.arn());

    let list_all_buckets_policy = iam_service::create_policy(
        &client,
        &format!("{}{}", "iam_demo_policy_", uuid),
        &list_all_buckets_policy_document,
    )
    .await?;
    println!(
        "Created policy: {}",
        list_all_buckets_policy.policy_name.as_ref().unwrap()
    );

    let attach_role_policy_result =
        iam_service::attach_role_policy(&client, &assume_role_role, &list_all_buckets_policy)
            .await?;
    println!(
        "Attached the policy to the role: {:?}",
        attach_role_policy_result
    );

    let inline_policy_name = format!("{}{}", "iam_demo_inline_policy_", uuid);
    let inline_policy_document = inline_policy_document.replace("{}", assume_role_role.arn());
    iam_service::create_user_policy(&client, &user, &inline_policy_name, &inline_policy_document)
        .await?;
    println!("Created inline policy.");

    //First, fail to list the buckets with the user.
    let creds = iamCredentials::from_keys(key.access_key_id(), key.secret_access_key(), None);
    let fail_config = aws_config::from_env()
        .credentials_provider(creds.clone())
        .load()
        .await;
    println!("Fail config: {:?}", fail_config);
    let fail_client: s3Client = s3Client::new(&fail_config);
    match fail_client.list_buckets().send().await {
        Ok(e) => {
            println!("This should not run. {:?}", e);
        }
        Err(e) => {
            println!("Successfully failed with error: {:?}", e)
        }
    }

    let sts_config = aws_config::from_env()
        .credentials_provider(creds.clone())
        .load()
        .await;
    let sts_client: stsClient = stsClient::new(&sts_config);
    sleep(Duration::from_secs(10)).await;
    let assumed_role = sts_client
        .assume_role()
        .role_arn(assume_role_role.arn())
        .role_session_name(format!("iam_demo_assumerole_session_{uuid}"))
        .send()
        .await;
    println!("Assumed role: {:?}", assumed_role);
    sleep(Duration::from_secs(10)).await;

    let assumed_credentials = iamCredentials::from_keys(
        assumed_role
            .as_ref()
            .unwrap()
            .credentials
            .as_ref()
            .unwrap()
            .access_key_id(),
        assumed_role
            .as_ref()
            .unwrap()
            .credentials
            .as_ref()
            .unwrap()
            .secret_access_key(),
        Some(
            assumed_role
                .as_ref()
                .unwrap()
                .credentials
                .as_ref()
                .unwrap()
                .session_token
                .clone(),
        ),
    );

    let succeed_config = aws_config::from_env()
        .credentials_provider(assumed_credentials)
        .load()
        .await;
    println!("succeed config: {:?}", succeed_config);
    let succeed_client: s3Client = s3Client::new(&succeed_config);
    sleep(Duration::from_secs(10)).await;
    match succeed_client.list_buckets().send().await {
        Ok(_) => {
            println!("This should now run successfully.")
        }
        Err(e) => {
            println!("This should not run. {:?}", e);
            panic!()
        }
    }

    //Clean up.
    iam_service::detach_role_policy(
        &client,
        assume_role_role.role_name(),
        list_all_buckets_policy.arn().unwrap_or_default(),
    )
    .await?;
    iam_service::delete_policy(&client, list_all_buckets_policy).await?;
    iam_service::delete_role(&client, &assume_role_role).await?;
    println!("Deleted role {}", assume_role_role.role_name());
    iam_service::delete_access_key(&client, &user, &key).await?;
    println!("Deleted key for {}", key.user_name());
    iam_service::delete_user_policy(&client, &user, &inline_policy_name).await?;
    println!("Deleted inline user policy: {}", inline_policy_name);
    iam_service::delete_user(&client, &user).await?;
    println!("Deleted user {}", user.user_name());

    Ok(())
}
```
+ 如需 API 詳細資訊，請參閱 *AWS SDK for Rust API reference* 中的下列主題。
  + [AttachRolePolicy](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.attach_role_policy)
  + [CreateAccessKey](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.create_access_key)
  + [CreatePolicy](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.create_policy)
  + [CreateRole](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.create_role)
  + [CreateUser](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.create_user)
  + [DeleteAccessKey](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.delete_access_key)
  + [DeletePolicy](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.delete_policy)
  + [DeleteRole](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.delete_role)
  + [DeleteUser](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.delete_user)
  + [DeleteUserPolicy](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.delete_user_policy)
  + [DetachRolePolicy](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.detach_role_policy)
  + [PutUserPolicy](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.put_user_policy)

------

# 使用 IAM 角色為在 Amazon EC2 執行個體上執行的應用程式授予許可
<a name="id_roles_use_switch-role-ec2"></a>

在 Amazon EC2 執行個體上執行的應用程式必須在 AWS API 請求中包含 AWS 登入資料。您可以讓您的開發人員直接將 AWS 登入資料存放在 Amazon EC2 執行個體中，並允許該執行個體中的應用程式使用這些登入資料。不過，開發人員將必須管理憑證，並確實將憑證安全地傳遞給每個執行個體，並在需要更新憑證時更新每個 Amazon EC2 執行個體。這是許多額外的工作。

與其這麼做，您可以 (也應該) 使用 IAM 角色來管理 Amazon EC2 執行個體上所執行應用程式的*臨時*憑證。使用角色時，您不必將長期憑證 (例如登入憑證或存取金鑰) 分發給 Amazon EC2 執行個體。相反地，該角色會提供暫時許可，供應用程式在呼叫其他 AWS 資源時使用。啟動 Amazon EC2 執行個體時，指定要與執行個體相關聯的 IAM 角色。然後，在執行個體上執行的應用程式可以使用角色提供的暫時憑證來簽署 API 請求。

如要透過角色為 Amazon EC2 執行個體上執行的應用程式授予許可，需搭配一些額外的組態。在 Amazon EC2 執行個體上執行的應用程式是由 AWS 虛擬化作業系統從 抽象化。由於此額外區隔，您需要額外的步驟，才能將 AWS 角色及其相關許可指派給 Amazon EC2 執行個體，並將其提供給其應用程式。此額外步驟是建立連接到執行個體的*[執行個體設定檔](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2_instance-profiles.html)*。執行個體描述檔包含角色，可以將角色的臨時憑證提供給在執行個體上執行的應用程式。然後，可以在應用程式的 API 呼叫中使用這些臨時憑證來存取資源，並限制僅存取角色指定的那些資源。

**注意**  
一次只能指派一個角色給 Amazon EC2 執行個體，執行個體上的所有應用程式會共用相同的角色和許可。當您利用 Amazon ECS 來管理 Amazon EC2 執行個體時，您可以向 Amazon ECS 任務指派角色，這些角色和執行 Amazon EC2 執行個體所使用的角色有所區別。為每項任務指派一個角色的做法符合最低權限存取原則，並且允許對動作和資源進行更精細的控制。  
如需詳細資訊，請參閱《Amazon Elastic Container Service 最佳實務指南》**中的[對 Amazon ECS 任務使用 IAM 角色](https://docs.aws.amazon.com/AmazonECS/latest/bestpracticesguide/security-iam-roles.html)。

以這種方式使用角色有幾個好處。由於角色憑證是臨時的並且是自動更新的，因此您不需要管理憑證，也不必擔心長期的安全風險。此外，如果對多個執行個體使用單一角色，則可以對該角色進行變更，並將變更自動傳播到所有執行個體。

**注意**  
雖然在啟動角色時通常就會將角色指派給 Amazon EC2 執行個體，但角色也可以與目前執行的 Amazon EC2 執行個體連接。若要了解如何將角色連接到正在執行的執行個體，請參閱 [Amazon EC2 的 IAM 角色](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html#attach-iam-role)。

**Topics**
+ [適用於 Amazon EC2 執行個體的角色如何運作？](#roles-usingrole-ec2instance-roles)
+ [使用 Amazon EC2 角色所需的許可](#roles-usingrole-ec2instance-permissions)
+ [我該如何開始？](#roles-usingrole-ec2instance-get-started)
+ [相關資訊](#roles-usingrole-ec2instance-related-info)

## 適用於 Amazon EC2 執行個體的角色如何運作？
<a name="roles-usingrole-ec2instance-roles"></a>

下圖中，開發人員在 Amazon EC2 執行個體上執行應用程式，該應用程式需要存取名為 `amzn-s3-demo-bucket-photos` 的 S3 儲存貯體。管理員建立 `Get-pics` 服務角色，並將角色連接到 Amazon EC2 執行個體。該角色包括許可政策，該政策授予對指定的 S3 儲存貯體的唯讀存取許可。角色還包含信任政策，該政策可允許 Amazon EC2 執行個體擔任角色並擷取臨時憑證。當應用程式在執行個體上執行時，它可以使用角色的臨時憑證來存取照片儲存貯體。管理員不必授予開發人員存取照片儲存貯體的許可，開發人員也不必共用或管理憑證。

![\[存取 AWS 資源的 Amazon EC2 執行個體上的應用程式\]](http://docs.aws.amazon.com/zh_tw/IAM/latest/UserGuide/images/roles-usingrole-ec2roleinstance.png)


1. 管理員使用 IAM 建立 **Get-pics** 角色。在角色的信任政策中，管理員指定只有 Amazon EC2 執行個體可以擔任該角色。在角色的許可政策中，管理員為 `amzn-s3-demo-bucket-photos` 儲存貯體指定唯讀許可。

1. 開發人員啟動 Amazon EC2 執行個體，並將 `Get-pics` 角色指派給該執行個體。
**注意**  
如果您使用 IAM 主控台，則會為您管理執行個體描述檔，並且對您來說幾乎是透明的。不過，如果您使用 AWS CLI 或 API 來建立和管理角色和 Amazon EC2 執行個體，則必須建立執行個體描述檔，並將角色指派為個別步驟。然後，當您啟動執行個體時，必須指定執行個體設定檔名稱，而不是角色名稱。

1. 應用程式執行時，會從 Amazon EC2 [執行個體中繼資料](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html)中取得暫時安全憑證，如[從執行個體中繼資料中擷取安全憑證](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html#instance-metadata-security-credentials)中所述。這些是代表角色的[暫時安全憑證](id_credentials_temp.md)，並且在有限的時間段內有效。

   透過一些 [AWS 開發套件](https://aws.amazon.com/tools/)，開發人員可以使用透明地管理暫時安全憑證的提供者。( AWS SDKs的文件說明該 SDK 支援用於管理登入資料的功能。)

   或者，應用程式可以直接從 Amazon EC2 執行個體的執行個體中繼資料中取得臨時憑證。您可以從中繼資料的 `iam/security-credentials/role-name` 類別 (在本例中為 `iam/security-credentials/Get-pics`) 中取得憑證和相關的值。如果應用程式從執行個體中繼資料取得憑證，則可以快取憑證。

1. 使用擷取到的臨時憑證，應用程式存取照片儲存貯體。基於連接至 **Get-pics** 角色的政策，應用程式具有唯讀許可。

   在執行個體上提供的臨時安全憑證在到期之前會自動更新，以便有效設定為永久可用。應用程式只需要確保在目前中繼資料到期之前，它從執行個體中繼資料中取得一組新的憑證。您可以使用 AWS SDK 來管理登入資料，因此應用程式不需要包含額外的邏輯來重新整理登入資料。例如，使用執行個體描述檔憑證提供者建立用戶端。不過，如果應用程式從執行個體中繼資料取得臨時安全憑證並快取它們，則應每小時或在目前設定過期之前至少 15 分鐘取得重新整理的憑證集。過期時間包含在 `iam/security-credentials/role-name` 類別中所傳回的資訊。

## 使用 Amazon EC2 角色所需的許可
<a name="roles-usingrole-ec2instance-permissions"></a>

若要使用角色啟動執行個體，開發人員必須具有啟動 Amazon EC2 執行個體的許可，以及傳遞 IAM 角色的許可。

下列範例政策允許使用者使用 AWS 管理主控台 來啟動具有 角色的執行個體。此政策包含萬用字元 (`*`)，以允許使用者傳遞任何角色，並執行列出的 Amazon EC2 動作。`ListInstanceProfiles` 動作讓使用者查看 AWS 帳戶中可用的所有角色。

**Example 範例政策，授予使用者使用 Amazon EC2 主控台啟動具有任何角色的執行個體的許可**    
****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "IamPassRole",
            "Effect": "Allow",
            "Action": "iam:PassRole",
            "Resource": "*",
            "Condition": {
                "StringEquals": {
                    "iam:PassedToService": "ec2.amazonaws.com"
                }
            }
        },
        {
            "Sid": "ListEc2AndListInstanceProfiles",
            "Effect": "Allow",
            "Action": [
                "iam:ListInstanceProfiles",
                "ec2:Describe*",
                "ec2:Search*",
                "ec2:Get*"
            ],
            "Resource": "*"
        }
    ]
}
```

### 限制哪些角色可以傳遞給 Amazon EC2 執行個體 (使用 PassRole)
<a name="roles-usingrole-ec2instance-passrole"></a>

您可以使用 `PassRole` 許可，限制使用者在啟動執行個體時可以將哪個角色傳遞給 Amazon EC2 執行個體。這有助於防止使用者執行具有比授予使用者更多許可的應用程式，也就是說，能夠獲得更高的許可。例如，假設使用者 Alice 只擁有啟動 Amazon EC2 執行個體以及使用 Amazon S3 儲存貯體的許可，但她傳遞給 Amazon EC2 執行個體的角色具有使用 IAM 和 Amazon DynamoDB 的許可。在這種情況下，Alice 或許可以啟動執行個體、登入執行個體、取得暫時安全憑證，然後執行她未授權的 IAM 或 DynamoDB 動作。

若要限制使用者可以將哪些角色傳遞給 Amazon EC2 執行個體，則要建立允許 `PassRole` 動作的政策。然後，您需要將政策連接到預計啟動 Amazon EC2 執行個體的使用者 (或使用者所屬的 IAM 群組)。在政策的 `Resource` 元素中，您需列出允許使用者傳遞給 Amazon EC2 執行個體的角色。當使用者啟動執行個體並將角色與其關聯時，Amazon EC2 檢查是否允許使用者傳送該角色。當然，您也應當確保使用者可以傳遞的角色不包含比使用者應具有的許可更多的許可。

**注意**  
`PassRole` 不是與`RunInstances` 或 `ListInstanceProfiles` 相同的 API 動作。反之，它是一種許可，每當角色 ARN 做為參數傳遞至 API 時 （或主控台會代表使用者執行此操作），就會進行 AWS 檢查。它可協助管理員控制哪些使用者可以傳遞哪些角色。在這種情況下，它確保允許使用者將特定角色連接到 Amazon EC2 執行個體。

**Example 此範例政策授予使用者許可，使其可以啟動具有特定角色的 Amazon EC2 執行個體**  
以下範例政策可允許使用者使用 Amazon EC2 API 來啟動具有角色的執行個體。`Resource` 元素指定角色的 Amazon Resource Name (ARN)。透過指定 ARN，政策授予使用者僅傳遞 `Get-pics` 角色的許可。如果使用者在啟動執行個體時嘗試指定不同的角色，則動作會失敗。使用者沒有執行任何執行個體的許可，無論其是否有傳遞角色。    
****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "ec2:RunInstances",
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": "iam:PassRole",
            "Resource": "arn:aws:iam::111122223333:role/Get-pics"
        }
    ]
}
```

### 允許執行個體設定檔角色切換到另一個帳戶中的角色
<a name="switch-role-ec2-another-account"></a>

您可以允許在 Amazon EC2 執行個體上執行的應用程式在另一個帳戶中執行命令。若要執行此操作，您必須允許將第一個帳戶中的 Amazon EC2 執行個體角色切換到第二個帳戶中的角色。

假設您使用兩個 ， AWS 帳戶 而且您想要允許在 Amazon EC2 執行個體上執行的應用程式在兩個帳戶中執行[AWS CLI](https://aws.amazon.com/cli/)命令。假設 Amazon EC2 執行個體存在於帳戶 `111111111111`。該執行個體包含 `abcd` 執行個體描述檔角色，該角色會允許應用程式在相同 `111111111111` 帳戶中對 `amzn-s3-demo-bucket1` 儲存貯體執行唯讀 Amazon S3 任務。不過，也必須允許應用程式擔任 `efgh` 跨帳戶角色來在帳戶 `222222222222` 中存取 `amzn-s3-demo-bucket2`Amazon S3 儲存貯體。

![\[此圖表顯示開發人員如何啟動具有該角色的 Amazon EC2 執行個體，以存取 Amazon S3 儲存貯體中的相片。\]](http://docs.aws.amazon.com/zh_tw/IAM/latest/UserGuide/images/roles-instance-profile-cross-account.png)


`abcd` Amazon EC2 執行個體設定檔角色必須具有以下許可政策，以允許應用程式存取 `amzn-s3-demo-bucket1` Amazon S3 儲存貯體：

***帳戶 111111111111 `abcd` 角色許可政策***

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "AllowAccountLevelS3Actions",
            "Effect": "Allow",
            "Action": [
                "s3:GetBucketLocation",
                "s3:GetAccountPublicAccessBlock",
                "s3:ListAccessPoints",
                "s3:ListAllMyBuckets"
            ],
            "Resource": "arn:aws:s3:::*"
        },
        {
            "Sid": "AllowListAndReadS3ActionOnMyBucket",
            "Effect": "Allow",
            "Action": [
                "s3:Get*",
                "s3:List*"
            ],
            "Resource": [
                "arn:aws:s3:::amzn-s3-demo-bucket1/*",
                "arn:aws:s3:::amzn-s3-demo-bucket1"
            ]
        },
        {
            "Sid": "AllowIPToAssumeCrossAccountRole",
            "Effect": "Allow",
            "Action": "sts:AssumeRole",
            "Resource": "arn:aws:iam::222222222222:role/efgh"
        }
    ]
}
```

------

`abcd` 角色必須信任 Amazon EC2 服務擔任該角色。若要執行此操作，`abcd` 角色必須有以下信任政策：

***帳戶 111111111111 `abcd` 角色信任政策***

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "abcdTrustPolicy",
            "Effect": "Allow",
            "Action": "sts:AssumeRole",
            "Principal": {"Service": "ec2.amazonaws.com"}
        }
    ]
}
```

------

假設 `efgh` 跨帳戶角色允許在相同 `222222222222` 帳戶中對 `amzn-s3-demo-bucket2` 儲存貯體的唯讀 Amazon S3 任務。若要執行此操作，`efgh` 跨帳戶角色必須有以下許可政策：

***帳戶 222222222222 `efgh` 角色許可政策***

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "AllowAccountLevelS3Actions",
            "Effect": "Allow",
            "Action": [
                "s3:GetBucketLocation",
                "s3:GetAccountPublicAccessBlock",
                "s3:ListAccessPoints",
                "s3:ListAllMyBuckets"
            ],
            "Resource": "arn:aws:s3:::*"
        },
        {
            "Sid": "AllowListAndReadS3ActionOnMyBucket",
            "Effect": "Allow",
            "Action": [
                "s3:Get*",
                "s3:List*"
            ],
            "Resource": [
                "arn:aws:s3:::amzn-s3-demo-bucket2/*",
                "arn:aws:s3:::amzn-s3-demo-bucket2"
            ]
        }
    ]
}
```

------

`efgh` 角色必須信任 `abcd` 執行個體設定檔角色擔任該角色。若要執行此操作，`efgh` 角色必須有以下信任政策：

***帳戶 222222222222 `efgh` 角色信任政策***

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "efghTrustPolicy",
            "Effect": "Allow",
            "Action": "sts:AssumeRole",
            "Principal": {"AWS": "arn:aws:iam::111111111111:role/abcd"}
        }
    ]
}
```

------

## 我該如何開始？
<a name="roles-usingrole-ec2instance-get-started"></a>

若要了解角色如何使用 Amazon EC2 執行個體，您需要使用 IAM 主控台建立角色，啟動使用該角色的 Amazon EC2 執行個體，然後檢查正在執行的執行個體。您可以檢查[執行個體中繼資料](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html)以查看角色的暫時憑證如何可用於執行個體。您還可以查看在執行個體上執行的應用程式如何使用該角色。使用以下資源以進一步了解。
+ [「在 Amazon EC2 執行個體上使用 IAM 角色」教學課程](https://www.youtube.com/watch?v=TlCuOjviOhk)。連結的影片會說明如何將 IAM 角色與 Amazon EC2 執行個體一起使用，以控制應用程式在執行個體上執行時可以執行的操作。影片顯示應用程式 （在 AWS SDK 中撰寫） 如何透過 角色取得臨時安全登入資料。
+ SDK 演練。軟體 AWS 開發套件文件包含逐步解說，顯示在 Amazon EC2 執行個體上執行的應用程式，該執行個體使用角色的臨時登入資料來讀取 Amazon S3 儲存貯體。以下每個演練都使用不同的程式設計語言提供類似的步驟：
  + 《適用於 Java 的 AWS SDK 開發人員指南》**中的[使用 SDK for Java 設定 Amazon EC2 的 IAM 角色](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/java-dg-roles.html) 
  + *《適用於 .NET 的 AWS SDK 開發人員指南》*中的[使用適用於 .NET 的開發套件啟動 Amazon EC2 執行個體](https://docs.aws.amazon.com/sdk-for-net/latest/developer-guide/run-instance.html)
  + 《適用於 Ruby 的 AWS SDK 開發人員指南》**中的[使用 SDK for Ruby 建立 Amazon EC2 執行個體](https://docs.aws.amazon.com/sdk-for-ruby/latest/developer-guide/ec2-example-create-instance.html)

## 相關資訊
<a name="roles-usingrole-ec2instance-related-info"></a>

如需建立角色或為 Amazon EC2 執行個體建立角色的詳細資訊，請參閱以下資訊：
+ 如需有關[搭配 Amazon EC2 執行個體使用 IAM 角色](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html) 的詳細資訊，請前往《Amazon EC2 使用者指南》**。
+ 若要建立角色，請參閱 [IAM 角色建立](id_roles_create.md)
+ 如需有關使用暫時安全憑證的詳細資訊，請參閱 [IAM 中的暫時安全憑證](id_credentials_temp.md)。
+ 如果使用 IAM API 或 CLI，則必須建立和管理 IAM 執行個體描述檔。如需有關執行個體設定檔的詳細資訊，請參閱 [使用執行個體設定檔](id_roles_use_switch-role-ec2_instance-profiles.md)。
+ 如需有關執行個體中繼資料中角色之臨時安全憑證的詳細資訊，請參閱《Amazon EC2 使用者指南》**中的 [Retrieving Security Credentials from Instance Metadata](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html#instance-metadata-security-credentials)。

# 使用執行個體設定檔
<a name="id_roles_use_switch-role-ec2_instance-profiles"></a>

使用執行個體描述檔將 IAM 角色傳遞給 EC2 執行個體。如需詳細資訊，請參閱 *Amazon EC2 User Guide* 中的 [IAM roles for Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html)。

## 管理執行個體設定檔 (主控台)
<a name="instance-profiles-manage-console"></a>

如果您使用 AWS 管理主控台 為 Amazon EC2 建立角色，主控台會自動建立執行個體描述檔，並為其提供與該角色相同的名稱。然後，當您使用 Amazon EC2 主控台啟動具有 IAM 角色的執行個體時，可以選擇要與執行個體關聯的角色。在主控台中，顯示的清單實際上是執行個體設定檔名稱的清單。主控台不會為與 Amazon EC2 無關的角色建立執行個體描述檔。

如果角色和執行個體描述檔具有相同的名稱，您可以使用 AWS 管理主控台 刪除 Amazon EC2 的 IAM 角色和執行個體描述檔。若要進一步了解刪除執行個體描述檔，請參閱 [刪除角色或執行個體設定檔](id_roles_manage_delete.md)。

**注意**  
若要更新執行個體的許可，請取代其執行個體設定檔。不建議從執行個體設定檔中移除角色，因為最多需要延遲一小時，此變更才生效。

## 管理執行個體描述檔 (AWS CLI 或 AWS API)
<a name="instance-profiles-manage-cli-api"></a>

如果您從 AWS CLI 或 AWS API 管理您的角色，您可以將角色和執行個體描述檔建立為個別動作。由於角色和執行個體描述檔可以有不同的名稱，因此您必須知道執行個體描述檔的名稱以及它們包含的角色的名稱。這樣，您可以在啟動 EC2 執行個體時選擇正確的執行個體描述檔。

您可以將標籤連接至 IAM 資源 (包括執行個體描述檔)，以識別、整理和控制其存取。您只能在使用 AWS CLI 或 AWS API 時標記執行個體描述檔。

**注意**  
執行個體描述檔只能包含一個 IAM 角色，但角色可以包含在多個執行個體描述檔中。每個執行個體設定檔的一個角色的限制無法增加。您可以移除現有角色，然後將不同角色新增到執行個體描述檔。然後 AWS ，由於[最終一致性](https://en.wikipedia.org/wiki/Eventual_consistency)，您必須等待變更出現在所有 中。若要強制變更，必須[取消關聯執行個體描述檔](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DisassociateIamInstanceProfile.html)，然後[關聯執行個體描述檔](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_AssociateIamInstanceProfile.html)，或者可以停止執行個體，然後重新啟動它。

### 管理執行個體設定檔 (AWS CLI)
<a name="instance-profiles-manage-cli"></a>

您可以使用下列 AWS CLI 命令來使用 帳戶中的 AWS 執行個體描述檔。
+ 建立執行個體描述檔: [https://docs.aws.amazon.com/cli/latest/reference/iam/create-instance-profile.html](https://docs.aws.amazon.com/cli/latest/reference/iam/create-instance-profile.html)
+ 標記執行個體描述檔：[https://docs.aws.amazon.com/cli/latest/reference/iam/tag-instance-profile.html](https://docs.aws.amazon.com/cli/latest/reference/iam/tag-instance-profile.html)
+ 列出執行個體描述檔的標籤：[https://docs.aws.amazon.com/cli/latest/reference/iam/list-instance-profile-tags.html](https://docs.aws.amazon.com/cli/latest/reference/iam/list-instance-profile-tags.html)
+ 取消標記執行個體描述檔：[https://docs.aws.amazon.com/cli/latest/reference/iam/untag-instance-profile.html](https://docs.aws.amazon.com/cli/latest/reference/iam/untag-instance-profile.html)
+ 將角色新增至執行個體描述檔: [https://docs.aws.amazon.com/cli/latest/reference/iam/add-role-to-instance-profile.html](https://docs.aws.amazon.com/cli/latest/reference/iam/add-role-to-instance-profile.html) 
+ 列出執行個體描述檔: [https://docs.aws.amazon.com/cli/latest/reference/iam/list-instance-profiles.html](https://docs.aws.amazon.com/cli/latest/reference/iam/list-instance-profiles.html), [https://docs.aws.amazon.com/cli/latest/reference/iam/list-instance-profiles-for-role.html](https://docs.aws.amazon.com/cli/latest/reference/iam/list-instance-profiles-for-role.html) 
+ 取得有關執行個體描述檔的資訊: [https://docs.aws.amazon.com/cli/latest/reference/iam/get-instance-profile.html](https://docs.aws.amazon.com/cli/latest/reference/iam/get-instance-profile.html) 
+ 從執行個體描述檔中移除角色: [https://docs.aws.amazon.com/cli/latest/reference/iam/remove-role-from-instance-profile.html](https://docs.aws.amazon.com/cli/latest/reference/iam/remove-role-from-instance-profile.html)
+ 刪除執行個體描述檔: [https://docs.aws.amazon.com/cli/latest/reference/iam/delete-instance-profile.html](https://docs.aws.amazon.com/cli/latest/reference/iam/delete-instance-profile.html) 

您還可以使用以下命令將角色連接到已在執行的 EC2 執行個體。如需詳細資訊，請參閱 [Amazon EC2 的 IAM 角色](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html#attach-iam-role)。
+ 將具有角色的執行個體描述檔連接至已停止或正在執行的 EC2 執行個體: [https://docs.aws.amazon.com/cli/latest/reference/ec2/associate-iam-instance-profile.html](https://docs.aws.amazon.com/cli/latest/reference/ec2/associate-iam-instance-profile.html) 
+ 取得有關連接至 EC2 執行個體的執行個體描述檔的資訊: [https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-iam-instance-profile-associations.html](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-iam-instance-profile-associations.html) 
+ 使用已停止或正在執行的 EC2 執行個體中的角色分開執行個體描述檔：[https://docs.aws.amazon.com/cli/latest/reference/ec2/disassociate-iam-instance-profile.html](https://docs.aws.amazon.com/cli/latest/reference/ec2/disassociate-iam-instance-profile.html)

### 管理執行個體描述檔 (AWS API)
<a name="instance-profiles-manage-api"></a>

您可以呼叫下列 AWS API 操作，以在 中使用執行個體描述檔 AWS 帳戶。
+ 建立執行個體描述檔: [https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateInstanceProfile.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateInstanceProfile.html) 
+ 標記執行個體描述檔：[https://docs.aws.amazon.com/IAM/latest/APIReference/API_TagInstanceProfile.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_TagInstanceProfile.html)
+ 列出執行個體描述檔的標籤：[https://docs.aws.amazon.com/IAM/latest/APIReference/API_TagInstanceProfile.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_TagInstanceProfile.html)
+ 取消標記執行個體描述檔：[https://docs.aws.amazon.com/IAM/latest/APIReference/API_TagInstanceProfile.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_TagInstanceProfile.html)
+ 將角色新增至執行個體描述檔: [https://docs.aws.amazon.com/IAM/latest/APIReference/API_AddRoleToInstanceProfile.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_AddRoleToInstanceProfile.html) 
+ 列出執行個體描述檔: [https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListInstanceProfiles.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListInstanceProfiles.html), [https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListInstanceProfilesForRole.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListInstanceProfilesForRole.html) 
+ 取得有關執行個體描述檔的資訊: [https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetInstanceProfile.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetInstanceProfile.html) 
+ 從執行個體描述檔中移除角色: [https://docs.aws.amazon.com/IAM/latest/APIReference/API_RemoveRoleFromInstanceProfile.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_RemoveRoleFromInstanceProfile.html) 
+ 刪除執行個體描述檔: [https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteInstanceProfile.html](https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteInstanceProfile.html) 

您還可以呼叫以下操作將角色連接到已在執行的 EC2 執行個體。如需詳細資訊，請參閱 [Amazon EC2 的 IAM 角色](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html#attach-iam-role)。
+ 將具有角色的執行個體描述檔連接至已停止或正在執行的 EC2 執行個體: [https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_AssociateIamInstanceProfile.html](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_AssociateIamInstanceProfile.html) 
+ 取得有關連接至 EC2 執行個體的執行個體描述檔的資訊: [https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeIamInstanceProfileAssociations.html](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeIamInstanceProfileAssociations.html) 
+ 使用已停止或正在執行的 EC2 執行個體中的角色分開執行個體描述檔：[https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DisassociateIamInstanceProfile.html](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DisassociateIamInstanceProfile.html)