Lancement d'une instance Amazon EC2 - AWS SDK for .NET

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.

Lancement d'une instance Amazon EC2

Cet exemple vous montre comment utiliser le AWS SDK for .NET pour lancer une ou plusieurs instances Amazon EC2 configurées de manière identique à partir de la même Amazon Machine Image (AMI). À l'aide de plusieurs entrées que vous fournissez, l'application lance une instance EC2, puis surveille l'instance jusqu'à ce qu'elle sorte de l'état « En attente ».

Lorsque votre instance EC2 est en cours d'exécution, vous pouvez vous y connecter à distance, comme décrit dans(facultatif) Connectez-vous à l'instance.

Vous pouvez lancer une instance EC2 dans un VPC ou dans EC2-Classic (si AWS votre compte le permet). Pour plus d'informations sur l'EC2 dans un VPC par rapport à EC2-Classic, consultez le guide de l'utilisateur Amazon EC2 ou le guide de l'utilisateur Amazon EC2.

Avertissement

Nous retirons EC2-Classic le 15 août 2022. Nous vous recommandons de migrer d'EC2-Classic vers un VPC. Pour plus d'informations, consultez la section Migrer d'EC2-Classic vers un VPC dans le guide de l'utilisateur Amazon EC2 ou le guide de l'utilisateur Amazon EC2. Consultez également le billet de blog EC2-Classic Networking is Retiring – Here's How to Prepare (Se préparer au retrait de la mise en réseau EC2-Classic).

Les sections suivantes fournissent des extraits et d'autres informations pour cet exemple. Le code complet de l'exemple est affiché après les extraits et peut être créé et exécuté tel quel.

Rassemblez ce dont vous avez besoin

Pour lancer une instance EC2, vous aurez besoin de plusieurs éléments.

  • Un VPC dans lequel l'instance sera lancée. S'il s'agit d'une instance Windows et que vous vous y connectez via RDP, le VPC aura probablement besoin d'une passerelle Internet attachée, ainsi que d'une entrée pour la passerelle Internet dans la table de routage. Pour plus d’informations, consultez Passerelles Internet dans le Guide de l’utilisateur Amazon VPC.

  • L'ID d'un sous-réseau existant dans le VPC où l'instance sera lancée. Pour le trouver ou le créer facilement, vous pouvez vous connecter à la console Amazon VPC, mais vous pouvez également l'obtenir par programmation en utilisant les méthodes et. CreateSubnetAsyncDescribeSubnetsAsync

    Note

    Si votre AWS compte prend en charge EC2-Classic et que c'est le type d'instance que vous souhaitez lancer, ce paramètre n'est pas obligatoire. Toutefois, si votre compte ne prend pas en charge EC2-Classic et que vous ne fournissez pas ce paramètre, la nouvelle instance est lancée dans le VPC par défaut de votre compte.

  • Si vous souhaitez vous connecter à la nouvelle instance, le groupe de sécurité mentionné précédemment doit disposer d'une règle entrante appropriée autorisant le trafic SSH sur le port 22 (instance Linux) ou le trafic RDP sur le port 3389 (instance Windows). Pour plus d'informations sur la procédure à suivreMise à jour des groupes de sécurité, voir Considérations supplémentaires notamment la fin de cette rubrique.

  • Nom du fichier PEM qui contient la clé privée de la paire de clés EC2 mentionnée précédemment. Le fichier PEM est utilisé lorsque vous vous connectez à distance à l'instance.

Lancer une instance

L'extrait de code suivant lance une instance EC2.

L'exemple situé à la fin de cette rubrique montre cet extrait en cours d'utilisation.

// // Method to launch the instances // Returns a list with the launched instance IDs private static async Task<List<string>> LaunchInstances( IAmazonEC2 ec2Client, RunInstancesRequest requestLaunch) { var instanceIds = new List<string>(); RunInstancesResponse responseLaunch = await ec2Client.RunInstancesAsync(requestLaunch); Console.WriteLine("\nNew instances have been created."); foreach (Instance item in responseLaunch.Reservation.Instances) { instanceIds.Add(item.InstanceId); Console.WriteLine($" New instance: {item.InstanceId}"); } return instanceIds; }

Surveiller l'instance

