

버전 4(V4) AWS SDK for .NET 가 릴리스되었습니다.

변경 사항 해제 및 애플리케이션 마이그레이션에 대한 자세한 내용은 [마이그레이션 주제를](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)

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# Amazon EC2 키 페어로 작업
<a name="key-pairs"></a>

Amazon EC2는 퍼블릭 키 암호화 기법을 사용하여 로그인 정보를 암호화 및 해독합니다. 퍼블릭 키 암호화 기법에서는 퍼블릭 키를 사용하여 데이터를 암호화한 후 수신자가 개인 키를 사용하여 해당 데이터를 해독합니다. 퍼블릭 키와 프라이빗 키를 키 페어라고 합니다. EC2 인스턴스에 로그인하려면 시작 시 키 페어를 지정한 다음 연결할 때 키 페어의 프라이빗 키를 제공해야 합니다.

EC2 인스턴스를 시작할 때 해당 인스턴스에 대해 키 페어를 생성하거나 다른 인스턴스를 시작할 때 이미 사용한 키 페어를 사용할 수 있습니다. Amazon EC2 키 페어에 대한 자세한 내용은 [Amazon EC2 사용 설명서](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/)의 [Amazon EC2 키 페어 작업](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html)을 참조하세요.

API 및 사전 조건에 대한 자세한 내용은 상위 섹션([Amazon EC2 작업](ec2-apis-intro.md))을 참조하세요.

**Topics**
+ [키 페어 생성 및 표시](create-save-key-pair.md)
+ [키 페어 삭제](delete-key-pairs.md)

# 키 페어 생성 및 표시
<a name="create-save-key-pair"></a>

이 예제에서는를 사용하여 키 페어를 AWS SDK for .NET 생성하는 방법을 보여줍니다. 애플리케이션은 새 키 페어의 이름과 PEM 파일(“.pem” 확장명)의 이름을 사용합니다. 키 페어를 생성하고 PEM 파일에 프라이빗 키를 쓴 다음 사용 가능한 모든 키 페어를 표시합니다. 명령줄 인수를 제공하지 않으면 애플리케이션은 사용 가능한 모든 키 페어만 표시합니다.

