

第 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)

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

# 使用 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 檔案、安全群組等。