

È stata rilasciata la versione 4 (V4) di\$1 AWS SDK per .NET 

Per informazioni su come apportare modifiche e migrare le applicazioni, consulta l'argomento sulla [migrazione](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)

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

# Avvio di un'istanza Amazon EC2
<a name="run-instance"></a>

Questo esempio mostra come utilizzare AWS SDK per .NET per avviare una o più istanze Amazon EC2 configurate in modo identico dalla stessa Amazon Machine Image (AMI). Utilizzando [diversi input forniti](#run-instance-gather), l'applicazione avvia un'istanza EC2 e quindi monitora l'istanza fino a quando non esce dallo stato «In sospeso».

Quando l'istanza EC2 è in esecuzione, puoi connetterti ad essa in remoto, come descritto in. [(opzionale) Connect all'istanza](#connect-to-instance)

**avvertimento**  
EC2-Classic è stato ritirato il 15 agosto 2022. Suggeriamo di effettuare la migrazione da EC2-Classic a un VPC. Per ulteriori informazioni, consulta il post del blog [EC2-Classic Networking is Retiring — Ecco](https://aws.amazon.com/blogs/aws/ec2-classic-is-retiring-heres-how-to-prepare/) come prepararsi.

Le sezioni seguenti forniscono frammenti e altre informazioni per questo esempio. Il [codice completo dell'esempio](#run-instance-complete-code) viene mostrato dopo gli snippet e può essere creato ed eseguito così com'è.

**Topics**
+ [Raccogli ciò di cui hai bisogno](#run-instance-gather)
+ [Avvio di un'istanza](#run-instance-launch)
+ [Monitora l'istanza](#run-instance-monitor)
+ [Codice completo](#run-instance-complete-code)
+ [Ulteriori considerazioni](#run-instance-additional)
+ [(opzionale) Connect all'istanza](#connect-to-instance)
+ [Eliminazione](#run-instance-cleanup)

## Raccogli ciò di cui hai bisogno
<a name="run-instance-gather"></a>

Per avviare un'istanza EC2, avrai bisogno di diversi elementi.
+ Un [VPC](https://docs.aws.amazon.com/vpc/latest/userguide/) in cui verrà avviata l'istanza. Se si tratta di un'istanza Windows e ti connetterai ad essa tramite RDP, molto probabilmente il VPC dovrà avere un gateway Internet collegato, oltre a una voce per il gateway Internet nella tabella delle rotte. Per ulteriori informazioni, consulta [Gateway Internet](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Internet_Gateway.html) nella *Guida per l’utente di Amazon VPC*.
+ L'ID di una sottorete esistente nel VPC in cui verrà avviata l'istanza. Un modo semplice per trovarlo o crearlo è accedere alla [console Amazon VPC](https://console.aws.amazon.com/vpc/home#subnets), ma puoi anche ottenerlo a livello di codice utilizzando i metodi and. [CreateSubnetAsync[DescribeSubnetsAsync](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/MEC2DescribeSubnetsAsyncDescribeSubnetsRequestCancellationToken.html)](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/MEC2CreateSubnetAsyncCreateSubnetRequestCancellationToken.html)
**Nota**  
Se non fornisci questo parametro, la nuova istanza viene avviata nel VPC predefinito per il tuo account.
+ L'ID di un gruppo di sicurezza esistente che appartiene al VPC in cui verrà avviata l'istanza. Per ulteriori informazioni, consulta [Lavorare con i gruppi di sicurezza in Amazon EC2](security-groups.md).
+ Se desideri connetterti alla nuova istanza, il gruppo di sicurezza menzionato in precedenza deve disporre di una regola in entrata appropriata che consenta il traffico SSH sulla porta 22 (istanza Linux) o il traffico RDP sulla porta 3389 (istanza Windows). Per informazioni su come eseguire questa operazione[Aggiornamento dei gruppi di sicurezza](authorize-ingress.md), consulta anche la parte finale [Ulteriori considerazioni](authorize-ingress.md#authorize-ingress-additional) dell'argomento.
+ L'Amazon Machine Image (AMI) che verrà utilizzata per creare l'istanza. Per informazioni su AMIs, consulta [Amazon Machine Images (AMIs)](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html) nella Guida per l'[utente di Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/). In particolare, vedi [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).
+ Il nome di una coppia di key pair EC2 esistente, utilizzata per connettersi alla nuova istanza. Per ulteriori informazioni, consulta [Utilizzo delle coppie di chiavi Amazon EC2](key-pairs.md).
+ Il nome del file PEM che contiene la chiave privata della coppia di chiavi EC2 menzionata in precedenza. Il file PEM viene utilizzato quando ci si [connette in remoto](#connect-to-instance) all'istanza.

## Avvio di un'istanza
<a name="run-instance-launch"></a>

Il seguente frammento avvia un'istanza EC2.

L'esempio [alla fine di questo argomento mostra questo frammento](#run-instance-complete-code) in uso.

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

## Monitora l'istanza
<a name="run-instance-monitor"></a>

Il seguente frammento monitora l'istanza fino a quando non esce dallo stato «In sospeso».

L'esempio [alla fine di questo argomento mostra questo frammento](#run-instance-complete-code) in uso.

Consultate la [InstanceState](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TInstanceState.html)classe per i valori validi della `Instance.State.Code` proprietà.

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

## Codice completo
<a name="run-instance-complete-code"></a>

Questa sezione mostra i riferimenti pertinenti e il codice completo per questo esempio.

### Riferimenti SDK
<a name="w2aac19c15c21c19b9c27b5b1"></a>

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

Elementi di programmazione:
+ [Spazio dei nomi Amazon.ec2](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/NEC2.html)

  Classe [Amazon EC2 Client](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TEC2Client.html)

  Classe [InstanceType](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TInstanceType.html)
+ [Spazio dei nomi Amazon.ec2.model](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/NEC2Model.html)

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

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

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

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

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

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

### Il codice
<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);
    }
  }

}
```

## Ulteriori considerazioni
<a name="run-instance-additional"></a>
+ Quando controlli lo stato di un'istanza EC2, puoi aggiungere un filtro alla `Filter` proprietà dell'[DescribeInstancesRequest](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TDescribeInstancesRequest.html)oggetto. Utilizzando questa tecnica, puoi limitare la richiesta a determinate istanze; ad esempio, istanze con un particolare tag specificato dall'utente.
+ Per brevità, ad alcune proprietà sono stati assegnati valori tipici. Alcune o tutte queste proprietà possono invece essere determinate a livello di codice o tramite l'input dell'utente.
+ I valori che è possibile utilizzare per l'[RunInstancesRequest](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TRunInstancesRequest.html)oggetto `MinCount` e `MaxCount` le proprietà sono determinati dalla zona di disponibilità di destinazione e dal numero massimo di istanze consentite per il tipo di istanza. Per ulteriori informazioni, consulta [Quante istanze posso eseguire in Amazon EC2 nelle](https://aws.amazon.com/ec2/faqs/#How_many_instances_can_I_run_in_Amazon_EC2) Domande frequenti generali di Amazon EC2.
+ Se desideri utilizzare un tipo di istanza diverso da questo esempio, ci sono diversi tipi di istanza tra cui scegliere. Per ulteriori informazioni, consulta i [tipi di istanze di Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) nella [Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/) User Guide. Consulta anche [Instance Type Details](https://aws.amazon.com/ec2/instance-types/) e [Instance Type Explorer](https://aws.amazon.com/ec2/instance-explorer/).
+ Puoi anche assegnare un [ruolo IAM](net-dg-hosm.md) a un'istanza al momento del lancio. A tale scopo, crea un [IamInstanceProfileSpecification](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TIamInstanceProfileSpecification.html)oggetto la cui `Name` proprietà è impostata sul nome di un ruolo IAM. Quindi aggiungi quell'oggetto alla `IamInstanceProfile` proprietà dell'[RunInstancesRequest](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TRunInstancesRequest.html)oggetto.
**Nota**  
Per avviare un'istanza EC2 a cui è associato un ruolo IAM, la configurazione di un utente IAM deve includere determinate autorizzazioni. Per ulteriori informazioni sulle autorizzazioni richieste, consulta la sezione [Concedere l'autorizzazione a un utente per passare un ruolo IAM a un'istanza](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html#permission-to-pass-iam-roles) nella [Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/) User Guide.

## (opzionale) Connect all'istanza
<a name="connect-to-instance"></a>

Dopo l'esecuzione di un'istanza, puoi connetterti ad essa in remoto utilizzando il client remoto appropriato. Sia per le istanze Linux che per quelle Windows, è necessario l'indirizzo IP pubblico o il nome DNS pubblico dell'istanza. È inoltre necessario quanto segue.

**Per istanze Linux**

Puoi usare un client SSH per connetterti alla tua istanza Linux. Assicurati che il gruppo di sicurezza utilizzato all'avvio dell'istanza consenta il traffico SSH sulla porta 22, come descritto in. [Aggiornamento dei gruppi di sicurezza](authorize-ingress.md)

È inoltre necessaria la parte privata della coppia di chiavi utilizzata per avviare l'istanza, ovvero il file PEM.

Per ulteriori informazioni, consulta [Connect to your Linux istance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/connect-to-linux-instance.html) nella Amazon EC2 User Guide.

**Per le istanze Windows**

Puoi utilizzare un client RDP per connetterti alla tua istanza. Assicurati che il gruppo di sicurezza utilizzato all'avvio dell'istanza consenta il traffico RDP sulla porta 3389, come descritto in. [Aggiornamento dei gruppi di sicurezza](authorize-ingress.md)

È inoltre necessaria la password dell'amministratore. È possibile ottenere ciò utilizzando il seguente codice di esempio, che richiede l'ID dell'istanza e la parte privata della coppia di chiavi utilizzata per avviare l'istanza, ovvero il file PEM.

Per ulteriori informazioni, consulta [Connect to your Windows nella](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/connecting_to_windows_instance.html) Amazon EC2 User Guide.

**avvertimento**  
Questo codice di esempio restituisce la password di amministratore in testo semplice per l'istanza.

### Riferimenti SDK
<a name="w2aac19c15c21c19b9c35c23b1"></a>

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

Elementi di programmazione:
+ [Spazio dei nomi Amazon.ec2](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/NEC2.html)

  Classe [Amazon EC2 Client](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TEC2Client.html)
+ [Spazio dei nomi Amazon.ec2.model](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/NEC2Model.html)

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

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

### Il codice
<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);
    }
  }

}
```

## Eliminazione
<a name="run-instance-cleanup"></a>

Quando non hai più bisogno della tua istanza EC2, assicurati di terminarla, come descritto in. [Terminazione di un'istanza Amazon EC2](terminate-instance.md)