

第 4 版 (V4) 適用於 .NET 的 AWS SDK 已發行！

如需有關中斷變更和遷移應用程式的資訊，請參閱[遷移主題](https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/net-dg-v4.html)。

 [https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/net-dg-v4.html](https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/net-dg-v4.html)

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

# 使用 存取 AWS Identity and Access Management (IAM) 適用於 .NET 的 AWS SDK
<a name="iam-apis-intro"></a>

 適用於 .NET 的 AWS SDK 支援 [AWS Identity and Access Management](https://docs.aws.amazon.com/IAM/latest/UserGuide/)，這是一種 Web 服務，可讓 AWS 客戶管理 中的使用者和使用者許可 AWS。

 AWS Identity and Access Management (IAM) *使用者*是您建立的實體 AWS。實體代表與 互動的人員或應用程式 AWS。如需 IAM 使用者的詳細資訊，請參閱《IAM 使用者指南》中的 IAM [使用者](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users.html)和 IAM [和 STS 限制](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-limits.html)。

您可以透過建立 IAM *政策*將許可授予使用者。政策包含*政策文件*，其中列出使用者可以執行的動作，以及這些動作可以影響的資源。如需 IAM 政策的詳細資訊，請參閱《*IAM 使用者指南*[》中的政策和許可](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html)。

**警告**  
為避免安全風險，在開發專用軟體或使用真實資料時，請勿使用 IAM 使用者進行身分驗證。相反地，搭配使用聯合功能和身分提供者，例如 [AWS IAM Identity Center](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html)。

## API
<a name="w2aac19c15c23c13"></a>

為 IAM 用戶端 適用於 .NET 的 AWS SDK 提供 APIs。APIs 可讓您使用 IAM 功能，例如使用者、角色和存取金鑰。

本節包含一些範例，顯示您在使用這些 APIs 時可遵循的模式。若要檢視完整的 APIs，請參閱 [適用於 .NET 的 AWS SDK API 參考](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/) （並捲動至「Amazon.IdentityManagement」)。

本節也包含[範例](net-dg-hosm.md)，說明如何將 IAM 角色連接至 Amazon EC2 執行個體，以便更輕鬆地管理登入資料。