L'extrait de code suivant surveille l'instance jusqu'à ce qu'elle sorte de l'état « En attente ».

L'exemple situé à la fin de cette rubrique montre cet extrait en cours d'utilisation.

Consultez la InstanceStateclasse pour connaître les valeurs valides de la Instance.State.Code propriété.

// // Method to wait until the instances are running (or at least not pending) private static async Task CheckState(IAmazonEC2 ec2Client, List<string> instanceIds) { Console.WriteLine( "\nWaiting for the instances to start." + "\nPress any key to stop waiting. (Response might be slightly delayed.)"); int numberRunning; DescribeInstancesResponse responseDescribe; var requestDescribe = new DescribeInstancesRequest{ InstanceIds = instanceIds}; // Check every couple of seconds int wait = 2000; while(true) { // Get and check the status for each of the instances to see if it's past pending. // Once all instances are past pending, break out. // (For this example, we are assuming that there is only one reservation.) Console.Write("."); numberRunning = 0; responseDescribe = await ec2Client.DescribeInstancesAsync(requestDescribe); foreach(Instance i in responseDescribe.Reservations[0].Instances) { // Check the lower byte of State.Code property // Code == 0 is the pending state if((i.State.Code & 255) > 0) numberRunning++; } if(numberRunning == responseDescribe.Reservations[0].Instances.Count) break; // Wait a bit and try again (unless the user wants to stop waiting) Thread.Sleep(wait); if(Console.KeyAvailable) break; } Console.WriteLine("\nNo more instances are pending."); foreach(Instance i in responseDescribe.Reservations[0].Instances) { Console.WriteLine($"For {i.InstanceId}:"); Console.WriteLine($" VPC ID: {i.VpcId}"); Console.WriteLine($" Instance state: {i.State.Name}"); Console.WriteLine($" Public IP address: {i.PublicIpAddress}"); Console.WriteLine($" Public DNS name: {i.PublicDnsName}"); Console.WriteLine($" Key pair name: {i.KeyName}"); } }

Code complet

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

