

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

# `PutRolePolicy` 搭配 AWS SDK 或 CLI 使用
<a name="iam_example_iam_PutRolePolicy_section"></a>

下列程式碼範例示範如何使用 `PutRolePolicy`。

動作範例是大型程式的程式碼摘錄，必須在內容中執行。您可以在下列程式碼範例的內容中看到此動作：
+  [開始使用 Redshift Serverless](iam_example_redshift_GettingStarted_038_section.md) 
+  [Amazon Redshift 佈建叢集入門](iam_example_redshift_GettingStarted_039_section.md) 
+  [Config 入門](iam_example_config_service_GettingStarted_053_section.md) 
+  [IoT Device Defender 入門](iam_example_iot_GettingStarted_079_section.md) 
+  [使用 FIS 在 EC2 執行個體上執行 CPU 壓力測試](iam_example_iam_GettingStarted_069_section.md) 

------
#### [ .NET ]

**適用於 .NET 的 SDK**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/IAM#code-examples)中設定和執行。

```
    /// <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;
    }
```
+  如需 API 詳細資訊，請參閱 *適用於 .NET 的 AWS SDK API Reference* 中的 [PutRolePolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/PutRolePolicy)。

------
#### [ 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)中設定和執行。

```
bool AwsDoc::IAM::putRolePolicy(
        const Aws::String &roleName,
        const Aws::String &policyName,
        const Aws::String &policyDocument,
        const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::IAM::IAMClient iamClient(clientConfig);
    Aws::IAM::Model::PutRolePolicyRequest request;

    request.SetRoleName(roleName);
    request.SetPolicyName(policyName);
    request.SetPolicyDocument(policyDocument);

    Aws::IAM::Model::PutRolePolicyOutcome outcome = iamClient.PutRolePolicy(request);
    if (!outcome.IsSuccess()) {
        std::cerr << "Error putting policy on role. " <<
                  outcome.GetError().GetMessage() << std::endl;
    }
    else {
        std::cout << "Successfully put the role policy." << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  如需 API 詳細資訊，請參閱 *適用於 C\$1\$1 的 AWS SDK API Reference* 中的 [PutRolePolicy](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/PutRolePolicy)。

------
#### [ CLI ]

**AWS CLI**  
**將許可政策連接至 IAM 角色**  
下列 `put-role-policy` 命令會將許可政策連接到名為 `Test-Role` 的角色。  

```
aws iam put-role-policy \
    --role-name Test-Role \
    --policy-name ExamplePolicy \
    --policy-document file://AdminPolicy.json
```
此命令不會產生輸出。  
會在 *AdminPolicy.json* 檔案中將此政策定義為 JSON 文件。(檔案名稱和副檔名沒有意義。)  
若要將信任政策連接至角色，請使用 `update-assume-role-policy` 命令。  
如需詳細資訊，請參閱《AWS IAM 使用者指南》**中的[修改角色](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_manage_modify.html)。  
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [PutRolePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/put-role-policy.html)。

------
#### [ JavaScript ]

**適用於 JavaScript (v3) 的 SDK**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)中設定和執行。

```
import { PutRolePolicyCommand, IAMClient } from "@aws-sdk/client-iam";

const examplePolicyDocument = JSON.stringify({
  Version: "2012-10-17",
  Statement: [
    {
      Sid: "VisualEditor0",
      Effect: "Allow",
      Action: [
        "s3:ListBucketMultipartUploads",
        "s3:ListBucketVersions",
        "s3:ListBucket",
        "s3:ListMultipartUploadParts",
      ],
      Resource: "arn:aws:s3:::amzn-s3-demo-bucket",
    },
    {
      Sid: "VisualEditor1",
      Effect: "Allow",
      Action: [
        "s3:ListStorageLensConfigurations",
        "s3:ListAccessPointsForObjectLambda",
        "s3:ListAllMyBuckets",
        "s3:ListAccessPoints",
        "s3:ListJobs",
        "s3:ListMultiRegionAccessPoints",
      ],
      Resource: "*",
    },
  ],
});

const client = new IAMClient({});

/**
 *
 * @param {string} roleName
 * @param {string} policyName
 * @param {string} policyDocument
 */
export const putRolePolicy = async (roleName, policyName, policyDocument) => {
  const command = new PutRolePolicyCommand({
    RoleName: roleName,
    PolicyName: policyName,
    PolicyDocument: policyDocument,
  });

  const response = await client.send(command);
  console.log(response);
  return response;
};
```
+  如需 API 詳細資訊，請參閱 *適用於 JavaScript 的 AWS SDK API Reference* 中的 [PutRolePolicy](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/PutRolePolicyCommand)。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**範例 1：此範例會建立名為 `FedTesterRolePolicy` 的內嵌政策，並將其內嵌在 IAM 角色 `FedTesterRole` 中。如果已存在同名的內嵌政策，其會被覆寫。JSON 政策內容來自 `FedTesterPolicy.json` 檔案。請注意，必須使用 `-Raw` 參數，才能成功處理 JSON 檔案的內容。**  

```
Write-IAMRolePolicy -RoleName FedTesterRole -PolicyName FedTesterRolePolicy -PolicyDocument (Get-Content -Raw FedTesterPolicy.json)
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V4)》**中的 [PutRolePolicy](https://docs.aws.amazon.com/powershell/v4/reference)。

**Tools for PowerShell V5**  
**範例 1：此範例會建立名為 `FedTesterRolePolicy` 的內嵌政策，並將其內嵌在 IAM 角色 `FedTesterRole` 中。如果已存在同名的內嵌政策，其會被覆寫。JSON 政策內容來自 `FedTesterPolicy.json` 檔案。請注意，必須使用 `-Raw` 參數，才能成功處理 JSON 檔案的內容。**  

```
Write-IAMRolePolicy -RoleName FedTesterRole -PolicyName FedTesterRolePolicy -PolicyDocument (Get-Content -Raw FedTesterPolicy.json)
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [PutRolePolicy](https://docs.aws.amazon.com/powershell/v5/reference)。

------

如需 AWS SDK 開發人員指南和程式碼範例的完整清單，請參閱 [搭配 AWS SDK 使用此服務](sdk-general-information-section.md)。此主題也包含有關入門的資訊和舊版 SDK 的詳細資訊。