IAM APIs 由 [AWSSDK.IdentityManagement](https://www.nuget.org/packages/AWSSDK.IdentityManagement) NuGet 套件提供。

## 先決條件
<a name="w2aac19c15c23c15"></a>

開始之前，請確定您已[設定環境](net-dg-config.md)並[設定專案](configuring-the-sdk.md)。也請檢閱 中的資訊[使用開發套件](net-dg-sdk-features.md)。

## 主題
<a name="w2aac19c15c23c17"></a>

**Topics**
+ [API](#w2aac19c15c23c13)
+ [先決條件](#w2aac19c15c23c15)
+ [主題](#w2aac19c15c23c17)
+ [從 JSON 建立受管政策](iam-policies-create-json.md)
+ [顯示政策文件](iam-policies-display.md)
+ [使用角色授予存取權](net-dg-hosm.md)

# 從 JSON 建立 IAM 受管政策
<a name="iam-policies-create-json"></a>

此範例說明如何使用 從 JSON 中的指定政策文件中 適用於 .NET 的 AWS SDK 建立 [IAM 受](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-vs-inline.html#aws-managed-policies)管政策。應用程式會建立 IAM 用戶端物件、從 檔案讀取政策文件，然後建立政策。

**注意**  
如需 JSON 中的範例政策文件，請參閱本主題結尾[的其他考量](#iam-policies-create-json-additional)事項。

下列各節提供此範例的程式碼片段。之後會顯示[範例的完整程式碼](#iam-policies-create-json-complete-code)，並可依原樣建置和執行。

**Topics**
+ [建立政策](#iam-policies-create-json-create)
+ [完成程式碼](#iam-policies-create-json-complete-code)
+ [其他考量](#iam-policies-create-json-additional)

## 建立政策
<a name="iam-policies-create-json-create"></a>

下列程式碼片段會建立具有指定名稱和政策文件的 IAM 受管政策。

[本主題結尾](#iam-policies-create-json-complete-code)的範例顯示此程式碼片段正在使用中。

```
    //
    // Method to create an IAM policy from a JSON file
    private static async Task<CreatePolicyResponse> CreateManagedPolicy(
      IAmazonIdentityManagementService iamClient, string policyName, string jsonFilename)
    {
      return await iamClient.CreatePolicyAsync(new CreatePolicyRequest{
        PolicyName = policyName,
        PolicyDocument = File.ReadAllText(jsonFilename)});
    }
```

## 完成程式碼
<a name="iam-policies-create-json-complete-code"></a>

本節顯示此範例的相關參考和完整程式碼。

### 開發套件參考
<a name="w2aac19c15c23c21c17b5b1"></a>

NuGet 套件：
+ [AWSSDK.IdentityManagement](https://www.nuget.org/packages/AWSSDK.IdentityManagement)

程式設計元素：
+ 命名空間 [Amazon.IdentityManagement](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/IAM/NIAM.html)

  [AmazonIdentityManagementServiceClient](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/IAM/TIAMServiceClient.html) 類別
+ 命名空間 [Amazon.IdentityManagement.Model](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/IAM/NIAMModel.html)

  類別 [CreatePolicyRequest](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/IAM/TCreatePolicyRequest.html)

  類別 [CreatePolicyResponse](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/IAM/TCreatePolicyResponse.html)

### 程式碼
<a name="w2aac19c15c23c21c17b7b1"></a>

```
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Amazon.IdentityManagement;
using Amazon.IdentityManagement.Model;

namespace IamCreatePolicyFromJson
{
  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // Class to create an IAM policy with a given policy document
  class Program
  {
    private const int MaxArgs = 2;

    static async Task Main(string[] args)
    {
      // Parse the command line and show help if necessary
      var parsedArgs = CommandLine.Parse(args);
      if((parsedArgs.Count == 0) || (parsedArgs.Count > MaxArgs))
      {
        PrintHelp();
        return;
      }

      // Get the application arguments from the parsed list
      string policyName =
        CommandLine.GetArgument(parsedArgs, null, "-p", "--policy-name");
      string policyFilename =
        CommandLine.GetArgument(parsedArgs, null, "-j", "--json-filename");
      if(   string.IsNullOrEmpty(policyName)
         || (string.IsNullOrEmpty(policyFilename) || !policyFilename.EndsWith(".json")))
        CommandLine.ErrorExit(
          "\nOne or more of the required arguments is missing or incorrect." +
          "\nRun the command with no arguments to see help.");

      // Create an IAM service client
      var iamClient = new AmazonIdentityManagementServiceClient();

      // Create the new policy
      var response = await CreateManagedPolicy(iamClient, policyName, policyFilename);
      Console.WriteLine($"\nPolicy {response.Policy.PolicyName} has been created.");
      Console.WriteLine($"  Arn: {response.Policy.Arn}");
    }


    //
    // Method to create an IAM policy from a JSON file
    private static async Task<CreatePolicyResponse> CreateManagedPolicy(
      IAmazonIdentityManagementService iamClient, string policyName, string jsonFilename)
    {
      return await iamClient.CreatePolicyAsync(new CreatePolicyRequest{
        PolicyName = policyName,
        PolicyDocument = File.ReadAllText(jsonFilename)});
    }


    //
    // Command-line help
    private static void PrintHelp()
    {
      Console.WriteLine(
        "\nUsage: IamCreatePolicyFromJson -p <policy-name> -j <json-filename>" +
        "\n  -p, --policy-name: The name you want the new policy to have." +
        "\n  -j, --json-filename: The name of the JSON file with the policy document.");
    }
  }


  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // Class that represents a command line on the console or terminal.
  // (This is the same for all examples. When you have seen it once, you can ignore it.)
  static class CommandLine
  {
    //
    // Method to parse a command line of the form: "--key value" or "-k value".
    //
    // Parameters:
    // - args: The command-line arguments passed into the application by the system.
    //
    // Returns:
    // A Dictionary with string Keys and Values.
    //
    // If a key is found without a matching value, Dictionary.Value is set to the key
    //  (including the dashes).
    // If a value is found without a matching key, Dictionary.Key is set to "--NoKeyN",
    //  where "N" represents sequential numbers.
    public static Dictionary<string,string> Parse(string[] args)
    {
      var parsedArgs = new Dictionary<string,string>();
      int i = 0, n = 0;
      while(i < args.Length)
      {
        // If the first argument in this iteration starts with a dash it's an option.
        if(args[i].StartsWith("-"))
        {
          var key = args[i++];
          var value = key;

          // Check to see if there's a value that goes with this option?
          if((i < args.Length) && (!args[i].StartsWith("-"))) value = args[i++];
          parsedArgs.Add(key, value);
        }

        // If the first argument in this iteration doesn't start with a dash, it's a value
        else
        {
          parsedArgs.Add("--NoKey" + n.ToString(), args[i++]);
          n++;
        }
      }

      return parsedArgs;
    }

    //
    // Method to get an argument from the parsed command-line arguments
    //
    // Parameters:
    // - parsedArgs: The Dictionary object returned from the Parse() method (shown above).
    // - defaultValue: The default string to return if the specified key isn't in parsedArgs.
    // - keys: An array of keys to look for in parsedArgs.
    public static string GetArgument(
      Dictionary<string,string> parsedArgs, string defaultReturn, params string[] keys)
    {
      string retval = null;
      foreach(var key in keys)
        if(parsedArgs.TryGetValue(key, out retval)) break;
      return retval ?? defaultReturn;
    }

    //
    // Method to exit the application with an error.
    public static void ErrorExit(string msg, int code=1)
    {
      Console.WriteLine("\nError");
      Console.WriteLine(msg);
      Environment.Exit(code);
    }
  }

}
```

## 其他考量
<a name="iam-policies-create-json-additional"></a>
+ 以下是您可以複製到 JSON 檔案並用作此應用程式輸入的範例政策文件：

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

****  

  ```
  {
    "Version":"2012-10-17",		 	 	 
    "Id"  : "DotnetTutorialPolicy",
    "Statement" : [
      {
        "Sid" : "DotnetTutorialPolicyS3",
        "Effect" : "Allow",
        "Action" : [
          "s3:Get*",
          "s3:List*"
        ],
        "Resource" : "*"
      },
      {
        "Sid" : "DotnetTutorialPolicyPolly",
        "Effect": "Allow",
        "Action": [
          "polly:DescribeVoices",
          "polly:SynthesizeSpeech"
        ],
        "Resource": "*"
      }
    ]
  }
  ```

------
+ 您可以在 [IAM 主控台](https://console.aws.amazon.com/iam/home#/policies)中查看政策是否已建立。在**篩選政策**下拉式清單中，選取**客戶受管**。當您不再需要政策時，請將其刪除。
+  如需政策建立的詳細資訊，請參閱《[IAM 使用者指南》中的建立](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create.html) [IAM 政策和 IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/) [JSON 政策參考](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies.html) 

# 顯示 IAM 受管政策的政策文件
<a name="iam-policies-display"></a>

此範例說明如何使用 適用於 .NET 的 AWS SDK 來顯示政策文件。應用程式會建立 IAM 用戶端物件、尋找指定 IAM 受管政策的預設版本，然後在 JSON 中顯示政策文件。

下列各節提供此範例的程式碼片段。之後會顯示[範例的完整程式碼](#iam-policies-display-complete-code)，並可依原樣建置和執行。

**Topics**
+ [尋找預設版本](#iam-policies-display-version)
+ [顯示政策文件](#iam-policies-display-doc)
+ [完成程式碼](#iam-policies-display-complete-code)

## 尋找預設版本
<a name="iam-policies-display-version"></a>

下列程式碼片段會尋找指定 IAM 政策的預設版本。

[本主題結尾](#iam-policies-display-complete-code)的範例顯示此程式碼片段正在使用中。

```
    //
    // Method to determine the default version of an IAM policy
    // Returns a string with the version
    private static async Task<string> GetDefaultVersion(
      IAmazonIdentityManagementService iamClient, string policyArn)
    {
      // Retrieve all the versions of this policy
      string defaultVersion = string.Empty;
      ListPolicyVersionsResponse reponseVersions =
        await iamClient.ListPolicyVersionsAsync(new ListPolicyVersionsRequest{
          PolicyArn = policyArn});

      // Find the default version
      foreach(PolicyVersion version in reponseVersions.Versions)
      {
        if(version.IsDefaultVersion)
        {
          defaultVersion = version.VersionId;
          break;
        }
      }

      return defaultVersion;
    }
```

## 顯示政策文件
<a name="iam-policies-display-doc"></a>

下列程式碼片段會以指定 IAM 政策的 JSON 顯示政策文件。

[本主題結尾](#iam-policies-display-complete-code)的範例顯示此程式碼片段正在使用中。

```
    //
    // Method to retrieve and display the policy document of an IAM policy
    private static async Task ShowPolicyDocument(
      IAmazonIdentityManagementService iamClient, string policyArn, string defaultVersion)
    {
      // Retrieve the policy document of the default version
      GetPolicyVersionResponse responsePolicy =
        await iamClient.GetPolicyVersionAsync(new GetPolicyVersionRequest{
          PolicyArn = policyArn,
          VersionId = defaultVersion});

      // Display the policy document (in JSON)
      Console.WriteLine($"Version {defaultVersion} of the policy (in JSON format):");
      Console.WriteLine(
        $"{HttpUtility.UrlDecode(responsePolicy.PolicyVersion.Document)}");
    }
```

## 完成程式碼
<a name="iam-policies-display-complete-code"></a>

本節顯示此範例的相關參考和完整程式碼。

### 開發套件參考
<a name="w2aac19c15c23c23c19b5b1"></a>

NuGet 套件：
+ [AWSSDK.IdentityManagement](https://www.nuget.org/packages/AWSSDK.IdentityManagement)

程式設計元素：
+ 命名空間 [Amazon.IdentityManagement](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/IAM/NIAM.html)

  [AmazonIdentityManagementServiceClient](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/IAM/TIAMServiceClient.html) 類別
+ 命名空間 [Amazon.IdentityManagement.Model](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/IAM/NIAMModel.html)

  類別 [GetPolicyVersionRequest](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/IAM/TGetPolicyVersionRequest.html)

  類別 [GetPolicyVersionResponse](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/IAM/TGetPolicyVersionResponse.html)

  類別 [ListPolicyVersionsRequest](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/IAM/TListPolicyVersionsRequest.html)

  類別 [ListPolicyVersionsResponse](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/IAM/TListPolicyVersionsResponse.html)

  類別[PolicyVersion](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/IAM/TPolicyVersion.html)

### 程式碼
<a name="w2aac19c15c23c23c19b7b1"></a>

```
using System;
using System.Web;
using System.Threading.Tasks;
using Amazon.IdentityManagement;
using Amazon.IdentityManagement.Model;

namespace IamDisplayPolicyJson
{
  class Program
  {
    static async Task Main(string[] args)
    {
      // Parse the command line and show help if necessary
      if(args.Length != 1)
      {
        Console.WriteLine("\nUsage: IamDisplayPolicyJson policy-arn");
        Console.WriteLine("   policy-arn: The ARN of the policy to retrieve.");
        return;
      }
      if(!args[0].StartsWith("arn:"))
      {
        Console.WriteLine("\nCould not find policy ARN in the command-line arguments:");
        Console.WriteLine($"{args[0]}");
        return;
      }

      // Create an IAM service client
      var iamClient = new AmazonIdentityManagementServiceClient();

      // Retrieve and display the policy document of the given policy
      string defaultVersion = await GetDefaultVersion(iamClient, args[0]);
      if(string.IsNullOrEmpty(defaultVersion))
        Console.WriteLine($"Could not find the default version for policy {args[0]}.");
      else
        await ShowPolicyDocument(iamClient, args[0], defaultVersion);
    }


    //
    // Method to determine the default version of an IAM policy
    // Returns a string with the version
    private static async Task<string> GetDefaultVersion(
      IAmazonIdentityManagementService iamClient, string policyArn)
    {
      // Retrieve all the versions of this policy
      string defaultVersion = string.Empty;
      ListPolicyVersionsResponse reponseVersions =
        await iamClient.ListPolicyVersionsAsync(new ListPolicyVersionsRequest{
          PolicyArn = policyArn});

      // Find the default version
      foreach(PolicyVersion version in reponseVersions.Versions)
      {
        if(version.IsDefaultVersion)
        {
          defaultVersion = version.VersionId;
          break;
        }
      }

      return defaultVersion;
    }


    //
    // Method to retrieve and display the policy document of an IAM policy
    private static async Task ShowPolicyDocument(
      IAmazonIdentityManagementService iamClient, string policyArn, string defaultVersion)
    {
      // Retrieve the policy document of the default version
      GetPolicyVersionResponse responsePolicy =
        await iamClient.GetPolicyVersionAsync(new GetPolicyVersionRequest{
          PolicyArn = policyArn,
          VersionId = defaultVersion});

      // Display the policy document (in JSON)
      Console.WriteLine($"Version {defaultVersion} of the policy (in JSON format):");
      Console.WriteLine(
        $"{HttpUtility.UrlDecode(responsePolicy.PolicyVersion.Document)}");
    }
  }
}
```

# 使用 IAM 角色授予存取權
<a name="net-dg-hosm"></a>

本教學課程說明如何使用 適用於 .NET 的 AWS SDK 在 Amazon EC2 執行個體上啟用 IAM 角色。

## 概觀
<a name="hosm-overview"></a>

對 的所有請求 AWS 都必須使用 發行的登入資料以密碼編譯方式簽署 AWS。因此，您需要策略來管理在 Amazon EC2 執行個體上執行之應用程式的登入資料。您必須安全地分發、存放和輪換這些登入資料，同時讓應用程式能夠存取這些登入資料。

透過 IAM 角色，您可以有效地管理這些登入資料。您可以建立 IAM 角色，並使用應用程式所需的許可進行設定，然後將該角色連接到 EC2 執行個體。若要進一步了解使用 IAM 角色的好處，請參閱《[Amazon EC2 使用者指南](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html)[》中的 Amazon EC2 的 IAM ](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/)角色。另請參閱《[IAM 使用者指南》中的 IAM 角色](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html)相關資訊。

對於使用 建置的應用程式 適用於 .NET 的 AWS SDK，當應用程式建構 AWS 服務的用戶端物件時，物件會從數個潛在來源搜尋登入資料。其搜尋的順序會顯示在 中[憑證和設定檔解析](creds-assign.md)。

如果用戶端物件找不到任何其他來源的登入資料，則會擷取具有與已設定為 IAM 角色且位於 EC2 執行個體中繼資料中相同許可的臨時登入資料。這些登入資料用於 AWS 從用戶端物件呼叫 。

## 關於本教學
<a name="about-hosm-tutorial"></a>

遵循本教學課程時，您可以使用 適用於 .NET 的 AWS SDK （和其他工具） 啟動已連接 IAM 角色的 Amazon EC2 執行個體，然後使用 IAM 角色的許可查看執行個體上的應用程式。

**Topics**
+ [概觀](#hosm-overview)
+ [關於本教學](#about-hosm-tutorial)
+ [建立範例 Amazon S3 應用程式](#net-dg-hosm-sample-s3-app)
+ [建立 IAM 角色](#net-dg-hosm-create-the-role)
+ [啟動 EC2 執行個體並連接 IAM 角色](#net-dg-hosm-launch-ec2-instance)
+ [連線至 EC2 執行個體](#net-dg-hosm-connect)
+ [在 EC2 執行個體上執行範例應用程式](#net-dg-hosm-run-the-app)
+ [清除](#net-dg-hosm-cleanup)

## 建立範例 Amazon S3 應用程式
<a name="net-dg-hosm-sample-s3-app"></a>

此範例應用程式會從 Amazon S3 擷取物件。若要執行應用程式，您需要下列項目：
+ 包含文字檔案的 Amazon S3 儲存貯體。
+ AWS 開發機器上的登入資料，可讓您存取 儲存貯體。

如需有關建立 Amazon S3 儲存貯體和上傳物件的資訊，請參閱 [Amazon Simple Storage Service 使用者指南](https://docs.aws.amazon.com/AmazonS3/latest/userguide/)。如需 AWS 登入資料的資訊，請參閱 [適用於 .NET 的 AWS SDK 使用 驗證 AWS](creds-idc.md)。

使用下列程式碼建立 .NET Core 專案。然後在開發機器上測試應用程式。

**注意**  
在您的開發機器上安裝了 .NET Core Runtime，可讓您在不發佈的情況下執行應用程式。在本教學稍後建立 EC2 執行個體時，您可以選擇在執行個體上安裝 .NET Core Runtime。這為您提供了類似的體驗和較小的檔案傳輸。  
 不過，您也可以選擇不要在執行個體上安裝 .NET Core Runtime。如果您選擇此動作，則必須發佈應用程式，以便在將應用程式轉移到執行個體時包含所有相依性。

### 開發套件參考
<a name="w2aac19c15c23c25c17c13b1"></a>

NuGet 套件：
+ [AWSSDK.S3](https://www.nuget.org/packages/AWSSDK.S3)

程式設計元素：
+ 命名空間 [Amazon.S3](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/S3/NS3.html)

  [AmazonS3Client](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/S3/TS3Client.html) 類別
+ 命名空間 [Amazon.S3.Model](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/S3/NS3Model.html)

  類別 [GetObjectResponse](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/S3/TGetObjectResponse.html)

### 程式碼
<a name="w2aac19c15c23c25c17c15b1"></a>

```
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Amazon.S3;
using Amazon.S3.Model;

namespace S3GetTextItem
{
  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // Class to retrieve a text file from an S3 bucket and write it to a local file
  class Program
  {
    static async Task Main(string[] args)
    {
      // Parse the command line and show help if necessary
      var parsedArgs = CommandLine.Parse(args);
      if(parsedArgs.Count == 0)
      {
        PrintHelp();
        return;
      }

      // Get the application arguments from the parsed list
      string bucket =
        CommandLine.GetArgument(parsedArgs, null, "-b", "--bucket-name");
      string item =
        CommandLine.GetArgument(parsedArgs, null, "-t", "--text-object");
      string outFile =
        CommandLine.GetArgument(parsedArgs, null, "-o", "--output-filename");
      if(   string.IsNullOrEmpty(bucket)
         || string.IsNullOrEmpty(item)
         || string.IsNullOrEmpty(outFile))
        CommandLine.ErrorExit(
          "\nOne or more of the required arguments is missing or incorrect." +
          "\nRun the command with no arguments to see help.");

      // Create the S3 client object and get the file object from the bucket.
      var response = await GetObject(new AmazonS3Client(), bucket, item);

      // Write the contents of the file object to the given output file.
      var reader = new StreamReader(response.ResponseStream);
      string contents = reader.ReadToEnd();
      using (var s = new FileStream(outFile, FileMode.Create))
      using (var writer = new StreamWriter(s))
        writer.WriteLine(contents);
    }


    //
    // Method to get an object from an S3 bucket.
    private static async Task<GetObjectResponse> GetObject(
      IAmazonS3 s3Client, string bucket, string item)
    {
        Console.WriteLine($"Retrieving {item} from bucket {bucket}.");
        return await s3Client.GetObjectAsync(bucket, item);
    }


    //
    // Command-line help
    private static void PrintHelp()
    {
      Console.WriteLine(
        "\nUsage: S3GetTextItem -b <bucket-name> -t <text-object> -o <output-filename>" +
        "\n  -b, --bucket-name: The name of the S3 bucket." +
        "\n  -t, --text-object: The name of the text object in the bucket." +
        "\n  -o, --output-filename: The name of the file to write the text to.");
    }
  }


  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // Class that represents a command line on the console or terminal.
  // (This is the same for all examples. When you have seen it once, you can ignore it.)
  static class CommandLine
  {
    //
    // Method to parse a command line of the form: "--key value" or "-k value".
    //
    // Parameters:
    // - args: The command-line arguments passed into the application by the system.
    //
    // Returns:
    // A Dictionary with string Keys and Values.
    //
    // If a key is found without a matching value, Dictionary.Value is set to the key
    //  (including the dashes).
    // If a value is found without a matching key, Dictionary.Key is set to "--NoKeyN",
    //  where "N" represents sequential numbers.
    public static Dictionary<string,string> Parse(string[] args)
    {
      var parsedArgs = new Dictionary<string,string>();
      int i = 0, n = 0;
      while(i < args.Length)
      {
        // If the first argument in this iteration starts with a dash it's an option.
        if(args[i].StartsWith("-"))
        {
          var key = args[i++];
          var value = key;

          // Check to see if there's a value that goes with this option?
          if((i < args.Length) && (!args[i].StartsWith("-"))) value = args[i++];
          parsedArgs.Add(key, value);
        }

        // If the first argument in this iteration doesn't start with a dash, it's a value
        else
        {
          parsedArgs.Add("--NoKey" + n.ToString(), args[i++]);
          n++;
        }
      }

      return parsedArgs;
    }

    //
    // Method to get an argument from the parsed command-line arguments
    //
    // Parameters:
    // - parsedArgs: The Dictionary object returned from the Parse() method (shown above).
    // - defaultValue: The default string to return if the specified key isn't in parsedArgs.
    // - keys: An array of keys to look for in parsedArgs.
    public static string GetArgument(
      Dictionary<string,string> parsedArgs, string defaultReturn, params string[] keys)
    {
      string retval = null;
      foreach(var key in keys)
        if(parsedArgs.TryGetValue(key, out retval)) break;
      return retval ?? defaultReturn;
    }

    //
    // Method to exit the application with an error.
    public static void ErrorExit(string msg, int code=1)
    {
      Console.WriteLine("\nError");
      Console.WriteLine(msg);
      Environment.Exit(code);
    }
  }

}
```

如果需要，您可以暫時移除在開發機器上使用的登入資料，以查看應用程式如何回應。（但請務必在完成時還原登入資料。)

## 建立 IAM 角色
<a name="net-dg-hosm-create-the-role"></a>

建立具有適當許可的 IAM 角色來存取 Amazon S3。

1. 開啟 [IAM 主控台](https://console.aws.amazon.com/iam/)。

1. 在導覽窗格中，選擇**角色**，然後選擇**建立角色**。

1. 選取**AWS 服務**，尋找並選擇 **EC2**，然後選擇**下一步：許可**。

1. 在**連接許可政策**下，尋找並選取 **AmazonS3ReadOnlyAccess**。如果您想要的話，請檢閱政策，然後選擇**下一步：標籤**。

1. 如果需要，請新增標籤，然後選擇**下一步：檢閱**。

1. 輸入該角色的名稱和說明，然後選擇 **Create role** (建立新角色)。請記住此名稱，因為在您啟動 EC2 執行個體時需要用到。

## 啟動 EC2 執行個體並連接 IAM 角色
<a name="net-dg-hosm-launch-ec2-instance"></a>

使用您先前建立的 IAM 角色啟動 EC2 執行個體。您可以透過下列方式執行此操作。
+ **使用 EC2 主控台**

  若要使用 EC2 主控台啟動執行個體，請參閱《[Amazon EC2 使用者指南](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/)》中的[使用新的啟動執行個體精靈啟動執行個體](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-instance-wizard.html)。

  當您查看啟動頁面時，您至少應該展開**進階詳細資訊**窗格，以便您可以指定先前在 IAM **執行個體描述檔中建立的 IAM** 角色。
+ **使用 適用於 .NET 的 AWS SDK**

  如需相關資訊，請參閱 [啟動 Amazon EC2 執行個體](run-instance.md)，包括該主題[其他考量](run-instance.md#run-instance-additional)接近結尾的 。

若要啟動已連接 IAM 角色的 EC2 執行個體，IAM 使用者的組態必須包含特定許可。如需所需許可的詳細資訊，請參閱《[Amazon EC2 使用者指南](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/)》中的[授予使用者將 IAM 角色傳遞至執行個體的許可](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html#permission-to-pass-iam-roles)。

## 連線至 EC2 執行個體
<a name="net-dg-hosm-connect"></a>

連線至 EC2 執行個體，以便您可以將範例應用程式轉移至該執行個體，然後執行應用程式。您需要包含用來啟動執行個體之金鑰對私有部分的 檔案，也就是 PEM 檔案。

如需連接至執行個體的資訊，請參閱《[Amazon EC2 使用者指南](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/)》中的[連接至 Linux 執行個體](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/connect-to-linux-instance.html)或[連接至 Windows 執行個體](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/connecting_to_windows_instance.html)。當您連線時，請以可讓您將檔案從開發機器傳輸到執行個體的方式執行此操作。

如果您在 Windows 上使用 Visual Studio，您也可以使用 Toolkit for Visual Studio 連線至執行個體。如需詳細資訊，請參閱 AWS Toolkit for Visual Studio 《 使用者指南》中的[連線至 Amazon EC2 執行個體](https://docs.aws.amazon.com/toolkit-for-visual-studio/latest/user-guide/tkv-ec2-ami.html#connect-ec2)。

## 在 EC2 執行個體上執行範例應用程式
<a name="net-dg-hosm-run-the-app"></a>

1. 將應用程式檔案從本機磁碟機複製到執行個體。

   傳輸哪些檔案取決於您建置應用程式的方式，以及執行個體是否已安裝 .NET Core Runtime。如需有關如何將檔案傳輸至執行個體的資訊，請參閱《[Amazon EC2 使用者指南](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/)》中的[連線至 Linux 執行個體](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/connect-to-linux-instance.html) （請參閱適當的子區段） 或[將檔案傳輸至 Windows 執行個體](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/connect-to-linux-instanceWindowsFileTransfer.html)。

1. 啟動應用程式，並確認其執行的結果與開發機器上的結果相同。

1. 確認應用程式使用 IAM 角色提供的登入資料。

   1. 開啟 [Amazon EC2 主控台](https://console.aws.amazon.com/ec2/)。

   1. 選取執行個體，並透過**動作**、**執行個體設定**、**連接/取代 IAM 角色來分離 IAM 角色**。

   1. 再次執行應用程式，並查看它傳回授權錯誤。

## 清除
<a name="net-dg-hosm-cleanup"></a>

完成本教學課程後，如果您不再需要您建立的 EC2 執行個體，請務必終止執行個體，以避免不必要的成本。您可以在 [Amazon EC2 主控台](https://console.aws.amazon.com/ec2/)或以程式設計方式執行此操作，如中所述[終止 Amazon EC2 執行個體](terminate-instance.md)。如果您願意，也可以刪除您為此教學課程建立的其他資源。這些可能包括 IAM 角色、EC2 金鑰對和 PEM 檔案、安全群組等。