using System; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Amazon.EC2; using Amazon.EC2.Model; namespace EC2LaunchInstance { // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = // Class to launch an EC2 instance 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 groupID = CommandLine.GetArgument(parsedArgs, null, "-g", "--group-id"); string ami = CommandLine.GetArgument(parsedArgs, null, "-a", "--ami-id"); string keyPairName = CommandLine.GetArgument(parsedArgs, null, "-k", "--keypair-name"); string subnetID = CommandLine.GetArgument(parsedArgs, null, "-s", "--subnet-id"); if( (string.IsNullOrEmpty(groupID) || !groupID.StartsWith("sg-")) || (string.IsNullOrEmpty(ami) || !ami.StartsWith("ami-")) || (string.IsNullOrEmpty(keyPairName)) || (!string.IsNullOrEmpty(subnetID) && !subnetID.StartsWith("subnet-"))) CommandLine.ErrorExit( "\nOne or more of the required arguments is missing or incorrect." + "\nRun the command with no arguments to see help."); // Create an EC2 client var ec2Client = new AmazonEC2Client(); // Create an object with the necessary properties RunInstancesRequest request = GetRequestData(groupID, ami, keyPairName, subnetID); // Launch the instances and wait for them to start running var instanceIds = await LaunchInstances(ec2Client, request); await CheckState(ec2Client, instanceIds); } // // Method to put together the properties needed to launch the instance. private static RunInstancesRequest GetRequestData( string groupID, string ami, string keyPairName, string subnetID) { // Common properties var groupIDs = new List<string>() { groupID }; var request = new RunInstancesRequest() { // The first three of these would be additional command-line arguments or similar. InstanceType = InstanceType.T1Micro, MinCount = 1, MaxCount = 1, ImageId = ami, KeyName = keyPairName }; // Properties specifically for EC2 in a VPC. if(!string.IsNullOrEmpty(subnetID)) { request.NetworkInterfaces = new List<InstanceNetworkInterfaceSpecification>() { new InstanceNetworkInterfaceSpecification() { DeviceIndex = 0, SubnetId = subnetID, Groups = groupIDs, AssociatePublicIpAddress = true } }; } // Properties specifically for EC2-Classic else { request.SecurityGroupIds = groupIDs; } return request; } // // Method to launch the instances // Returns a list with the launched instance IDs private static async Task<List<string>> LaunchInstances( IAmazonEC2 ec2Client, RunInstancesRequest requestLaunch) { var instanceIds = new List<string>(); RunInstancesResponse responseLaunch = await ec2Client.RunInstancesAsync(requestLaunch); Console.WriteLine("\nNew instances have been created."); foreach (Instance item in responseLaunch.Reservation.Instances) { instanceIds.Add(item.InstanceId); Console.WriteLine($" New instance: {item.InstanceId}"); } return instanceIds; } // // Method to wait until the instances are running (or at least not pending) private static async Task CheckState(IAmazonEC2 ec2Client, List<string> instanceIds) { Console.WriteLine( "\nWaiting for the instances to start." + "\nPress any key to stop waiting. (Response might be slightly delayed.)"); int numberRunning; DescribeInstancesResponse responseDescribe; var requestDescribe = new DescribeInstancesRequest{ InstanceIds = instanceIds}; // Check every couple of seconds int wait = 2000; while(true) { // Get and check the status for each of the instances to see if it's past pending. // Once all instances are past pending, break out. // (For this example, we are assuming that there is only one reservation.) Console.Write("."); numberRunning = 0; responseDescribe = await ec2Client.DescribeInstancesAsync(requestDescribe); foreach(Instance i in responseDescribe.Reservations[0].Instances) { // Check the lower byte of State.Code property // Code == 0 is the pending state if((i.State.Code & 255) > 0) numberRunning++; } if(numberRunning == responseDescribe.Reservations[0].Instances.Count) break; // Wait a bit and try again (unless the user wants to stop waiting) Thread.Sleep(wait); if(Console.KeyAvailable) break; } Console.WriteLine("\nNo more instances are pending."); foreach(Instance i in responseDescribe.Reservations[0].Instances) { Console.WriteLine($"For {i.InstanceId}:"); Console.WriteLine($" VPC ID: {i.VpcId}"); Console.WriteLine($" Instance state: {i.State.Name}"); Console.WriteLine($" Public IP address: {i.PublicIpAddress}"); Console.WriteLine($" Public DNS name: {i.PublicDnsName}"); Console.WriteLine($" Key pair name: {i.KeyName}"); } } // // Command-line help private static void PrintHelp() { Console.WriteLine( "\nUsage: EC2LaunchInstance -g <group-id> -a <ami-id> -k <keypair-name> [-s <subnet-id>]" + "\n -g, --group-id: The ID of the security group." + "\n -a, --ami-id: The ID of an Amazon Machine Image." + "\n -k, --keypair-name - The name of a key pair." + "\n -s, --subnet-id: The ID of a subnet. Required only for EC2 in a 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); } } }

Considérations supplémentaires

  • Lorsque vous vérifiez l'état d'une instance EC2, vous pouvez ajouter un filtre à la Filter propriété de l'DescribeInstancesRequestobjet. Grâce à cette technique, vous pouvez limiter la demande à certaines instances, par exemple les instances dotées d'une balise spécifique spécifiée par l'utilisateur.

  • Par souci de concision, des valeurs typiques ont été attribuées à certaines propriétés. L'une ou l'ensemble de ces propriétés peuvent plutôt être déterminées par programmation ou par saisie par l'utilisateur.

  • Les valeurs que vous pouvez utiliser pour les MaxCount propriétés MinCount et de l'RunInstancesRequestobjet sont déterminées par la zone de disponibilité cible et le nombre maximum d'instances autorisées pour le type d'instance. Pour plus d'informations, consultez la section Combien d'instances puis-je exécuter dans Amazon EC2 dans la FAQ générale d'Amazon EC2.

  • Si vous souhaitez utiliser un type d'instance différent de celui de cet exemple, vous pouvez choisir parmi plusieurs types d'instance, que vous pouvez consulter dans le guide de l'utilisateur Amazon EC2 ou le guide de l'utilisateur Amazon EC2.

  • Vous pouvez également associer un rôle IAM à une instance lorsque vous la lancez. Pour ce faire, créez un IamInstanceProfileSpecificationobjet dont la Name propriété est définie sur le nom d'un rôle IAM. Ajoutez ensuite cet objet à la IamInstanceProfile propriété de l'RunInstancesRequestobjet.

    Note

    Pour lancer une instance EC2 à laquelle un rôle IAM est attaché, la configuration d'un utilisateur IAM doit inclure certaines autorisations. Pour plus d'informations sur les autorisations requises, consultez le guide de l'utilisateur Amazon EC2 ou le guide de l'utilisateur Amazon EC2.

(facultatif) Connectez-vous à l'instance

Une fois qu'une instance est en cours d'exécution, vous pouvez vous y connecter à distance à l'aide du client distant approprié. Pour les instances Linux et Windows, vous avez besoin de l'adresse IP publique ou du nom DNS public de l'instance. Vous avez également besoin des éléments suivants.

Pour les instances Linux

Vous pouvez utiliser un client SSH pour vous connecter à votre instance Linux. Assurez-vous que le groupe de sécurité que vous avez utilisé lorsque vous avez lancé l'instance autorise le trafic SSH sur le port 22, comme décrit dansMise à jour des groupes de sécurité.

Vous avez également besoin de la partie privée de la paire de clés que vous avez utilisée pour lancer l'instance, c'est-à-dire le fichier PEM.

Pour plus d'informations, consultez Connect to your Linux instance dans le guide de l'utilisateur Amazon EC2.

Pour les instances Windows

Vous pouvez utiliser un client RDP pour vous connecter à votre instance. Assurez-vous que le groupe de sécurité que vous avez utilisé lorsque vous avez lancé l'instance autorise le trafic RDP sur le port 3389, comme décrit dans. Mise à jour des groupes de sécurité

Vous avez également besoin du mot de passe administrateur. Vous pouvez l'obtenir en utilisant l'exemple de code suivant, qui nécessite l'ID de l'instance et la partie privée de la paire de clés utilisée pour lancer l'instance, c'est-à-dire le fichier PEM.

Pour plus d'informations, consultez la section Connexion à votre instance Windows dans le guide de l'utilisateur Amazon EC2.

Avertissement

Cet exemple de code renvoie le mot de passe administrateur en texte brut pour votre instance.

using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using Amazon.EC2; using Amazon.EC2.Model; namespace EC2GetWindowsPassword { // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = // Class to get the Administrator password of a Windows EC2 instance 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 instanceID = CommandLine.GetArgument(parsedArgs, null, "-i", "--instance-id"); string pemFileName = CommandLine.GetArgument(parsedArgs, null, "-p", "--pem-filename"); if( (string.IsNullOrEmpty(instanceID) || !instanceID.StartsWith("i-")) || (string.IsNullOrEmpty(pemFileName) || !pemFileName.EndsWith(".pem"))) CommandLine.ErrorExit( "\nOne or more of the required arguments is missing or incorrect." + "\nRun the command with no arguments to see help."); // Create the EC2 client var ec2Client = new AmazonEC2Client(); // Get and display the password string password = await GetPassword(ec2Client, instanceID, pemFileName); Console.WriteLine($"\nPassword: {password}"); } // // Method to get the administrator password of a Windows EC2 instance private static async Task<string> GetPassword( IAmazonEC2 ec2Client, string instanceID, string pemFilename) { string password = string.Empty; GetPasswordDataResponse response = await ec2Client.GetPasswordDataAsync(new GetPasswordDataRequest{ InstanceId = instanceID}); if(response.PasswordData != null) { password = response.GetDecryptedPassword(File.ReadAllText(pemFilename)); } else { Console.WriteLine($"\nThe password is not available for instance {instanceID}."); Console.WriteLine($"If this is a Windows instance, the password might not be ready."); } return password; } // // Command-line help private static void PrintHelp() { Console.WriteLine( "\nUsage: EC2GetWindowsPassword -i <instance-id> -p pem-filename" + "\n -i, --instance-id: The name of the EC2 instance." + "\n -p, --pem-filename: The name of the PEM file with the private key."); } } // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = // 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); } } }

Nettoyage

Lorsque vous n'avez plus besoin de votre instance EC2, veillez à la mettre hors service, comme décrit dansInterruption d'une instance Amazon EC2.