セキュリティグループの更新 - AWS SDK for .NET

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

セキュリティグループの更新

この例では、 を使用してセキュリティグループにルール AWS SDK for .NET を追加する方法を示します。特にこの例では、特定の TCP ポートでインバウンドトラフィックを許可するルールを追加します。これは、EC2 インスタンスへのリモート接続などに使用できます。アプリケーションは、既存のセキュリティグループの ID、CIDR 形式の IP アドレス (またはアドレス範囲)、およびオプションで TCP ポート番号を取得します。アプリケーションは次に、指定されたセキュリティグループにインバウンドルールを追加します。

注記

この例を使用するには、CIDR 形式の IP アドレス (またはアドレス範囲) が必要です。お使いのローカルコンピュータの IP アドレスを取得する方法については、このトピックの最後にある追加の考慮事項を参照してください。

以下のセクションでは、この例のスニペットを確認できます。その下には、この例のコードの全文が示されており、そのままビルドして実行できます。

インバウンドルールの追加

次のスニペットでは、セキュリティグループに特定の IP アドレス (または範囲) および TCP ポートのインバウンドルールを追加します。

このトピックの最後で、スニペットが実際に使用されている例を確認できます。

// // 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}"); }

コード全文

このセクションでは、例に関連する参考資料とコードの全文を示します。

NuGet パッケージ:

プログラミング要素:

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); } } }

追加の考慮事項

  • ポート番号を指定しない場合、アプリケーションはデフォルトでポート 3389 を使用します。これは Windows RDP 用のポートで、Windows が動作している EC2 インスタンスに接続できるようになります。Linux が動作している EC2 インスタンスを起動する場合は、代わりに TCP ポート 22 (SSH) を使用できます。

  • 例では IpProtocol が「tcp」にセットされている点に注目してください。の値はIpProtocolIpPermission クラスの IpProtocolプロパティの説明にあります。

  • この例を使用する際に、お使いのローカルコンピュータの IP アドレスを確認する必要があるかもしれません。アドレスを取得する方法を以下にいくつか示します。

    • EC2 インスタンスに接続するローカルコンピュータが静的パブリック IP アドレスを持っている場合は、サービスを使用してそのアドレスを取得できます。サービスの一例としては http://checkip.amazonaws.com/ があります。インバウンドトラフィックの承認の詳細については、Amazon EC2 ユーザーガイド」またはAmazon EC2 ユーザーガイド」を参照してください。

    • ローカルコンピュータの IP アドレスを取得する別の方法として、Amazon EC2 コンソールを使用できます。

      いずれかのセキュリティグループを選択し、[Inbound rules] (インバウンドルール) タブをクリックして [Edit inbound rules] (インバウンドのルールの編集) を選択します。インバウンドルールで [Source] (送信元) 列にあるドロップダウンメニューを開き、[My IP] (マイ IP) を選択して、ローカルコンピュータの IP アドレスを CIDR 形式で表示します。必ず操作を [Cancel] (キャンセル) するようにしてください。

  • Amazon EC2 コンソールでセキュリティグループのリストを確認することにより、この例の結果を検証できます。