

La AWS SDK pour .NET V3 est passée en mode maintenance.

Nous vous recommandons de migrer vers la version [AWS SDK pour .NET V4](https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/welcome.html). Pour plus de détails et d'informations sur la façon de migrer, veuillez consulter notre [annonce relative au mode de maintenance](https://aws.amazon.com/blogs/developer/aws-sdk-for-net-v3-maintenance-mode-announcement/).

Les traductions sont fournies par des outils de traduction automatique. En cas de conflit entre le contenu d'une traduction et celui de la version originale en anglais, la version anglaise prévaudra.

# Travailler avec des groupes de sécurité dans Amazon EC2
<a name="security-groups"></a>

Dans Amazon EC2, un *groupe de sécurité* agit comme un pare-feu virtuel qui contrôle le trafic réseau pour une ou plusieurs instances EC2. Par défaut, EC2 associe vos instances à un groupe de sécurité qui n'autorise aucun trafic entrant. Vous pouvez créer un groupe de sécurité qui autorise vos instances EC2 à accepter un certain trafic. Par exemple, si vous devez vous connecter à une instance Windows EC2, vous devez configurer le groupe de sécurité afin d'autoriser le trafic RDP.

Pour en savoir plus sur les groupes de sécurité, consultez les groupes de [sécurité Amazon EC2 dans le guide](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-security-groups.html) de l'utilisateur [Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/).

