Starten einer Amazon EC2 EC2-Instance - AWS SDK for .NET

Die vorliegende Übersetzung wurde maschinell erstellt. Im Falle eines Konflikts oder eines Widerspruchs zwischen dieser übersetzten Fassung und der englischen Fassung (einschließlich infolge von Verzögerungen bei der Übersetzung) ist die englische Fassung maßgeblich.

Starten einer Amazon EC2 EC2-Instance

Dieses Beispiel zeigt Ihnen, wie Sie die verwenden AWS SDK for .NET , um eine oder mehrere identisch konfigurierte Amazon EC2 EC2-Instances von demselben Amazon Machine Image (AMI) aus zu starten. Unter Verwendung mehrerer von Ihnen eingegebener Eingaben startet die Anwendung eine EC2-Instance und überwacht die Instance dann, bis sie den Status „Ausstehend“ erreicht hat.

Wenn Ihre EC2-Instance läuft, können Sie eine Remoteverbindung zu ihr herstellen, wie unter beschrieben. (optional) Connect zur Instanz her

Warnung

EC2-Classic wurde am 15. August 2022 außer Betrieb genommen. Wir empfehlen Ihnen die Migration von EC2-Classic zu einer VPC. Weitere Informationen finden Sie im Blogbeitrag EC2-Classic Networking is Retiring — So bereiten Sie sich vor.

Die folgenden Abschnitte enthalten Auszüge und andere Informationen zu diesem Beispiel. Der vollständige Code für das Beispiel wird hinter den Codefragmenten angezeigt und kann unverändert erstellt und ausgeführt werden.

Sammle, was du brauchst

Um eine EC2-Instance zu starten, benötigen Sie mehrere Dinge.

  • Eine VPC, auf der die Instance gestartet wird. Wenn es sich um eine Windows-Instance handelt und Sie über RDP eine Verbindung zu ihr herstellen, muss an die VPC höchstwahrscheinlich ein Internet-Gateway sowie ein Eintrag für das Internet-Gateway in der Routing-Tabelle angeschlossen sein. Weitere Informationen finden Sie unter Internet-Gateways im Amazon-VPC-Benutzerhandbuch.

  • Die ID eines vorhandenen Subnetzes in der VPC, in dem die Instance gestartet wird. Eine einfache Möglichkeit, dies zu finden oder zu erstellen, besteht darin, sich bei der Amazon VPC-Konsole anzumelden. Sie können es aber auch programmgesteuert abrufen, indem Sie die CreateSubnetAsyncMethoden und verwenden. DescribeSubnetsAsync

    Anmerkung

    Wenn Sie diesen Parameter nicht angeben, wird die neue Instance in der Standard-VPC für Ihr Konto gestartet.

  • Wenn Sie eine Verbindung mit der neuen Instanz herstellen möchten, muss die zuvor erwähnte Sicherheitsgruppe über eine entsprechende Regel für eingehenden Datenverkehr verfügen, die SSH-Verkehr auf Port 22 (Linux-Instanz) oder RDP-Verkehr auf Port 3389 (Windows-Instanz) zulässt. Informationen dazu finden Sie unterSicherheitsgruppen werden aktualisiert, auch am Ende dieses Weitere Überlegungen Themas.

Starten einer -Instance

Das folgende Snippet startet eine EC2-Instance.

Das Beispiel am Ende dieses Themas zeigt, wie dieses Snippet verwendet wird.

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

Überwachen Sie die Instanz

Das folgende Snippet überwacht die Instanz, bis sie den Status „Ausstehend“ erreicht hat.

Das Beispiel am Ende dieses Themas zeigt, wie dieses Snippet verwendet wird.

Die gültigen Werte der Eigenschaft finden Sie in der InstanceStateInstance.State.CodeKlasse.

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

Vollständiger Code

Dieser Abschnitt enthält relevante Referenzen und den vollständigen Code für dieses Beispiel.

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

Weitere Überlegungen

  • Wenn Sie den Status einer EC2-Instance überprüfen, können Sie der Filter Eigenschaft des DescribeInstancesRequestObjekts einen Filter hinzufügen. Mit dieser Technik können Sie die Anfrage auf bestimmte Instanzen beschränken, z. B. auf Instanzen mit einem bestimmten benutzerdefinierten Tag.

  • Der Kürze halber wurden einigen Eigenschaften typische Werte zugewiesen. Einige oder alle dieser Eigenschaften können stattdessen programmgesteuert oder durch Benutzereingaben bestimmt werden.

  • Die Werte, die Sie für die MaxCount Eigenschaften MinCount und des RunInstancesRequestObjekts verwenden können, werden durch die Ziel-Availability Zone und die maximale Anzahl von Instanzen bestimmt, die Sie für den Instance-Typ verwenden können. Weitere Informationen finden Sie unter Wie viele Instances kann ich in Amazon EC2 ausführen in den Allgemeinen Häufig gestellten Fragen zu Amazon EC2.

(optional) Connect zur Instanz her

Nachdem eine Instanz ausgeführt wurde, können Sie mithilfe des entsprechenden Remote-Clients eine Remoteverbindung zu ihr herstellen. Sowohl für Linux- als auch für Windows-Instances benötigen Sie die öffentliche IP-Adresse oder den öffentlichen DNS-Namen der Instanz. Sie benötigen außerdem Folgendes.

Für Linux-Instanzen

Sie können einen SSH-Client verwenden, um eine Verbindung zu Ihrer Linux-Instance herzustellen. Stellen Sie sicher, dass die Sicherheitsgruppe, die Sie beim Start der Instance verwendet haben, SSH-Verkehr auf Port 22 zulässt, wie unter beschrieben. Sicherheitsgruppen werden aktualisiert

Sie benötigen auch den privaten Teil des key pair, das Sie zum Starten der Instance verwendet haben, d. h. die PEM-Datei.

Weitere Informationen finden Sie unter Connect to your Linux Instance im Amazon EC2 EC2-Benutzerhandbuch.

Für Windows-Instances

Sie können einen RDP-Client verwenden, um eine Verbindung zu Ihrer Instance herzustellen. Stellen Sie sicher, dass die Sicherheitsgruppe, die Sie beim Start der Instance verwendet haben, RDP-Verkehr auf Port 3389 zulässt, wie unter beschrieben. Sicherheitsgruppen werden aktualisiert

Sie benötigen außerdem das Administratorkennwort. Sie können dies mithilfe des folgenden Beispielcodes abrufen, für den die Instanz-ID und der private Teil des key pair erforderlich sind, das zum Starten der Instance verwendet wurde, d. h. die PEM-Datei.

Weitere Informationen finden Sie unter Connect to your Windows Instance im Amazon EC2 EC2-Benutzerhandbuch.

Warnung

Dieser Beispielcode gibt das Administratorkennwort im Klartext für Ihre Instance zurück.

NuGet Pakete:

Elemente der Programmierung:

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

Bereinigen

Wenn Sie Ihre EC2-Instance nicht mehr benötigen, beenden Sie sie unbedingt, wie unter beschriebenBeenden einer Amazon EC2 EC2-Instance.