

Version 4 (V4) von AWS SDK für .NET wurde veröffentlicht\$1

Informationen zu wichtigen Änderungen und zur Migration Ihrer Anwendungen finden Sie im [Migrationsthema](https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/net-dg-v4.html).

 [https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/net-dg-v4.html](https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/net-dg-v4.html)

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
<a name="run-instance"></a>

Dieses Beispiel zeigt Ihnen, wie Sie die verwenden AWS SDK für .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](#run-instance-gather) 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](#connect-to-instance)

**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](https://aws.amazon.com/blogs/aws/ec2-classic-is-retiring-heres-how-to-prepare/) vor.

Die folgenden Abschnitte enthalten Auszüge und andere Informationen zu diesem Beispiel. Der [vollständige Code für das Beispiel](#run-instance-complete-code) wird hinter den Codefragmenten angezeigt und kann unverändert erstellt und ausgeführt werden.

**Topics**
+ [Sammle, was du brauchst](#run-instance-gather)
+ [Starten einer -Instance](#run-instance-launch)
+ [Überwachen Sie die Instanz](#run-instance-monitor)
+ [Vollständiger Code](#run-instance-complete-code)
+ [Weitere Überlegungen](#run-instance-additional)
+ [(optional) Connect zur Instanz her](#connect-to-instance)
+ [Bereinigen](#run-instance-cleanup)

## Sammle, was du brauchst
<a name="run-instance-gather"></a>

Um eine EC2-Instance zu starten, benötigen Sie mehrere Dinge.
+ Eine [VPC](https://docs.aws.amazon.com/vpc/latest/userguide/), 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](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Internet_Gateway.html) im *Benutzerhandbuch für Amazon VPC*.
+ 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](https://console.aws.amazon.com/vpc/home#subnets) anzumelden. Sie können es aber auch programmgesteuert abrufen, indem Sie die [CreateSubnetAsync](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/MEC2CreateSubnetAsyncCreateSubnetRequestCancellationToken.html)Methoden und verwenden. [DescribeSubnetsAsync](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/MEC2DescribeSubnetsAsyncDescribeSubnetsRequestCancellationToken.html)
**Anmerkung**  
Wenn Sie diesen Parameter nicht angeben, wird die neue Instance in der Standard-VPC für Ihr Konto gestartet.
+ Die ID einer vorhandenen Sicherheitsgruppe, die zu der VPC gehört, in der die Instance gestartet wird. Weitere Informationen finden Sie unter [Arbeiten mit Sicherheitsgruppen in Amazon EC2](security-groups.md).
+ 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 unter[Sicherheitsgruppen werden aktualisiert](authorize-ingress.md), auch am Ende dieses [Weitere Überlegungen](authorize-ingress.md#authorize-ingress-additional) Themas.
+ Das Amazon Machine Image (AMI), das zur Erstellung der Instance verwendet wird. Weitere Informationen dazu AMIs finden Sie unter [Amazon Machine Images (AMIs)](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html) im [Amazon EC2 EC2-Benutzerhandbuch](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/). Insbesondere siehe [Find an AMI](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/finding-an-ami.html) and [Shared AMIs](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/sharing-amis.html).
+ Der Name eines vorhandenen EC2-Schlüsselpaars, das für die Verbindung mit der neuen Instance verwendet wird. Weitere Informationen finden Sie unter [Arbeiten mit Amazon EC2 EC2-Schlüsselpaaren](key-pairs.md).
+ Der Name der PEM-Datei, die den privaten Schlüssel des zuvor erwähnten EC2-Schlüsselpaars enthält. Die PEM-Datei wird verwendet, wenn Sie eine [Remoteverbindung mit der Instance herstellen](#connect-to-instance).

## Starten einer -Instance
<a name="run-instance-launch"></a>

Das folgende Snippet startet eine EC2-Instance.

Das Beispiel [am Ende dieses Themas zeigt, wie dieses](#run-instance-complete-code) 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
<a name="run-instance-monitor"></a>

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

Das Beispiel [am Ende dieses Themas zeigt, wie dieses](#run-instance-complete-code) Snippet verwendet wird.

Die gültigen Werte der Eigenschaft finden Sie in der [InstanceState](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TInstanceState.html)`Instance.State.Code`Klasse.

```
    //
    // 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
<a name="run-instance-complete-code"></a>

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

### SDK-Referenzen
<a name="w2aac19c15c21c19b9c27b5b1"></a>

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

Elemente der Programmierung:
+ [Namespace Amazon.ec2](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/NEC2.html)

  Klasse [EC2Amazon-Kunde](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TEC2Client.html)

  Klasse [InstanceType](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TInstanceType.html)
+ [Namespace Amazon.EC2.Model](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/NEC2Model.html)

  Klasse [DescribeInstancesRequest](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TDescribeInstancesRequest.html)

  Klasse [DescribeInstancesResponse](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TDescribeInstancesResponse.html)

  [Klasseninstanz](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TInstance.html)

  Klasse [InstanceNetworkInterfaceSpecification](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TInstanceNetworkInterfaceSpecification.html)

  Klasse [RunInstancesRequest](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TRunInstancesRequest.html)

  Klasse [RunInstancesResponse](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TRunInstancesResponse.html)

### Der Code
<a name="w2aac19c15c21c19b9c27b7b1"></a>

```
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
<a name="run-instance-additional"></a>
+ Wenn Sie den Status einer EC2-Instance überprüfen, können Sie der `Filter` Eigenschaft des [DescribeInstancesRequest](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TDescribeInstancesRequest.html)Objekts 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 [RunInstancesRequest](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TRunInstancesRequest.html)Objekts 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](https://aws.amazon.com/ec2/faqs/#How_many_instances_can_I_run_in_Amazon_EC2) den Allgemeinen Häufig gestellten Fragen zu Amazon EC2.
+ Wenn Sie einen anderen Instance-Typ als dieses Beispiel verwenden möchten, stehen Ihnen mehrere Instance-Typen zur Auswahl. Weitere Informationen finden Sie unter [Amazon EC2 EC2-Instance-Typen](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) im [Amazon EC2 EC2-Benutzerhandbuch](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/). Weitere Informationen finden Sie unter [Details zum Instanztyp](https://aws.amazon.com/ec2/instance-types/) und [Instanztyp-Explorer](https://aws.amazon.com/ec2/instance-explorer/).
+ Sie können einer Instance auch eine [IAM-Rolle](net-dg-hosm.md) zuordnen, wenn Sie sie starten. Erstellen Sie dazu ein [IamInstanceProfileSpecification](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TIamInstanceProfileSpecification.html)Objekt, dessen `Name` Eigenschaft auf den Namen einer IAM-Rolle gesetzt ist. Fügen Sie dieses Objekt dann der `IamInstanceProfile` Eigenschaft des [RunInstancesRequest](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TRunInstancesRequest.html)Objekts hinzu.
**Anmerkung**  
Um eine EC2-Instance zu starten, der eine IAM-Rolle zugewiesen ist, muss die Konfiguration eines IAM-Benutzers bestimmte Berechtigungen enthalten. Weitere Informationen zu den erforderlichen Berechtigungen finden Sie im [Amazon EC2 EC2-Benutzerhandbuch](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/) [unter Gewähren einer Benutzerberechtigung zur Übergabe einer IAM-Rolle an eine Instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html#permission-to-pass-iam-roles).

## (optional) Connect zur Instanz her
<a name="connect-to-instance"></a>

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-Instances**

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](authorize-ingress.md)

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](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/connect-to-linux-instance.html) 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](authorize-ingress.md)

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

Weitere Informationen finden Sie unter [Connect to your Windows Instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/connecting_to_windows_instance.html) im Amazon EC2 EC2-Benutzerhandbuch.

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

### SDK-Referenzen
<a name="w2aac19c15c21c19b9c35c23b1"></a>

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

Elemente der Programmierung:
+ [Namespace Amazon.ec2](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/NEC2.html)

  Klasse [EC2Amazon-Kunde](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TEC2Client.html)
+ [Namespace Amazon.EC2.Model](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/NEC2Model.html)

  Klasse [GetPasswordDataRequest](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TGetPasswordDataRequest.html)

  Klasse [GetPasswordDataResponse](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TGetPasswordDataResponse.html)

### Der Code
<a name="w2aac19c15c21c19b9c35c25b1"></a>

```
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
<a name="run-instance-cleanup"></a>

Wenn Sie Ihre EC2-Instance nicht mehr benötigen, beenden Sie sie unbedingt, wie unter beschrieben[Beenden einer Amazon EC2 EC2-Instance](terminate-instance.md).