다음 섹션에서는 이 예제의 코드 조각을 제공합니다. [예제의 전체 코드](#create-save-key-pair-complete-code)는 그 뒤에 표시되며, 그대로 빌드하고 실행할 수 있습니다.

**Topics**
+ [키 페어 생성](#create-save-key-pair-create)
+ [사용 가능한 키 페어 표시](#create-save-key-pair-display)
+ [전체 코드](#create-save-key-pair-complete-code)
+ [추가 고려 사항](#create-save-key-pair-additional)

## 키 페어 생성
<a name="create-save-key-pair-create"></a>

다음 코드 조각은 키 페어를 생성한 다음 지정된 PEM 파일에 프라이빗 키를 저장합니다.

[이 주제의 끝 부분에 있는](#create-save-key-pair-complete-code) 예제에서는 사용 중인 이 코드 조각을 보여줍니다.

```
    //
    // Method to create a key pair and save the key material in a PEM file
    private static async Task CreateKeyPair(
      IAmazonEC2 ec2Client, string keyPairName, string pemFileName)
    {
      // Create the key pair
      CreateKeyPairResponse response =
        await ec2Client.CreateKeyPairAsync(new CreateKeyPairRequest{
          KeyName = keyPairName
        });
      Console.WriteLine($"\nCreated new key pair: {response.KeyPair.KeyName}");

      // Save the private key in a PEM file
      using (var s = new FileStream(pemFileName, FileMode.Create))
      using (var writer = new StreamWriter(s))
      {
        writer.WriteLine(response.KeyPair.KeyMaterial);
      }
    }
```

## 사용 가능한 키 페어 표시
<a name="create-save-key-pair-display"></a>

다음 코드 조각은 사용 가능한 키 페어의 목록을 표시합니다.

[이 주제의 끝 부분에 있는](#create-save-key-pair-complete-code) 예제에서는 사용 중인 이 코드 조각을 보여줍니다.

```
    //
    // Method to show the key pairs that are available
    private static async Task EnumerateKeyPairs(IAmazonEC2 ec2Client)
    {
      DescribeKeyPairsResponse response = await ec2Client.DescribeKeyPairsAsync();
      Console.WriteLine("Available key pairs:");
      foreach (KeyPairInfo item in response.KeyPairs)
        Console.WriteLine($"  {item.KeyName}");
    }
```

## 전체 코드
<a name="create-save-key-pair-complete-code"></a>

이 섹션에는 이 예제에 대한 관련 참조와 전체 코드가 나와 있습니다.

### SDK 레퍼런스
<a name="w2aac19c15c21c15c11c19b5b1"></a>

NuGet 패키지:
+ [AWSSDK.EC2](https://www.nuget.org/packages/AWSSDK.EC2)

프로그래밍 요소:
+ 네임스페이스 [Amazon.EC2](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/NEC2.html)

  클래스 [AmazonEC2Client](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TEC2Client.html)
+ 네임스페이스 [Amazon.EC2.Model](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/NEC2Model.html)

  클래스 [CreateKeyPairRequest](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TCreateKeyPairRequest.html)

  클래스 [CreateKeyPairResponse](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TCreateKeyPairResponse.html)

  클래스 [DescribeKeyPairsResponse](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TDescribeKeyPairsResponse.html)

  클래스 [KeyPairInfo](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TKeyPairInfo.html)

### 코드
<a name="w2aac19c15c21c15c11c19b7b1"></a>

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

namespace EC2CreateKeyPair
{
  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // Class to create and store a key pair
  class Program
  {
    static async Task Main(string[] args)
    {
      // Create the EC2 client
      var ec2Client = new AmazonEC2Client();

      // Parse the command line and show help if necessary
      var parsedArgs = CommandLine.Parse(args);
      if(parsedArgs.Count == 0)
      {
        // In the case of no command-line arguments,
        // just show help and the existing key pairs
        PrintHelp();
        Console.WriteLine("\nNo arguments specified.");
        Console.Write(
          "Do you want to see a list of the existing key pairs? ((y) or n): ");
        string response = Console.ReadLine();
        if((string.IsNullOrEmpty(response)) || (response.ToLower() == "y"))
          await EnumerateKeyPairs(ec2Client);
        return;
      }

      // Get the application arguments from the parsed list
      string keyPairName =
        CommandLine.GetArgument(parsedArgs, null, "-k", "--keypair-name");
      string pemFileName =
        CommandLine.GetArgument(parsedArgs, null, "-p", "--pem-filename");
      if(string.IsNullOrEmpty(keyPairName))
        CommandLine.ErrorExit("\nNo key pair name specified." +
          "\nRun the command with no arguments to see help.");
      if(string.IsNullOrEmpty(pemFileName) || !pemFileName.EndsWith(".pem"))
        CommandLine.ErrorExit("\nThe PEM filename is missing or incorrect." +
          "\nRun the command with no arguments to see help.");

      // Create the key pair
      await CreateKeyPair(ec2Client, keyPairName, pemFileName);
      await EnumerateKeyPairs(ec2Client);
    }


    //
    // Method to create a key pair and save the key material in a PEM file
    private static async Task CreateKeyPair(
      IAmazonEC2 ec2Client, string keyPairName, string pemFileName)
    {
      // Create the key pair
      CreateKeyPairResponse response =
        await ec2Client.CreateKeyPairAsync(new CreateKeyPairRequest{
          KeyName = keyPairName
        });
      Console.WriteLine($"\nCreated new key pair: {response.KeyPair.KeyName}");

      // Save the private key in a PEM file
      using (var s = new FileStream(pemFileName, FileMode.Create))
      using (var writer = new StreamWriter(s))
      {
        writer.WriteLine(response.KeyPair.KeyMaterial);
      }
    }


    //
    // Method to show the key pairs that are available
    private static async Task EnumerateKeyPairs(IAmazonEC2 ec2Client)
    {
      DescribeKeyPairsResponse response = await ec2Client.DescribeKeyPairsAsync();
      Console.WriteLine("Available key pairs:");
      foreach (KeyPairInfo item in response.KeyPairs)
        Console.WriteLine($"  {item.KeyName}");
    }


    //
    // Command-line help
    private static void PrintHelp()
    {
      Console.WriteLine(
        "\nUsage: EC2CreateKeyPair -k <keypair-name> -p <pem-filename>" +
        "\n  -k, --keypair-name: The name you want to assign to the key pair." +
        "\n  -p, --pem-filename: The name of the PEM file to create, with a \".pem\" extension.");
    }
  }


  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // 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="create-save-key-pair-additional"></a>
+ 예제를 실행한 후 [Amazon EC2 콘솔](https://console.aws.amazon.com/ec2/#KeyPairs)에서 새 키 페어를 확인할 수 있습니다.
+ 나중에 프라이빗 키를 검색할 수 없으므로 키 페어를 생성할 때는 반환되는 프라이빗 키를 저장해야 합니다.

# 키 페어 삭제
<a name="delete-key-pairs"></a>

이 예제에서는를 사용하여 키 페어 AWS SDK for .NET 를 삭제하는 방법을 보여줍니다. 이 애플리케이션은 키 페어 이름을 사용합니다. 키 페어를 삭제한 다음 사용 가능한 모든 키 페어를 표시합니다. 명령줄 인수를 제공하지 않으면 애플리케이션은 사용 가능한 모든 키 페어만 표시합니다.

다음 섹션에서는 이 예제의 코드 조각을 제공합니다. [예제의 전체 코드](#delete-key-pairs-complete-code)는 그 뒤에 표시되며, 그대로 빌드하고 실행할 수 있습니다.

**Topics**
+ [키 페어 삭제](#delete-key-pairs-create)
+ [사용 가능한 키 페어 표시](#delete-key-pairs-display)
+ [전체 코드](#delete-key-pairs-complete-code)

## 키 페어 삭제
<a name="delete-key-pairs-create"></a>

다음 코드 조각은 키 페어를 삭제합니다.

[이 주제의 끝 부분에 있는](#delete-key-pairs-complete-code) 예제에서는 사용 중인 이 코드 조각을 보여줍니다.

```
    //
    // Method to delete a key pair
    private static async Task DeleteKeyPair(IAmazonEC2 ec2Client, string keyName)
    {
      await ec2Client.DeleteKeyPairAsync(new DeleteKeyPairRequest{
        KeyName = keyName});
      Console.WriteLine($"\nKey pair {keyName} has been deleted (if it existed).");
    }
```

## 사용 가능한 키 페어 표시
<a name="delete-key-pairs-display"></a>

다음 코드 조각은 사용 가능한 키 페어의 목록을 표시합니다.

[이 주제의 끝 부분에 있는](#delete-key-pairs-complete-code) 예제에서는 사용 중인 이 코드 조각을 보여줍니다.

```
    //
    // Method to show the key pairs that are available
    private static async Task EnumerateKeyPairs(IAmazonEC2 ec2Client)
    {
      DescribeKeyPairsResponse response = await ec2Client.DescribeKeyPairsAsync();
      Console.WriteLine("Available key pairs:");
      foreach (KeyPairInfo item in response.KeyPairs)
        Console.WriteLine($"  {item.KeyName}");
    }
```

## 전체 코드
<a name="delete-key-pairs-complete-code"></a>

이 섹션에는 이 예제에 대한 관련 참조와 전체 코드가 나와 있습니다.

### SDK 레퍼런스
<a name="w2aac19c15c21c15c13c19b5b1"></a>

NuGet 패키지:
+ [AWSSDK.EC2](https://www.nuget.org/packages/AWSSDK.EC2)

프로그래밍 요소:
+ 네임스페이스 [Amazon.EC2](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/NEC2.html)

  클래스 [AmazonEC2Client](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TEC2Client.html)
+ 네임스페이스 [Amazon.EC2.Model](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/NEC2Model.html)

  클래스 [https://docs.aws.amazon.com/sdkfornet/v4/apidocs/](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/)

  클래스 [DescribeKeyPairsResponse](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TDescribeKeyPairsResponse.html)

  클래스 [KeyPairInfo](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TKeyPairInfo.html)

### 코드
<a name="w2aac19c15c21c15c13c19b7b1"></a>

```
using System;
using System.Threading.Tasks;
using Amazon.EC2;
using Amazon.EC2.Model;

namespace EC2DeleteKeyPair
{
  class Program
  {
    static async Task Main(string[] args)
    {
      // Create the EC2 client
      var ec2Client = new AmazonEC2Client();

      if(args.Length == 1)
      {
        // Delete a key pair (if it exists)
        await DeleteKeyPair(ec2Client, args[0]);

        // Display the key pairs that are left
        await EnumerateKeyPairs(ec2Client);
      }
      else
      {
        Console.WriteLine("\nUsage: EC2DeleteKeyPair keypair-name");
        Console.WriteLine("  keypair-name - The name of the key pair you want to delete.");
        Console.WriteLine("\nNo arguments specified.");
        Console.Write(
          "Do you want to see a list of the existing key pairs? ((y) or n): ");
        string response = Console.ReadLine();
        if((string.IsNullOrEmpty(response)) || (response.ToLower() == "y"))
          await EnumerateKeyPairs(ec2Client);
      }
    }


    //
    // Method to delete a key pair
    private static async Task DeleteKeyPair(IAmazonEC2 ec2Client, string keyName)
    {
      await ec2Client.DeleteKeyPairAsync(new DeleteKeyPairRequest{
        KeyName = keyName});
      Console.WriteLine($"\nKey pair {keyName} has been deleted (if it existed).");
    }


    //
    // Method to show the key pairs that are available
    private static async Task EnumerateKeyPairs(IAmazonEC2 ec2Client)
    {
      DescribeKeyPairsResponse response = await ec2Client.DescribeKeyPairsAsync();
      Console.WriteLine("Available key pairs:");
      foreach (KeyPairInfo item in response.KeyPairs)
        Console.WriteLine($"  {item.KeyName}");
    }
  }
}
```