**Avertissement**  
EC2-Classic a été retiré le 15 août 2022. Nous vous recommandons de migrer d'EC2-Classic vers un VPC. Pour plus d'informations, consultez le billet de blog [EC2-Classic Networking is Retiring — Here's How](https://aws.amazon.com/blogs/aws/ec2-classic-is-retiring-heres-how-to-prepare/) to Prepare.

Pour plus d'informations sur le APIs et les prérequis, consultez la section parent ([Utilisation avec Amazon EC2](ec2-apis-intro.md)).

**Topics**
+ [Énumération des groupes de sécurité](enumerate-security-groups.md)
+ [Création de groupes de sécurité](creating-security-group.md)
+ [Mise à jour des groupes de sécurité](authorize-ingress.md)

# Énumération des groupes de sécurité
<a name="enumerate-security-groups"></a>

Cet exemple montre comment utiliser le pour AWS SDK pour .NET énumérer les groupes de sécurité. Si vous fournissez un [Amazon Virtual Private Cloud](https://docs.aws.amazon.com/vpc/latest/userguide/) ID, l'application énumère les groupes de sécurité pour ce VPC en particulier. Dans le cas contraire, l'application affiche simplement la liste de tous les groupes de sécurité disponibles.

Les sections suivantes fournissent des extraits de cet exemple. Le [code complet de l'exemple](#enum-sec-groups-complete-code) est affiché ensuite et peut être créé et exécuté tel quel.

**Topics**
+ [Énumérer les groupes de sécurité](#enum-sec-groups-enum)
+ [Code complet](#enum-sec-groups-complete-code)
+ [Considérations supplémentaires](#enum-sec-groups-additional)

## Énumérer les groupes de sécurité
<a name="enum-sec-groups-enum"></a>

L'extrait suivant répertorie vos groupes de sécurité. Il énumère tous les groupes ou les groupes d'un VPC en particulier s'il en existe un.

L'exemple [à la fin de cette rubrique montre cet](#enum-sec-groups-complete-code) extrait de code en cours d'utilisation.

```
    //
    // Method to enumerate the security groups
    private static async Task EnumerateGroups(IAmazonEC2 ec2Client, string vpcID)
    {
      // A request object, in case we need it.
      var request = new DescribeSecurityGroupsRequest();

      // Put together the properties, if needed
      if(!string.IsNullOrEmpty(vpcID))
      {
        // We have a VPC ID. Find the security groups for just that VPC.
        Console.WriteLine($"\nGetting security groups for VPC {vpcID}...\n");
        request.Filters.Add(new Filter
        {
          Name = "vpc-id",
          Values = new List<string>() { vpcID }
        });
      }

      // Get the list of security groups
      DescribeSecurityGroupsResponse response =
        await ec2Client.DescribeSecurityGroupsAsync(request);

      // Display the list of security groups.
      foreach (SecurityGroup item in response.SecurityGroups)
      {
        Console.WriteLine("Security group: " + item.GroupId);
        Console.WriteLine("\tGroupId: " + item.GroupId);
        Console.WriteLine("\tGroupName: " + item.GroupName);
        Console.WriteLine("\tVpcId: " + item.VpcId);
        Console.WriteLine();
      }
    }
```

## Code complet
<a name="enum-sec-groups-complete-code"></a>

Cette section présente les références pertinentes et le code complet de cet exemple.

### Références du SDK
<a name="w2aac19c15c17c13c13c15b5b1"></a>

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

Éléments de programmation :
+ [Espace de noms Amazon.ec2](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/NEC2.html)

  Classe [Amazon EC2 Client](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TEC2Client.html)
+ [Espace de noms Amazon.ec2.model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/NEC2Model.html)

  Classe [DescribeSecurityGroupsRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TDescribeSecurityGroupsRequest.html)

  Classe [DescribeSecurityGroupsResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TDescribeSecurityGroupsResponse.html)

  [Filtre](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TFilter.html) de classe

  Classe [SecurityGroup](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TSecurityGroup.html)

### Le code
<a name="w2aac19c15c17c13c13c15b7b1"></a>

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

namespace EC2EnumerateSecGroups
{
  class Program
  {
    static async Task Main(string[] args)
    {
      // Parse the command line
       string vpcID = string.Empty;
      if(args.Length == 0)
      {
        Console.WriteLine("\nEC2EnumerateSecGroups [vpc_id]");
        Console.WriteLine("  vpc_id - The ID of the VPC for which you want to see security groups.");
        Console.WriteLine("\nSince you specified no arguments, showing all available security groups.");
      }
      else
      {
        vpcID = args[0];
      }

      if(vpcID.StartsWith("vpc-") || string.IsNullOrEmpty(vpcID))
      {
        // Create an EC2 client object
        var ec2Client = new AmazonEC2Client();

        // Enumerate the security groups
        await EnumerateGroups(ec2Client, vpcID);
      }
      else
      {
        Console.WriteLine("Could not find a valid VPC ID in the command-line arguments:");
        Console.WriteLine($"{args[0]}");
      }
    }


    //
    // Method to enumerate the security groups
    private static async Task EnumerateGroups(IAmazonEC2 ec2Client, string vpcID)
    {
      // A request object, in case we need it.
      var request = new DescribeSecurityGroupsRequest();

      // Put together the properties, if needed
      if(!string.IsNullOrEmpty(vpcID))
      {
        // We have a VPC ID. Find the security groups for just that VPC.
        Console.WriteLine($"\nGetting security groups for VPC {vpcID}...\n");
        request.Filters.Add(new Filter
        {
          Name = "vpc-id",
          Values = new List<string>() { vpcID }
        });
      }

      // Get the list of security groups
      DescribeSecurityGroupsResponse response =
        await ec2Client.DescribeSecurityGroupsAsync(request);

      // Display the list of security groups.
      foreach (SecurityGroup item in response.SecurityGroups)
      {
        Console.WriteLine("Security group: " + item.GroupId);
        Console.WriteLine("\tGroupId: " + item.GroupId);
        Console.WriteLine("\tGroupName: " + item.GroupName);
        Console.WriteLine("\tVpcId: " + item.VpcId);
        Console.WriteLine();
      }
    }
  }
}
```

## Considérations supplémentaires
<a name="enum-sec-groups-additional"></a>
+ Notez que dans le cas d'un VPC, le filtre est construit avec la `Name` partie de la paire nom-valeur définie sur « vpc-id ». Ce nom provient de la description de la `Filters` propriété de la [DescribeSecurityGroupsRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TDescribeSecurityGroupsRequest.html)classe.
+ Pour obtenir la liste complète de vos groupes de sécurité, vous pouvez également utiliser [ DescribeSecurityGroupsAsync sans paramètres](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/MEC2DescribeSecurityGroupsAsyncCancellationToken.html).
+ Vous pouvez vérifier les résultats en consultant la liste des groupes de sécurité dans la console [Amazon EC2.](https://console.aws.amazon.com/ec2/v2/home#SecurityGroups)

# Création de groupes de sécurité
<a name="creating-security-group"></a>

Cet exemple montre comment utiliser le AWS SDK pour .NET pour créer un groupe de sécurité. Vous pouvez fournir l'ID d'un VPC existant afin de créer un groupe de sécurité pour EC2 dans un VPC. Si vous ne fournissez pas un tel identifiant, le nouveau groupe de sécurité sera destiné à EC2-Classic si votre AWS compte le permet.

Si vous ne fournissez pas d'identifiant VPC et que votre AWS compte ne prend pas en charge EC2-Classic, le nouveau groupe de sécurité appartiendra au VPC par défaut de votre compte.

**Avertissement**  
EC2-Classic a été retiré le 15 août 2022. Nous vous recommandons de migrer d'EC2-Classic vers un VPC. Pour plus d'informations, consultez le billet de blog [EC2-Classic Networking is Retiring — Here's How](https://aws.amazon.com/blogs/aws/ec2-classic-is-retiring-heres-how-to-prepare/) to Prepare.

Les sections suivantes fournissent des extraits de cet exemple. Le [code complet de l'exemple](#create-sec-groups-complete-code) est affiché ensuite et peut être créé et exécuté tel quel.

**Topics**
+ [Rechercher des groupes de sécurité existants](#create-sec-groups-find)
+ [Création d’un groupe de sécurité](#create-sec-groups-enum)
+ [Code complet](#create-sec-groups-complete-code)

## Rechercher des groupes de sécurité existants
<a name="create-sec-groups-find"></a>

L'extrait suivant recherche les groupes de sécurité existants portant le nom donné dans le VPC donné.

L'exemple [à la fin de cette rubrique montre cet](#create-sec-groups-complete-code) extrait de code en cours d'utilisation.

```
    //
    // Method to determine if a security group with the specified name
    // already exists in the VPC
    private static async Task<List<SecurityGroup>> FindSecurityGroups(
      IAmazonEC2 ec2Client, string groupName, string vpcID)
    {
      var request = new DescribeSecurityGroupsRequest();
      request.Filters.Add(new Filter{
        Name = "group-name",
        Values = new List<string>() { groupName }
      });
      if(!string.IsNullOrEmpty(vpcID))
        request.Filters.Add(new Filter{
          Name = "vpc-id",
          Values = new List<string>() { vpcID }
        });

      var response = await ec2Client.DescribeSecurityGroupsAsync(request);
      return response.SecurityGroups;
    }
```

## Création d’un groupe de sécurité
<a name="create-sec-groups-enum"></a>

L'extrait suivant crée un nouveau groupe de sécurité si aucun groupe portant ce nom n'existe dans le VPC donné. Si aucun VPC n'est indiqué et qu'un ou plusieurs groupes portant ce nom existent, l'extrait renvoie simplement la liste des groupes.

L'exemple [à la fin de cette rubrique montre cet](#create-sec-groups-complete-code) extrait de code en cours d'utilisation.

```
    //
    // Method to create a new security group (either EC2-Classic or EC2-VPC)
    // If vpcID is empty, the security group will be for EC2-Classic
    private static async Task<List<SecurityGroup>> CreateSecurityGroup(
      IAmazonEC2 ec2Client, string groupName, string vpcID)
    {
      // See if one or more security groups with that name
      // already exist in the given VPC. If so, return the list of them.
      var securityGroups = await FindSecurityGroups(ec2Client, groupName, vpcID);
      if (securityGroups.Count > 0)
      {
        Console.WriteLine(
          $"\nOne or more security groups with name {groupName} already exist.\n");
        return securityGroups;
      }

      // If the security group doesn't already exists, create it.
      var createRequest = new CreateSecurityGroupRequest{
        GroupName = groupName
      };
      if(string.IsNullOrEmpty(vpcID))
      {
        createRequest.Description = "My .NET example security group for EC2-Classic";
      }
      else
      {
        createRequest.VpcId = vpcID;
        createRequest.Description = "My .NET example security group for EC2-VPC";
      }
      CreateSecurityGroupResponse createResponse =
        await ec2Client.CreateSecurityGroupAsync(createRequest);

      // Return the new security group
      DescribeSecurityGroupsResponse describeResponse =
        await ec2Client.DescribeSecurityGroupsAsync(new DescribeSecurityGroupsRequest{
          GroupIds = new List<string>() { createResponse.GroupId }
        });
      return describeResponse.SecurityGroups;
    }
```

## Code complet
<a name="create-sec-groups-complete-code"></a>

Cette section présente les références pertinentes et le code complet de cet exemple.

### Références du SDK
<a name="w2aac19c15c17c13c15c23b5b1"></a>

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

Éléments de programmation :
+ [Espace de noms Amazon.ec2](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/NEC2.html)

  Classe [Amazon EC2 Client](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TEC2Client.html)
+ [Espace de noms Amazon.ec2.model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/NEC2Model.html)

  Classe [CreateSecurityGroupRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TCreateSecurityGroupRequest.html)

  Classe [CreateSecurityGroupResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TCreateSecurityGroupResponse.html)

  Classe [DescribeSecurityGroupsRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TDescribeSecurityGroupsRequest.html)

  Classe [DescribeSecurityGroupsResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TDescribeSecurityGroupsResponse.html)

  [Filtre](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TFilter.html) de classe

  Classe [SecurityGroup](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TSecurityGroup.html)

### Le code
<a name="w2aac19c15c17c13c15c23b7b1"></a>

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

namespace EC2CreateSecGroup
{
  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // Class to create a security group
  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)
      {
        PrintHelp();
        return;
      }
      if(parsedArgs.Count > MaxArgs)
        CommandLine.ErrorExit("\nThe number of command-line arguments is incorrect." +
          "\nRun the command with no arguments to see help.");

      // Get the application arguments from the parsed list
      var groupName = CommandLine.GetArgument(parsedArgs, null, "-g", "--group-name");
      var vpcID = CommandLine.GetArgument(parsedArgs, null, "-v", "--vpc-id");
      if(string.IsNullOrEmpty(groupName))
        CommandLine.ErrorExit("\nYou must supply a name for the new group." +
          "\nRun the command with no arguments to see help.");
      if(!string.IsNullOrEmpty(vpcID) && !vpcID.StartsWith("vpc-"))
        CommandLine.ErrorExit($"\nNot a valid VPC ID: {vpcID}");

      // groupName has a value and vpcID either has a value or is null (which is fine)
      // Create the new security group and display information about it
      var securityGroups =
        await CreateSecurityGroup(new AmazonEC2Client(), groupName, vpcID);
      Console.WriteLine("Information about the security group(s):");
      foreach(var group in securityGroups)
      {
        Console.WriteLine($"\nGroupName: {group.GroupName}");
        Console.WriteLine($"GroupId: {group.GroupId}");
        Console.WriteLine($"Description: {group.Description}");
        Console.WriteLine($"VpcId (if any): {group.VpcId}");
      }
    }


    //
    // Method to create a new security group (either EC2-Classic or EC2-VPC)
    // If vpcID is empty, the security group will be for EC2-Classic
    private static async Task<List<SecurityGroup>> CreateSecurityGroup(
      IAmazonEC2 ec2Client, string groupName, string vpcID)
    {
      // See if one or more security groups with that name
      // already exist in the given VPC. If so, return the list of them.
      var securityGroups = await FindSecurityGroups(ec2Client, groupName, vpcID);
      if (securityGroups.Count > 0)
      {
        Console.WriteLine(
          $"\nOne or more security groups with name {groupName} already exist.\n");
        return securityGroups;
      }

      // If the security group doesn't already exists, create it.
      var createRequest = new CreateSecurityGroupRequest{
        GroupName = groupName
      };
      if(string.IsNullOrEmpty(vpcID))
      {
        createRequest.Description = "Security group for .NET code example (no VPC specified)";
      }
      else
      {
        createRequest.VpcId = vpcID;
        createRequest.Description = "Security group for .NET code example (VPC: " + vpcID + ")";
      }
      CreateSecurityGroupResponse createResponse =
        await ec2Client.CreateSecurityGroupAsync(createRequest);

      // Return the new security group
      DescribeSecurityGroupsResponse describeResponse =
        await ec2Client.DescribeSecurityGroupsAsync(new DescribeSecurityGroupsRequest{
          GroupIds = new List<string>() { createResponse.GroupId }
        });
      return describeResponse.SecurityGroups;
    }


    //
    // Method to determine if a security group with the specified name
    // already exists in the VPC
    private static async Task<List<SecurityGroup>> FindSecurityGroups(
      IAmazonEC2 ec2Client, string groupName, string vpcID)
    {
      var request = new DescribeSecurityGroupsRequest();
      request.Filters.Add(new Filter{
        Name = "group-name",
        Values = new List<string>() { groupName }
      });
      if(!string.IsNullOrEmpty(vpcID))
        request.Filters.Add(new Filter{
          Name = "vpc-id",
          Values = new List<string>() { vpcID }
        });

      var response = await ec2Client.DescribeSecurityGroupsAsync(request);
      return response.SecurityGroups;
    }


    //
    // Command-line help
    private static void PrintHelp()
    {
      Console.WriteLine(
        "\nUsage: EC2CreateSecGroup -g <group-name> [-v <vpc-id>]" +
        "\n  -g, --group-name: The name you would like the new security group to have." +
        "\n  -v, --vpc-id: The ID of a VPC to which the new security group will belong." +
        "\n     If vpc-id isn't present, the security group will be" +
        "\n     for EC2-Classic (if your AWS account supports this)" +
        "\n     or will use the default VCP for EC2-VPC.");
    }
  }


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

}
```

# Mise à jour des groupes de sécurité
<a name="authorize-ingress"></a>

Cet exemple montre comment utiliser le pour AWS SDK pour .NET ajouter une règle à un groupe de sécurité. En particulier, l'exemple ajoute une règle pour autoriser le trafic entrant sur un port TCP donné, qui peut être utilisée, par exemple, pour les connexions à distance à une instance EC2. L'application prend l'identifiant d'un groupe de sécurité existant, une adresse IP (ou plage d'adresses) au format CIDR et éventuellement un numéro de port TCP. Il ajoute ensuite une règle entrante au groupe de sécurité donné.

**Note**  
Pour utiliser cet exemple, vous avez besoin d'une adresse IP (ou d'une plage d'adresses) au format CIDR. Consultez la section **Considérations supplémentaires** à la fin de cette rubrique pour connaître les méthodes permettant d'obtenir l'adresse IP de votre ordinateur local.

Les sections suivantes fournissent des extraits de cet exemple. Le [code complet de l'exemple](#authorize-ingress-complete-code) est affiché ensuite et peut être créé et exécuté tel quel.

**Topics**
+ [Ajouter une règle de trafic entrant](#authorize-ingress-add-rule)
+ [Code complet](#authorize-ingress-complete-code)
+ [Considérations supplémentaires](#authorize-ingress-additional)

## Ajouter une règle de trafic entrant
<a name="authorize-ingress-add-rule"></a>

L'extrait suivant ajoute une règle entrante à un groupe de sécurité pour une adresse IP (ou plage) et un port TCP particuliers.

L'exemple [à la fin de cette rubrique montre cet](#authorize-ingress-complete-code) extrait de code en cours d'utilisation.

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

## Code complet
<a name="authorize-ingress-complete-code"></a>

Cette section présente les références pertinentes et le code complet de cet exemple.

### Références du SDK
<a name="w2aac19c15c17c13c17c17b5b1"></a>

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

Éléments de programmation :
+ [Espace de noms Amazon.ec2](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/NEC2.html)

  Classe [Amazon EC2 Client](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TEC2Client.html)
+ [Espace de noms Amazon.ec2.model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/NEC2Model.html)

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

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

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

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

### Le code
<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);
    }
  }

}
```

## Considérations supplémentaires
<a name="authorize-ingress-additional"></a>
+ Si vous ne fournissez pas de numéro de port, l'application utilise par défaut le port 3389. Il s'agit du port pour Windows RDP, qui vous permet de vous connecter à une instance EC2 exécutant Windows. Si vous lancez une instance EC2 exécutant Linux, vous pouvez utiliser le port TCP 22 (SSH) à la place.
+ Notez que l'exemple prend la valeur `IpProtocol` « tcp ». Les valeurs de se `IpProtocol` trouvent dans la description de la `IpProtocol` propriété de la [IpPermission](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TIpPermission.html)classe.
+ Vous aurez peut-être besoin de l'adresse IP de votre ordinateur local lorsque vous utiliserez cet exemple. Voici certains des moyens par lesquels vous pouvez obtenir l'adresse.
  + Si votre ordinateur local (à partir duquel vous allez vous connecter à votre instance EC2) possède une adresse IP publique statique, vous pouvez utiliser un service pour obtenir cette adresse. L'un de ces services est [http://checkip.amazonaws.com/](http://checkip.amazonaws.com/). Pour en savoir plus sur l'autorisation du trafic entrant, consultez les sections [Ajouter des règles à un groupe de sécurité et Règles de groupe](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/working-with-security-groups.html#adding-security-group-rule) [de sécurité pour différents cas d'utilisation](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/security-group-rules-reference.html) dans le guide de l'utilisateur [Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/).
  + Une autre méthode pour obtenir l'adresse IP de votre ordinateur local consiste à utiliser la console [Amazon EC2](https://console.aws.amazon.com/ec2/v2/home#SecurityGroups).

    Sélectionnez l'un de vos groupes de sécurité, sélectionnez l'onglet **Règles entrantes**, puis choisissez **Modifier les règles entrantes**. Dans une règle entrante, ouvrez le menu déroulant dans la colonne **Source** et choisissez **Mon adresse IP** pour voir l'adresse IP de votre ordinateur local au format CIDR. Assurez-vous d'**annuler** l'opération.
+ Vous pouvez vérifier les résultats de cet exemple en examinant la liste des groupes de sécurité dans la console [Amazon EC2](https://console.aws.amazon.com/ec2/v2/home#SecurityGroups).