

 AWS SDK for .NET V3가 유지 관리 모드로 전환되었습니다.

[AWS SDK for .NET V4](https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/welcome.html)로 마이그레이션하는 것이 좋습니다. 마이그레이션 방법에 대한 자세한 내용과 정보는 [유지 관리 모드 공지](https://aws.amazon.com/blogs/developer/aws-sdk-for-net-v3-maintenance-mode-announcement/)를 참조하세요.

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

# 보안 그룹 업데이트
<a name="authorize-ingress"></a>

이 예제에서는 AWS SDK for .NET 를 사용하여 보안 그룹에 규칙을 추가하는 방법을 보여줍니다. 특히 이 예제에서는 지정된 TCP 포트에서 인바운드 트래픽을 허용하는 규칙을 추가합니다. 이 규칙은 예를 들어 EC2 인스턴스에 대한 원격 연결에 사용할 수 있습니다. 애플리케이션은 기존 보안 그룹의 ID, CIDR 형식의 IP 주소(또는 주소 범위), 그리고 선택적으로 TCP 포트 번호를 사용합니다. 그런 다음 지정된 보안 그룹에 인바운드 규칙을 추가합니다.

**참고**  
이 예제를 사용하려면 CIDR 형식의 IP 주소(또는 주소 범위)가 필요합니다. 로컬 컴퓨터의 IP 주소를 얻는 방법은 이 주제의 끝 부분에 있는 **추가 고려 사항**을 참조하세요.

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

**Topics**
+ [인바운드 규칙 추가](#authorize-ingress-add-rule)
+ [전체 코드](#authorize-ingress-complete-code)
+ [추가 고려 사항](#authorize-ingress-additional)

## 인바운드 규칙 추가
<a name="authorize-ingress-add-rule"></a>

다음 코드 조각은 특정 IP 주소(또는 범위) 및 TCP 포트에 대한 보안 그룹에 인바운드 규칙을 추가합니다.

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

```
    //
    // Method that adds a TCP ingress rule to a security group
    private static async Task AddIngressRule(
      IAmazonEC2 eC2Client, string groupID, string ipAddress, int port)
    {
      // Create an object to hold the request information for the rule.
      // It uses an IpPermission object to hold the IP information for the rule.
      var ingressRequest = new AuthorizeSecurityGroupIngressRequest{
        GroupId = groupID};
      ingressRequest.IpPermissions.Add(new IpPermission{
        IpProtocol = "tcp",
        FromPort = port,
        ToPort = port,
        Ipv4Ranges = new List<IpRange>() { new IpRange { CidrIp = ipAddress } }
      });

      // Create the inbound rule for the security group
      AuthorizeSecurityGroupIngressResponse responseIngress =
        await eC2Client.AuthorizeSecurityGroupIngressAsync(ingressRequest);
      Console.WriteLine($"\nNew RDP rule was written in {groupID} for {ipAddress}.");
      Console.WriteLine($"Result: {responseIngress.HttpStatusCode}");
    }
```

## 전체 코드
<a name="authorize-ingress-complete-code"></a>

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

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

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

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

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

  클래스 [AuthorizeSecurityGroupIngressRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TAuthorizeSecurityGroupIngressRequest.html)

  클래스 [AuthorizeSecurityGroupIngressResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TAuthorizeSecurityGroupIngressResponse.html)

  클래스 [IpPermission](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TIpPermission.html)

  클래스 [IpRange](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TIpRange.html)

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

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

namespace EC2AddRuleForRDP
{
  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // Class to add a rule that allows inbound traffic on TCP a port
  class Program
  {
    private const int DefaultPort = 3389;

    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
      var groupID = CommandLine.GetArgument(parsedArgs, null, "-g", "--group-id");
      var ipAddress = CommandLine.GetArgument(parsedArgs, null, "-i", "--ip-address");
      var portStr = CommandLine.GetArgument(parsedArgs, DefaultPort.ToString(), "-p", "--port");
      if(string.IsNullOrEmpty(ipAddress))
        CommandLine.ErrorExit("\nYou must supply an IP address in CIDR format.");
      if(string.IsNullOrEmpty(groupID) || !groupID.StartsWith("sg-"))
        CommandLine.ErrorExit("\nThe ID for a security group is missing or incorrect.");
      if(int.Parse(portStr) == 0)
        CommandLine.ErrorExit($"\nThe given TCP port number, {portStr}, isn't allowed.");

      // Add a rule to the given security group that allows
      // inbound traffic on a TCP port
      await AddIngressRule(
        new AmazonEC2Client(), groupID, ipAddress, int.Parse(portStr));
    }


    //
    // Method that adds a TCP ingress rule to a security group
    private static async Task AddIngressRule(
      IAmazonEC2 eC2Client, string groupID, string ipAddress, int port)
    {
      // Create an object to hold the request information for the rule.
      // It uses an IpPermission object to hold the IP information for the rule.
      var ingressRequest = new AuthorizeSecurityGroupIngressRequest{
        GroupId = groupID};
      ingressRequest.IpPermissions.Add(new IpPermission{
        IpProtocol = "tcp",
        FromPort = port,
        ToPort = port,
        Ipv4Ranges = new List<IpRange>() { new IpRange { CidrIp = ipAddress } }
      });

      // Create the inbound rule for the security group
      AuthorizeSecurityGroupIngressResponse responseIngress =
        await eC2Client.AuthorizeSecurityGroupIngressAsync(ingressRequest);
      Console.WriteLine($"\nNew RDP rule was written in {groupID} for {ipAddress}.");
      Console.WriteLine($"Result: {responseIngress.HttpStatusCode}");
    }


    //
    // Command-line help
    private static void PrintHelp()
    {
      Console.WriteLine(
        "\nUsage: EC2AddRuleForRDP -g <group-id> -i <ip-address> [-p <port>]" +
        "\n  -g, --group-id: The ID of the security group to which you want to add the inbound rule." +
        "\n  -i, --ip-address: An IP address or address range in CIDR format." +
        "\n  -p, --port: The TCP port number. Defaults to 3389.");
    }
  }


  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // 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="authorize-ingress-additional"></a>
+ 포트 번호를 제공하지 않는 경우 애플리케이션은 기본적으로 포트 3389로 설정됩니다. 이 포트는 Windows RDP용 포트로, Windows를 실행하는 EC2 인스턴스에 연결할 수 있습니다. Linux를 실행하는 EC2 인스턴스를 시작하는 경우에는 그 대신에 TCP 포트 22(SSH)를 사용하세요.
+ 참고로 이 예제에서는 `IpProtocol`이 “tcp”로 설정되어 있습니다. `IpProtocol`의 값은 [IpPermission](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TIpPermission.html) 클래스의 `IpProtocol` 속성에 대한 설명에서 찾을 수 있습니다.
+ 이 예를 사용할 때 로컬 컴퓨터의 IP 주소가 필요할 수 있습니다. 주소를 확인할 수 있는 몇 가지 방법은 다음과 같습니다.
  + EC2 인스턴스에 연결할 로컬 컴퓨터에 정적 퍼블릭 IP 주소가 있는 경우 서비스를 사용하여 해당 주소를 가져올 수 있습니다. 이러한 서비스 중 하나가 [http://checkip.amazonaws.com/](http://checkip.amazonaws.com/)입니다. 인바운드 트래픽 권한 부여에 대한 자세한 내용은 [Amazon EC2 사용 설명서](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/)의 [보안 그룹에 규칙 추가](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/working-with-security-groups.html#adding-security-group-rule) 및 [다양한 사용 사례에 대한 보안 그룹 규칙](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/security-group-rules-reference.html)을 참조하세요.
  + 로컬 컴퓨터의 IP 주소를 얻는 또 다른 방법은 [Amazon EC2 콘솔](https://console.aws.amazon.com/ec2/v2/home#SecurityGroups)을 사용하는 것입니다.

    보안 그룹 중 하나를 선택하고 **인바운드 규칙** 탭을 선택한 다음 **인바운드 규칙 편집**을 선택합니다. 인바운드 규칙에서 **소스** 열의 드롭다운 메뉴를 열고 **내 IP**를 선택하면 로컬 컴퓨터의 IP 주소가 CIDR 형식으로 표시됩니다. 작업을 **취소**해야 합니다.
+ [Amazon EC2 콘솔](https://console.aws.amazon.com/ec2/v2/home#SecurityGroups)에서 보안 그룹 목록을 검사하여 이 예제의 결과를 확인할 수 있습니다.