

 AWS SDK untuk .NET V3 telah memasuki mode pemeliharaan.

Kami menyarankan Anda bermigrasi ke [AWS SDK untuk .NET V4](https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/welcome.html). Untuk detail dan informasi tambahan tentang cara bermigrasi, silakan lihat [pengumuman mode pemeliharaan](https://aws.amazon.com/blogs/developer/aws-sdk-for-net-v3-maintenance-mode-announcement/) kami.

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

# Bekerja dengan Amazon EC2
<a name="ec2-apis-intro"></a>

Ini AWS SDK untuk .NET mendukung [Amazon EC2](https://docs.aws.amazon.com/ec2/), yang merupakan layanan web yang menyediakan kapasitas komputasi yang dapat diubah ukurannya. Anda menggunakan kapasitas komputasi ini untuk membangun dan meng-host sistem perangkat lunak Anda.

## APIs
<a name="w2aac19c15c17b5"></a>

 AWS SDK untuk .NET Ini menyediakan API untuk klien Amazon EC2. API memungkinkan Anda untuk bekerja dengan fitur EC2 seperti grup keamanan dan pasangan kunci. API juga memungkinkan Anda mengontrol instans Amazon EC2. Bagian ini berisi sejumlah kecil contoh yang menunjukkan pola yang dapat Anda ikuti saat bekerja dengan ini APIs. Untuk melihat set lengkap APIs, lihat [Referensi AWS SDK untuk .NET API](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/) (dan gulir ke “Amazon.EC2").

Amazon EC2 APIs disediakan oleh [AWSSDK NuGet paket.EC2](https://www.nuget.org/packages/AWSSDK.EC2).

## Prasyarat
<a name="w2aac19c15c17b7"></a>

Sebelum Anda mulai, pastikan Anda telah [mengatur lingkungan dan proyek Anda](net-dg-config.md). Juga tinjau informasi di[Fitur SDK](net-dg-sdk-features.md).

## Tentang contoh
<a name="ec2-apis-intro-about"></a>

Contoh di bagian ini menunjukkan cara bekerja dengan klien Amazon EC2 dan mengelola instans Amazon EC2.

[Tutorial Instans Spot EC2](how-to-spot-instances.md) menunjukkan cara meminta Instans Spot Amazon EC2. Instans Spot memungkinkan Anda mengakses kapasitas EC2 yang tidak digunakan dengan harga kurang dari harga Sesuai Permintaan.

**Topics**
+ [APIs](#w2aac19c15c17b5)
+ [Prasyarat](#w2aac19c15c17b7)
+ [Tentang contoh](#ec2-apis-intro-about)
+ [Grup keamanan](security-groups.md)
+ [Pasangan kunci](key-pairs.md)
+ [Wilayah dan Zona Ketersediaan](using-regions-and-availability-zones.md)
+ [Instans EC2](how-to-ec2.md)
+ [Tutorial Instans Spot](how-to-spot-instances.md)

# Bekerja dengan grup keamanan di Amazon EC2
<a name="security-groups"></a>

Di Amazon EC2, *grup keamanan* bertindak sebagai firewall virtual yang mengontrol lalu lintas jaringan untuk satu atau lebih instans EC2. Secara default, EC2 mengaitkan instans Anda dengan grup keamanan yang tidak mengizinkan lalu lintas masuk. Anda dapat membuat grup keamanan yang memungkinkan instans EC2 Anda menerima lalu lintas tertentu. Misalnya, jika Anda perlu terhubung ke instans EC2 Windows, Anda harus mengkonfigurasi grup keamanan untuk memungkinkan lalu lintas RDP.

Untuk membaca selengkapnya tentang grup keamanan, lihat [grup keamanan Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-security-groups.html) di Panduan Pengguna [Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/).

**Awas**  
EC2-Classic sudah tidak digunakan lagi pada 15 Agustus 2022. Kami menyarankan Anda bermigrasi dari EC2-Classic ke VPC. Untuk informasi lebih lanjut, lihat posting blog [EC2-Classic Networking is Retiring - Inilah Cara Mempersiapkan](https://aws.amazon.com/blogs/aws/ec2-classic-is-retiring-heres-how-to-prepare/).

Untuk informasi tentang APIs dan prasyarat, lihat bagian induk (). [Bekerja dengan Amazon EC2](ec2-apis-intro.md)

**Topics**
+ [Menghitung kelompok keamanan](enumerate-security-groups.md)
+ [Membuat grup keamanan](creating-security-group.md)
+ [Memperbarui grup keamanan](authorize-ingress.md)

# Menghitung kelompok keamanan
<a name="enumerate-security-groups"></a>

Contoh ini menunjukkan kepada Anda cara menggunakan AWS SDK untuk .NET untuk menghitung grup keamanan. Jika Anda menyediakan ID [Amazon Virtual Private Cloud](https://docs.aws.amazon.com/vpc/latest/userguide/), aplikasi menghitung grup keamanan untuk VPC tertentu. Jika tidak, aplikasi hanya menampilkan daftar semua grup keamanan yang tersedia.

Bagian berikut menyediakan cuplikan dari contoh ini. [Kode lengkap untuk contoh](#enum-sec-groups-complete-code) ditampilkan setelah itu, dan dapat dibangun dan dijalankan apa adanya.

**Topics**
+ [Menghitung kelompok keamanan](#enum-sec-groups-enum)
+ [Kode lengkap](#enum-sec-groups-complete-code)
+ [Pertimbangan tambahan](#enum-sec-groups-additional)

## Menghitung kelompok keamanan
<a name="enum-sec-groups-enum"></a>

Cuplikan berikut menyebutkan grup keamanan Anda. Ini menghitung semua grup atau grup untuk VPC tertentu jika diberikan.

Contoh [di akhir topik ini](#enum-sec-groups-complete-code) menunjukkan cuplikan ini digunakan.

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

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

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

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

## Kode lengkap
<a name="enum-sec-groups-complete-code"></a>

Bagian ini menunjukkan referensi yang relevan dan kode lengkap untuk contoh ini.

### Referensi SDK
<a name="w2aac19c15c17c13c13c15b5b1"></a>

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

Elemen pemrograman:
+ [Namespace Amazon.EC2](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/NEC2.html)

  [EC2Klien Kelas Amazon](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TEC2Client.html)
+ [Namespace Amazon.EC2.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/NEC2Model.html)

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

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

  [Filter](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TFilter.html) Kelas

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

### Kode
<a name="w2aac19c15c17c13c13c15b7b1"></a>

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

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

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

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


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

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

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

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

## Pertimbangan tambahan
<a name="enum-sec-groups-additional"></a>
+ Perhatikan untuk kasus VPC bahwa filter dibuat dengan `Name` bagian dari pasangan nama-nilai yang disetel ke “vpc-id”. Nama ini berasal dari deskripsi untuk `Filters` properti [DescribeSecurityGroupsRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TDescribeSecurityGroupsRequest.html)kelas.
+ Untuk mendapatkan daftar lengkap grup keamanan Anda, Anda juga dapat menggunakan [ DescribeSecurityGroupsAsync tanpa parameter](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/MEC2DescribeSecurityGroupsAsyncCancellationToken.html).
+ Anda dapat memverifikasi hasilnya dengan memeriksa daftar grup keamanan di konsol [Amazon EC2](https://console.aws.amazon.com/ec2/v2/home#SecurityGroups).

# Membuat grup keamanan
<a name="creating-security-group"></a>

Contoh ini menunjukkan cara menggunakan AWS SDK untuk .NET untuk membuat grup keamanan. Anda dapat memberikan ID VPC yang ada untuk membuat grup keamanan EC2 di VPC. Jika Anda tidak memberikan ID seperti itu, grup keamanan baru akan digunakan untuk EC2-Classic jika AWS akun Anda mendukung ini.

Jika Anda tidak memberikan ID VPC dan AWS akun Anda tidak mendukung EC2-Classic, grup keamanan baru akan menjadi milik VPC default akun Anda.

**Awas**  
EC2-Classic sudah tidak digunakan lagi pada 15 Agustus 2022. Kami menyarankan Anda bermigrasi dari EC2-Classic ke VPC. Untuk informasi lebih lanjut, lihat posting blog [EC2-Classic Networking is Retiring - Inilah Cara Mempersiapkan](https://aws.amazon.com/blogs/aws/ec2-classic-is-retiring-heres-how-to-prepare/).

Bagian berikut menyediakan cuplikan dari contoh ini. [Kode lengkap untuk contoh](#create-sec-groups-complete-code) ditampilkan setelah itu, dan dapat dibangun dan dijalankan apa adanya.

**Topics**
+ [Temukan grup keamanan yang ada](#create-sec-groups-find)
+ [Membuat grup keamanan](#create-sec-groups-enum)
+ [Kode lengkap](#create-sec-groups-complete-code)

## Temukan grup keamanan yang ada
<a name="create-sec-groups-find"></a>

Cuplikan berikut mencari grup keamanan yang ada dengan nama yang diberikan di VPC yang diberikan.

Contoh [di akhir topik ini](#create-sec-groups-complete-code) menunjukkan cuplikan ini digunakan.

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

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

## Membuat grup keamanan
<a name="create-sec-groups-enum"></a>

Cuplikan berikut membuat grup keamanan baru jika grup dengan nama itu tidak ada di VPC yang diberikan. Jika tidak ada VPC yang diberikan dan satu atau lebih grup dengan nama itu ada, cuplikan hanya mengembalikan daftar grup.

Contoh [di akhir topik ini](#create-sec-groups-complete-code) menunjukkan cuplikan ini digunakan.

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

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

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

## Kode lengkap
<a name="create-sec-groups-complete-code"></a>

Bagian ini menunjukkan referensi yang relevan dan kode lengkap untuk contoh ini.

### Referensi SDK
<a name="w2aac19c15c17c13c15c23b5b1"></a>

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

Elemen pemrograman:
+ [Namespace Amazon.EC2](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/NEC2.html)

  [EC2Klien Kelas Amazon](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TEC2Client.html)
+ [Namespace Amazon.EC2.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/NEC2Model.html)

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

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

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

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

  [Filter](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TFilter.html) Kelas

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

### Kodenya
<a name="w2aac19c15c17c13c15c23b7b1"></a>

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

namespace EC2CreateSecGroup
{
  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // Class to create a security group
  class Program
  {
    private const int MaxArgs = 2;

    static async Task Main(string[] args)
    {
      // Parse the command line and show help if necessary
      var parsedArgs = CommandLine.Parse(args);
      if(parsedArgs.Count == 0)
      {
        PrintHelp();
        return;
      }
      if(parsedArgs.Count > MaxArgs)
        CommandLine.ErrorExit("\nThe number of command-line arguments is incorrect." +
          "\nRun the command with no arguments to see help.");

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

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


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

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

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


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

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


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


  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // Class that represents a command line on the console or terminal.
  // (This is the same for all examples. When you have seen it once, you can ignore it.)
  static class CommandLine
  {
    //
    // Method to parse a command line of the form: "--key value" or "-k value".
    //
    // Parameters:
    // - args: The command-line arguments passed into the application by the system.
    //
    // Returns:
    // A Dictionary with string Keys and Values.
    //
    // If a key is found without a matching value, Dictionary.Value is set to the key
    //  (including the dashes).
    // If a value is found without a matching key, Dictionary.Key is set to "--NoKeyN",
    //  where "N" represents sequential numbers.
    public static Dictionary<string,string> Parse(string[] args)
    {
      var parsedArgs = new Dictionary<string,string>();
      int i = 0, n = 0;
      while(i < args.Length)
      {
        // If the first argument in this iteration starts with a dash it's an option.
        if(args[i].StartsWith("-"))
        {
          var key = args[i++];
          var value = key;

          // Check to see if there's a value that goes with this option?
          if((i < args.Length) && (!args[i].StartsWith("-"))) value = args[i++];
          parsedArgs.Add(key, value);
        }

        // If the first argument in this iteration doesn't start with a dash, it's a value
        else
        {
          parsedArgs.Add("--NoKey" + n.ToString(), args[i++]);
          n++;
        }
      }

      return parsedArgs;
    }

    //
    // Method to get an argument from the parsed command-line arguments
    //
    // Parameters:
    // - parsedArgs: The Dictionary object returned from the Parse() method (shown above).
    // - defaultValue: The default string to return if the specified key isn't in parsedArgs.
    // - keys: An array of keys to look for in parsedArgs.
    public static string GetArgument(
      Dictionary<string,string> parsedArgs, string defaultReturn, params string[] keys)
    {
      string retval = null;
      foreach(var key in keys)
        if(parsedArgs.TryGetValue(key, out retval)) break;
      return retval ?? defaultReturn;
    }

    //
    // Method to exit the application with an error.
    public static void ErrorExit(string msg, int code=1)
    {
      Console.WriteLine("\nError");
      Console.WriteLine(msg);
      Environment.Exit(code);
    }
  }

}
```

# Memperbarui grup keamanan
<a name="authorize-ingress"></a>

Contoh ini menunjukkan cara menggunakan aturan AWS SDK untuk .NET untuk menambahkan aturan ke grup keamanan. Secara khusus, contoh menambahkan aturan untuk mengizinkan lalu lintas masuk pada port TCP tertentu, yang dapat digunakan, misalnya, untuk koneksi jarak jauh ke instance EC2. Aplikasi mengambil ID dari grup keamanan yang ada, alamat IP (atau rentang alamat) dalam format CIDR, dan opsional nomor port TCP. Kemudian menambahkan aturan masuk ke grup keamanan yang diberikan.

**catatan**  
Untuk menggunakan contoh ini, Anda memerlukan alamat IP (atau rentang alamat) dalam format CIDR. Lihat **Pertimbangan tambahan** di akhir topik ini untuk metode mendapatkan alamat IP komputer lokal Anda.

Bagian berikut menyediakan cuplikan dari contoh ini. [Kode lengkap untuk contoh](#authorize-ingress-complete-code) ditampilkan setelah itu, dan dapat dibangun dan dijalankan apa adanya.

**Topics**
+ [Tambahkan aturan masuk](#authorize-ingress-add-rule)
+ [Kode lengkap](#authorize-ingress-complete-code)
+ [Pertimbangan tambahan](#authorize-ingress-additional)

## Tambahkan aturan masuk
<a name="authorize-ingress-add-rule"></a>

Cuplikan berikut menambahkan aturan masuk ke grup keamanan untuk alamat IP tertentu (atau rentang) dan port TCP.

Contoh [di akhir topik ini](#authorize-ingress-complete-code) menunjukkan cuplikan ini digunakan.

```
    //
    // Method that adds a TCP ingress rule to a security group
    private static async Task AddIngressRule(
      IAmazonEC2 eC2Client, string groupID, string ipAddress, int port)
    {
      // Create an object to hold the request information for the rule.
      // It uses an IpPermission object to hold the IP information for the rule.
      var ingressRequest = new AuthorizeSecurityGroupIngressRequest{
        GroupId = groupID};
      ingressRequest.IpPermissions.Add(new IpPermission{
        IpProtocol = "tcp",
        FromPort = port,
        ToPort = port,
        Ipv4Ranges = new List<IpRange>() { new IpRange { CidrIp = ipAddress } }
      });

      // Create the inbound rule for the security group
      AuthorizeSecurityGroupIngressResponse responseIngress =
        await eC2Client.AuthorizeSecurityGroupIngressAsync(ingressRequest);
      Console.WriteLine($"\nNew RDP rule was written in {groupID} for {ipAddress}.");
      Console.WriteLine($"Result: {responseIngress.HttpStatusCode}");
    }
```

## Kode lengkap
<a name="authorize-ingress-complete-code"></a>

Bagian ini menunjukkan referensi yang relevan dan kode lengkap untuk contoh ini.

### Referensi SDK
<a name="w2aac19c15c17c13c17c17b5b1"></a>

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

Elemen pemrograman:
+ [Namespace Amazon.EC2](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/NEC2.html)

  [EC2Klien Kelas Amazon](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TEC2Client.html)
+ [Namespace Amazon.EC2.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/NEC2Model.html)

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

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

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

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

### Kodenya
<a name="w2aac19c15c17c13c17c17b7b1"></a>

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

namespace EC2AddRuleForRDP
{
  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // Class to add a rule that allows inbound traffic on TCP a port
  class Program
  {
    private const int DefaultPort = 3389;

    static async Task Main(string[] args)
    {
      // Parse the command line and show help if necessary
      var parsedArgs = CommandLine.Parse(args);
      if(parsedArgs.Count == 0)
      {
        PrintHelp();
        return;
      }

      // Get the application arguments from the parsed list
      var groupID = CommandLine.GetArgument(parsedArgs, null, "-g", "--group-id");
      var ipAddress = CommandLine.GetArgument(parsedArgs, null, "-i", "--ip-address");
      var portStr = CommandLine.GetArgument(parsedArgs, DefaultPort.ToString(), "-p", "--port");
      if(string.IsNullOrEmpty(ipAddress))
        CommandLine.ErrorExit("\nYou must supply an IP address in CIDR format.");
      if(string.IsNullOrEmpty(groupID) || !groupID.StartsWith("sg-"))
        CommandLine.ErrorExit("\nThe ID for a security group is missing or incorrect.");
      if(int.Parse(portStr) == 0)
        CommandLine.ErrorExit($"\nThe given TCP port number, {portStr}, isn't allowed.");

      // Add a rule to the given security group that allows
      // inbound traffic on a TCP port
      await AddIngressRule(
        new AmazonEC2Client(), groupID, ipAddress, int.Parse(portStr));
    }


    //
    // Method that adds a TCP ingress rule to a security group
    private static async Task AddIngressRule(
      IAmazonEC2 eC2Client, string groupID, string ipAddress, int port)
    {
      // Create an object to hold the request information for the rule.
      // It uses an IpPermission object to hold the IP information for the rule.
      var ingressRequest = new AuthorizeSecurityGroupIngressRequest{
        GroupId = groupID};
      ingressRequest.IpPermissions.Add(new IpPermission{
        IpProtocol = "tcp",
        FromPort = port,
        ToPort = port,
        Ipv4Ranges = new List<IpRange>() { new IpRange { CidrIp = ipAddress } }
      });

      // Create the inbound rule for the security group
      AuthorizeSecurityGroupIngressResponse responseIngress =
        await eC2Client.AuthorizeSecurityGroupIngressAsync(ingressRequest);
      Console.WriteLine($"\nNew RDP rule was written in {groupID} for {ipAddress}.");
      Console.WriteLine($"Result: {responseIngress.HttpStatusCode}");
    }


    //
    // Command-line help
    private static void PrintHelp()
    {
      Console.WriteLine(
        "\nUsage: EC2AddRuleForRDP -g <group-id> -i <ip-address> [-p <port>]" +
        "\n  -g, --group-id: The ID of the security group to which you want to add the inbound rule." +
        "\n  -i, --ip-address: An IP address or address range in CIDR format." +
        "\n  -p, --port: The TCP port number. Defaults to 3389.");
    }
  }


  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // Class that represents a command line on the console or terminal.
  // (This is the same for all examples. When you have seen it once, you can ignore it.)
  static class CommandLine
  {
    //
    // Method to parse a command line of the form: "--key value" or "-k value".
    //
    // Parameters:
    // - args: The command-line arguments passed into the application by the system.
    //
    // Returns:
    // A Dictionary with string Keys and Values.
    //
    // If a key is found without a matching value, Dictionary.Value is set to the key
    //  (including the dashes).
    // If a value is found without a matching key, Dictionary.Key is set to "--NoKeyN",
    //  where "N" represents sequential numbers.
    public static Dictionary<string,string> Parse(string[] args)
    {
      var parsedArgs = new Dictionary<string,string>();
      int i = 0, n = 0;
      while(i < args.Length)
      {
        // If the first argument in this iteration starts with a dash it's an option.
        if(args[i].StartsWith("-"))
        {
          var key = args[i++];
          var value = key;

          // Check to see if there's a value that goes with this option?
          if((i < args.Length) && (!args[i].StartsWith("-"))) value = args[i++];
          parsedArgs.Add(key, value);
        }

        // If the first argument in this iteration doesn't start with a dash, it's a value
        else
        {
          parsedArgs.Add("--NoKey" + n.ToString(), args[i++]);
          n++;
        }
      }

      return parsedArgs;
    }

    //
    // Method to get an argument from the parsed command-line arguments
    //
    // Parameters:
    // - parsedArgs: The Dictionary object returned from the Parse() method (shown above).
    // - defaultValue: The default string to return if the specified key isn't in parsedArgs.
    // - keys: An array of keys to look for in parsedArgs.
    public static string GetArgument(
      Dictionary<string,string> parsedArgs, string defaultReturn, params string[] keys)
    {
      string retval = null;
      foreach(var key in keys)
        if(parsedArgs.TryGetValue(key, out retval)) break;
      return retval ?? defaultReturn;
    }

    //
    // Method to exit the application with an error.
    public static void ErrorExit(string msg, int code=1)
    {
      Console.WriteLine("\nError");
      Console.WriteLine(msg);
      Environment.Exit(code);
    }
  }

}
```

## Pertimbangan tambahan
<a name="authorize-ingress-additional"></a>
+ Jika Anda tidak menyediakan nomor port, aplikasi default ke port 3389. Ini adalah port untuk Windows RDP, yang memungkinkan Anda untuk terhubung ke instans EC2 yang menjalankan Windows. Jika Anda meluncurkan instans EC2 yang menjalankan Linux, Anda dapat menggunakan port TCP 22 (SSH) sebagai gantinya.
+ Perhatikan bahwa contoh disetel `IpProtocol` ke “tcp”. Nilai untuk `IpProtocol` dapat ditemukan dalam deskripsi untuk `IpProtocol` properti [IpPermission](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TIpPermission.html)kelas.
+ Anda mungkin menginginkan alamat IP komputer lokal Anda saat menggunakan contoh ini. Berikut ini adalah beberapa cara di mana Anda bisa mendapatkan alamat.
  + Jika komputer lokal Anda (dari mana Anda akan terhubung ke instans EC2 Anda) memiliki alamat IP publik statis, Anda dapat menggunakan layanan untuk mendapatkan alamat itu. Salah satu layanan tersebut adalah [http://checkip.amazonaws.com/](http://checkip.amazonaws.com/). Untuk membaca selengkapnya tentang mengotorisasi lalu lintas masuk, lihat [Menambahkan aturan ke grup keamanan](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/working-with-security-groups.html#adding-security-group-rule) dan [Aturan grup keamanan untuk kasus penggunaan yang berbeda](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/security-group-rules-reference.html) di Panduan Pengguna [Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/).
  + Cara lain untuk mendapatkan alamat IP komputer lokal Anda adalah dengan menggunakan konsol [Amazon EC2](https://console.aws.amazon.com/ec2/v2/home#SecurityGroups).

    Pilih salah satu grup keamanan Anda, pilih tab **Aturan masuk**, dan pilih **Edit aturan masuk**. Dalam aturan masuk, buka menu tarik-turun di kolom **Sumber** dan pilih **IP Saya** untuk melihat alamat IP komputer lokal Anda dalam format CIDR. Pastikan untuk **Membatalkan** operasi.
+ Anda dapat memverifikasi hasil contoh ini dengan memeriksa daftar grup keamanan di konsol [Amazon EC2](https://console.aws.amazon.com/ec2/v2/home#SecurityGroups).

# Bekerja dengan pasangan kunci Amazon EC2
<a name="key-pairs"></a>

Amazon EC2 menggunakan kriptografi kunci publik untuk mengenkripsi dan mendekripsi informasi login. Kriptografi kunci publik menggunakan kunci publik untuk mengenkripsi data, dan kemudian penerima menggunakan kunci pribadi untuk mendekripsi data. Kunci publik dan privat dikenal sebagai pasangan kunci. Jika Anda ingin masuk ke instans EC2, Anda harus menentukan key pair ketika Anda meluncurkannya, dan kemudian memberikan kunci pribadi pasangan ketika Anda terhubung ke sana.

Saat meluncurkan instans EC2, Anda dapat membuat key pair untuknya atau menggunakan salah satu yang sudah Anda gunakan saat meluncurkan instance lain. Untuk membaca selengkapnya tentang pasangan kunci Amazon EC2, lihat [Bekerja dengan pasangan kunci Amazon EC2 di Panduan](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html) Pengguna Amazon [EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/).

Untuk informasi tentang APIs dan prasyarat, lihat bagian induk (). [Bekerja dengan Amazon EC2](ec2-apis-intro.md)

**Topics**
+ [Membuat dan menampilkan pasangan kunci](create-save-key-pair.md)
+ [Menghapus pasangan kunci](delete-key-pairs.md)

# Membuat dan menampilkan pasangan kunci
<a name="create-save-key-pair"></a>

Contoh ini menunjukkan kepada Anda cara menggunakan AWS SDK untuk .NET to create a key pair. Aplikasi ini mengambil nama untuk key pair baru dan nama file PEM (dengan ekstensi “.pem”). Ini menciptakan keypair, menulis kunci pribadi ke file PEM, dan kemudian menampilkan semua pasangan kunci yang tersedia. Jika Anda tidak memberikan argumen baris perintah, aplikasi hanya menampilkan semua pasangan kunci yang tersedia.

Bagian berikut menyediakan cuplikan dari contoh ini. [Kode lengkap untuk contoh](#create-save-key-pair-complete-code) ditampilkan setelah itu, dan dapat dibangun dan dijalankan apa adanya.

**Topics**
+ [Buat pasangan kunci](#create-save-key-pair-create)
+ [Tampilkan pasangan kunci yang tersedia](#create-save-key-pair-display)
+ [Kode lengkap](#create-save-key-pair-complete-code)
+ [Pertimbangan tambahan](#create-save-key-pair-additional)

## Buat pasangan kunci
<a name="create-save-key-pair-create"></a>

Cuplikan berikut membuat key pair dan kemudian menyimpan kunci pribadi ke file PEM yang diberikan.

Contoh [di akhir topik ini](#create-save-key-pair-complete-code) menunjukkan cuplikan ini digunakan.

```
    //
    // Method to create a key pair and save the key material in a PEM file
    private static async Task CreateKeyPair(
      IAmazonEC2 ec2Client, string keyPairName, string pemFileName)
    {
      // Create the key pair
      CreateKeyPairResponse response =
        await ec2Client.CreateKeyPairAsync(new CreateKeyPairRequest{
          KeyName = keyPairName
        });
      Console.WriteLine($"\nCreated new key pair: {response.KeyPair.KeyName}");

      // Save the private key in a PEM file
      using (var s = new FileStream(pemFileName, FileMode.Create))
      using (var writer = new StreamWriter(s))
      {
        writer.WriteLine(response.KeyPair.KeyMaterial);
      }
    }
```

## Tampilkan pasangan kunci yang tersedia
<a name="create-save-key-pair-display"></a>

Cuplikan berikut menampilkan daftar pasangan kunci yang tersedia.

Contoh [di akhir topik ini](#create-save-key-pair-complete-code) menunjukkan cuplikan ini digunakan.

```
    //
    // Method to show the key pairs that are available
    private static async Task EnumerateKeyPairs(IAmazonEC2 ec2Client)
    {
      DescribeKeyPairsResponse response = await ec2Client.DescribeKeyPairsAsync();
      Console.WriteLine("Available key pairs:");
      foreach (KeyPairInfo item in response.KeyPairs)
        Console.WriteLine($"  {item.KeyName}");
    }
```

## Kode lengkap
<a name="create-save-key-pair-complete-code"></a>

Bagian ini menunjukkan referensi yang relevan dan kode lengkap untuk contoh ini.

### Referensi SDK
<a name="w2aac19c15c17c15c11c19b5b1"></a>

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

Elemen pemrograman:
+ [Namespace Amazon.EC2](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/NEC2.html)

  [EC2Klien Kelas Amazon](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TEC2Client.html)
+ [Namespace Amazon.EC2.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/NEC2Model.html)

  Kelas [CreateKeyPairRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TCreateKeyPairRequest.html)

  Kelas [CreateKeyPairResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TCreateKeyPairResponse.html)

  Kelas [DescribeKeyPairsResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TDescribeKeyPairsResponse.html)

  Kelas [KeyPairInfo](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TKeyPairInfo.html)

### Kodenya
<a name="w2aac19c15c17c15c11c19b7b1"></a>

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

namespace EC2CreateKeyPair
{
  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // Class to create and store a key pair
  class Program
  {
    static async Task Main(string[] args)
    {
      // Create the EC2 client
      var ec2Client = new AmazonEC2Client();

      // Parse the command line and show help if necessary
      var parsedArgs = CommandLine.Parse(args);
      if(parsedArgs.Count == 0)
      {
        // In the case of no command-line arguments,
        // just show help and the existing key pairs
        PrintHelp();
        Console.WriteLine("\nNo arguments specified.");
        Console.Write(
          "Do you want to see a list of the existing key pairs? ((y) or n): ");
        string response = Console.ReadLine();
        if((string.IsNullOrEmpty(response)) || (response.ToLower() == "y"))
          await EnumerateKeyPairs(ec2Client);
        return;
      }

      // Get the application arguments from the parsed list
      string keyPairName =
        CommandLine.GetArgument(parsedArgs, null, "-k", "--keypair-name");
      string pemFileName =
        CommandLine.GetArgument(parsedArgs, null, "-p", "--pem-filename");
      if(string.IsNullOrEmpty(keyPairName))
        CommandLine.ErrorExit("\nNo key pair name specified." +
          "\nRun the command with no arguments to see help.");
      if(string.IsNullOrEmpty(pemFileName) || !pemFileName.EndsWith(".pem"))
        CommandLine.ErrorExit("\nThe PEM filename is missing or incorrect." +
          "\nRun the command with no arguments to see help.");

      // Create the key pair
      await CreateKeyPair(ec2Client, keyPairName, pemFileName);
      await EnumerateKeyPairs(ec2Client);
    }


    //
    // Method to create a key pair and save the key material in a PEM file
    private static async Task CreateKeyPair(
      IAmazonEC2 ec2Client, string keyPairName, string pemFileName)
    {
      // Create the key pair
      CreateKeyPairResponse response =
        await ec2Client.CreateKeyPairAsync(new CreateKeyPairRequest{
          KeyName = keyPairName
        });
      Console.WriteLine($"\nCreated new key pair: {response.KeyPair.KeyName}");

      // Save the private key in a PEM file
      using (var s = new FileStream(pemFileName, FileMode.Create))
      using (var writer = new StreamWriter(s))
      {
        writer.WriteLine(response.KeyPair.KeyMaterial);
      }
    }


    //
    // Method to show the key pairs that are available
    private static async Task EnumerateKeyPairs(IAmazonEC2 ec2Client)
    {
      DescribeKeyPairsResponse response = await ec2Client.DescribeKeyPairsAsync();
      Console.WriteLine("Available key pairs:");
      foreach (KeyPairInfo item in response.KeyPairs)
        Console.WriteLine($"  {item.KeyName}");
    }


    //
    // Command-line help
    private static void PrintHelp()
    {
      Console.WriteLine(
        "\nUsage: EC2CreateKeyPair -k <keypair-name> -p <pem-filename>" +
        "\n  -k, --keypair-name: The name you want to assign to the key pair." +
        "\n  -p, --pem-filename: The name of the PEM file to create, with a \".pem\" extension.");
    }
  }


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

}
```

## Pertimbangan tambahan
<a name="create-save-key-pair-additional"></a>
+ Setelah Anda menjalankan contoh, Anda dapat melihat key pair baru di konsol [Amazon EC2](https://console.aws.amazon.com/ec2/#KeyPairs).
+ Ketika Anda membuat key pair, Anda harus menyimpan kunci pribadi yang dikembalikan karena Anda tidak dapat mengambil kunci pribadi nanti.

# Menghapus pasangan kunci
<a name="delete-key-pairs"></a>

Contoh ini menunjukkan kepada Anda cara menggunakan AWS SDK untuk .NET to delete a key pair. Aplikasi ini mengambil nama key pair. Ini menghapus key pair dan kemudian menampilkan semua pasangan kunci yang tersedia. Jika Anda tidak memberikan argumen baris perintah, aplikasi hanya menampilkan semua pasangan kunci yang tersedia.

Bagian berikut menyediakan cuplikan dari contoh ini. [Kode lengkap untuk contoh](#delete-key-pairs-complete-code) ditampilkan setelah itu, dan dapat dibangun dan dijalankan apa adanya.

**Topics**
+ [Hapus key pair](#delete-key-pairs-create)
+ [Tampilkan pasangan kunci yang tersedia](#delete-key-pairs-display)
+ [Kode lengkap](#delete-key-pairs-complete-code)

## Hapus key pair
<a name="delete-key-pairs-create"></a>

Cuplikan berikut menghapus key pair.

Contoh [di akhir topik ini](#delete-key-pairs-complete-code) menunjukkan cuplikan ini digunakan.

```
    //
    // Method to delete a key pair
    private static async Task DeleteKeyPair(IAmazonEC2 ec2Client, string keyName)
    {
      await ec2Client.DeleteKeyPairAsync(new DeleteKeyPairRequest{
        KeyName = keyName});
      Console.WriteLine($"\nKey pair {keyName} has been deleted (if it existed).");
    }
```

## Tampilkan pasangan kunci yang tersedia
<a name="delete-key-pairs-display"></a>

Cuplikan berikut menampilkan daftar pasangan kunci yang tersedia.

Contoh [di akhir topik ini](#delete-key-pairs-complete-code) menunjukkan cuplikan ini digunakan.

```
    //
    // Method to show the key pairs that are available
    private static async Task EnumerateKeyPairs(IAmazonEC2 ec2Client)
    {
      DescribeKeyPairsResponse response = await ec2Client.DescribeKeyPairsAsync();
      Console.WriteLine("Available key pairs:");
      foreach (KeyPairInfo item in response.KeyPairs)
        Console.WriteLine($"  {item.KeyName}");
    }
```

## Kode lengkap
<a name="delete-key-pairs-complete-code"></a>

Bagian ini menunjukkan referensi yang relevan dan kode lengkap untuk contoh ini.

### Referensi SDK
<a name="w2aac19c15c17c15c13c19b5b1"></a>

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

Elemen pemrograman:
+ [Namespace Amazon.EC2](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/NEC2.html)

  [EC2Klien Kelas Amazon](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TEC2Client.html)
+ [Namespace Amazon.EC2.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/NEC2Model.html)

  Kelas [https://docs.aws.amazon.com/sdkfornet/v3/apidocs/](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/)

  Kelas [DescribeKeyPairsResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TDescribeKeyPairsResponse.html)

  Kelas [KeyPairInfo](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TKeyPairInfo.html)

### Kodenya
<a name="w2aac19c15c17c15c13c19b7b1"></a>

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

namespace EC2DeleteKeyPair
{
  class Program
  {
    static async Task Main(string[] args)
    {
      // Create the EC2 client
      var ec2Client = new AmazonEC2Client();

      if(args.Length == 1)
      {
        // Delete a key pair (if it exists)
        await DeleteKeyPair(ec2Client, args[0]);

        // Display the key pairs that are left
        await EnumerateKeyPairs(ec2Client);
      }
      else
      {
        Console.WriteLine("\nUsage: EC2DeleteKeyPair keypair-name");
        Console.WriteLine("  keypair-name - The name of the key pair you want to delete.");
        Console.WriteLine("\nNo arguments specified.");
        Console.Write(
          "Do you want to see a list of the existing key pairs? ((y) or n): ");
        string response = Console.ReadLine();
        if((string.IsNullOrEmpty(response)) || (response.ToLower() == "y"))
          await EnumerateKeyPairs(ec2Client);
      }
    }


    //
    // Method to delete a key pair
    private static async Task DeleteKeyPair(IAmazonEC2 ec2Client, string keyName)
    {
      await ec2Client.DeleteKeyPairAsync(new DeleteKeyPairRequest{
        KeyName = keyName});
      Console.WriteLine($"\nKey pair {keyName} has been deleted (if it existed).");
    }


    //
    // Method to show the key pairs that are available
    private static async Task EnumerateKeyPairs(IAmazonEC2 ec2Client)
    {
      DescribeKeyPairsResponse response = await ec2Client.DescribeKeyPairsAsync();
      Console.WriteLine("Available key pairs:");
      foreach (KeyPairInfo item in response.KeyPairs)
        Console.WriteLine($"  {item.KeyName}");
    }
  }
}
```

# Melihat Wilayah Amazon EC2 dan Availability Zone
<a name="using-regions-and-availability-zones"></a>

Amazon EC2 di-host di beberapa lokasi di seluruh dunia. Lokasi ini terdiri dari Wilayah dan Zona Ketersediaan . Setiap Wilayah adalah wilayah geografis terpisah yang memiliki beberapa lokasi terisolasi yang dikenal sebagai Availability Zone.

Untuk membaca lebih lanjut tentang Wilayah dan Availability Zone, lihat [Wilayah dan Zona](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html) di [Panduan Pengguna Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/).

Contoh ini menunjukkan kepada Anda cara menggunakan AWS SDK untuk .NET untuk mendapatkan detail tentang Wilayah dan Availability Zone yang terkait dengan klien EC2. Aplikasi ini menampilkan daftar Wilayah dan Availability Zone yang tersedia untuk klien EC2.

## Referensi SDK
<a name="w2aac19c15c17c17b9b1"></a>

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

Elemen pemrograman:
+ [Namespace Amazon.EC2](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/NEC2.html)

  [EC2Klien Kelas Amazon](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TEC2Client.html)
+ [Namespace Amazon.EC2.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/NEC2Model.html)

  Kelas [DescribeAvailabilityZonesResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TDescribeAvailabilityZonesResponse.html)

  Kelas [DescribeRegionsResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TDescribeRegionsResponse.html)

  Kelas [AvailabilityZone](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TAvailabilityZone.html)

  [Wilayah](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TRegion.html) Kelas

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

namespace EC2RegionsAndZones
{
  class Program
  {
    static async Task Main(string[] args)
    {
      Console.WriteLine(
        "Finding the Regions and Availability Zones available to an EC2 client...");

      // Create the EC2 client
      var ec2Client = new AmazonEC2Client();

      // Display the Regions and Availability Zones
      await DescribeRegions(ec2Client);
      await DescribeAvailabilityZones(ec2Client);
    }


    //
    // Method to display Regions
    private static async Task DescribeRegions(IAmazonEC2 ec2Client)
    {
      Console.WriteLine("\nRegions that are enabled for the EC2 client:");
      DescribeRegionsResponse response = await ec2Client.DescribeRegionsAsync();
      foreach (Region region in response.Regions)
        Console.WriteLine(region.RegionName);
    }


    //
    // Method to display Availability Zones
    private static async Task DescribeAvailabilityZones(IAmazonEC2 ec2Client)
    {
      Console.WriteLine("\nAvailability Zones for the EC2 client's region:");
      DescribeAvailabilityZonesResponse response =
        await ec2Client.DescribeAvailabilityZonesAsync();
      foreach (AvailabilityZone az in response.AvailabilityZones)
        Console.WriteLine(az.ZoneName);
    }
  }
}
```

# Bekerja dengan instans Amazon EC2
<a name="how-to-ec2"></a>

Anda dapat menggunakan AWS SDK untuk .NET untuk mengontrol instans Amazon EC2 dengan operasi seperti membuat, memulai, dan mengakhiri. Topik di bagian ini memberikan beberapa contoh bagaimana melakukan ini. Untuk membaca selengkapnya tentang instans EC2, lihat instans [Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Instances.html) di Panduan Pengguna Amazon [EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/).

Untuk informasi tentang APIs dan prasyarat, lihat bagian induk (). [Bekerja dengan Amazon EC2](ec2-apis-intro.md)

**Topics**
+ [Meluncurkan instans EC2](run-instance.md)
+ [Mengakhiri instans EC2](terminate-instance.md)

# Meluncurkan instans Amazon EC2
<a name="run-instance"></a>

Contoh ini menunjukkan kepada Anda cara menggunakan AWS SDK untuk .NET untuk meluncurkan satu atau lebih instans Amazon EC2 yang dikonfigurasi secara identik dari Amazon Machine Image (AMI) yang sama. Menggunakan [beberapa input](#run-instance-gather) yang Anda berikan, aplikasi meluncurkan instans EC2 dan kemudian memonitor instance hingga keluar dari status “Tertunda”.

Saat instans EC2 Anda berjalan, Anda dapat menghubungkannya dari jarak jauh, seperti yang dijelaskan dalam. [(opsional) Connect ke instance](#connect-to-instance)

**Awas**  
EC2-Classic sudah tidak digunakan lagi pada 15 Agustus 2022. Kami menyarankan Anda bermigrasi dari EC2-Classic ke VPC. Untuk informasi lebih lanjut, lihat posting blog [EC2-Classic Networking is Retiring - Inilah Cara Mempersiapkan](https://aws.amazon.com/blogs/aws/ec2-classic-is-retiring-heres-how-to-prepare/).

Bagian berikut menyediakan cuplikan dan informasi lain untuk contoh ini. [Kode lengkap untuk contoh](#run-instance-complete-code) ditampilkan setelah cuplikan, dan dapat dibangun dan dijalankan apa adanya.

**Topics**
+ [Kumpulkan apa yang Anda butuhkan](#run-instance-gather)
+ [Luncurkan sebuah instans](#run-instance-launch)
+ [Pantau instance](#run-instance-monitor)
+ [Kode lengkap](#run-instance-complete-code)
+ [Pertimbangan tambahan](#run-instance-additional)
+ [(opsional) Connect ke instance](#connect-to-instance)
+ [Bersihkan](#run-instance-cleanup)

## Kumpulkan apa yang Anda butuhkan
<a name="run-instance-gather"></a>

Untuk meluncurkan instans EC2, Anda memerlukan beberapa hal.
+ [VPC](https://docs.aws.amazon.com/vpc/latest/userguide/) tempat instance akan diluncurkan. Jika itu adalah instance Windows dan Anda akan menghubungkannya melalui RDP, VPC kemungkinan besar harus memiliki gateway internet yang terpasang padanya, serta entri untuk gateway internet di tabel rute. Untuk informasi lebih lanjut, lihat [Gateway internet](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Internet_Gateway.html) di *Panduan Pengguna Amazon VPC*.
+ ID subnet yang ada di VPC tempat instance akan diluncurkan. Cara mudah untuk menemukan atau membuat ini adalah dengan masuk ke [konsol VPC Amazon](https://console.aws.amazon.com/vpc/home#subnets), tetapi Anda juga dapat memperolehnya secara terprogram dengan menggunakan metode dan. [CreateSubnetAsync[DescribeSubnetsAsync](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/MEC2DescribeSubnetsAsyncDescribeSubnetsRequestCancellationToken.html)](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/MEC2CreateSubnetAsyncCreateSubnetRequestCancellationToken.html)
**catatan**  
Jika Anda tidak menyediakan parameter ini, instance baru akan diluncurkan di VPC default untuk akun Anda.
+ ID grup keamanan yang ada milik VPC tempat instance akan diluncurkan. Untuk informasi selengkapnya, lihat [Bekerja dengan grup keamanan di Amazon EC2](security-groups.md).
+ Jika Anda ingin terhubung ke instance baru, grup keamanan yang disebutkan sebelumnya harus memiliki aturan masuk yang sesuai yang memungkinkan lalu lintas SSH pada port 22 (instance Linux) atau lalu lintas RDP pada port 3389 (instance Windows). Untuk informasi tentang cara melakukan ini[Memperbarui grup keamanan](authorize-ingress.md), lihat, termasuk [Pertimbangan tambahan](authorize-ingress.md#authorize-ingress-additional) mendekati akhir topik itu.
+ Amazon Machine Image (AMI) yang akan digunakan untuk membuat instance. Untuk selengkapnya AMIs, lihat [Gambar Mesin Amazon (AMIs)](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html) di [Panduan Pengguna Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/). Secara khusus, lihat [Menemukan AMI](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/finding-an-ami.html) dan [Dibagikan AMIs](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/sharing-amis.html).
+ Nama key pair EC2 yang ada, yang digunakan untuk terhubung ke instance baru. Untuk informasi selengkapnya, lihat [Bekerja dengan pasangan kunci Amazon EC2](key-pairs.md).
+ Nama file PEM yang berisi kunci pribadi dari key pair EC2 yang disebutkan sebelumnya. File PEM digunakan saat Anda [terhubung dari jarak jauh](#connect-to-instance) ke instance.

## Luncurkan sebuah instans
<a name="run-instance-launch"></a>

Cuplikan berikut meluncurkan instance EC2.

Contoh di [dekat akhir topik ini](#run-instance-complete-code) menunjukkan cuplikan ini digunakan.

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

## Pantau instance
<a name="run-instance-monitor"></a>

Cuplikan berikut memonitor instance hingga keluar dari status “Tertunda”.

Contoh di [dekat akhir topik ini](#run-instance-complete-code) menunjukkan cuplikan ini digunakan.

Lihat [InstanceState](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TInstanceState.html)kelas untuk nilai valid dari `Instance.State.Code` properti.

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

## Kode lengkap
<a name="run-instance-complete-code"></a>

Bagian ini menunjukkan referensi yang relevan dan kode lengkap untuk contoh ini.

### Referensi SDK
<a name="w2aac19c15c17c19b9c27b5b1"></a>

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

Elemen pemrograman:
+ [Namespace Amazon.EC2](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/NEC2.html)

  [EC2Klien Kelas Amazon](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TEC2Client.html)

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

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

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

  [Instance](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TInstance.html) Kelas

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

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

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

### Kodenya
<a name="w2aac19c15c17c19b9c27b7b1"></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);
    }
  }

}
```

## Pertimbangan tambahan
<a name="run-instance-additional"></a>
+ Saat memeriksa status instans EC2, Anda dapat menambahkan filter ke `Filter` properti [DescribeInstancesRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TDescribeInstancesRequest.html)objek. Dengan menggunakan teknik ini, Anda dapat membatasi permintaan ke instance tertentu; misalnya, instance dengan tag tertentu yang ditentukan pengguna.
+ Untuk singkatnya, beberapa properti diberi nilai tipikal. Salah satu atau semua properti ini dapat ditentukan secara terprogram atau dengan masukan pengguna.
+ Nilai yang dapat Anda gunakan untuk `MaxCount` properti `MinCount` dan [RunInstancesRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TRunInstancesRequest.html)objek ditentukan oleh Zona Ketersediaan target dan jumlah maksimum instance yang diizinkan untuk jenis instans. Untuk informasi selengkapnya, lihat [Berapa banyak instans yang dapat saya jalankan di Amazon](https://aws.amazon.com/ec2/faqs/#How_many_instances_can_I_run_in_Amazon_EC2) EC2 di FAQ Umum Amazon EC2.
+ Jika Anda ingin menggunakan jenis instance yang berbeda dari contoh ini, ada beberapa jenis instance untuk dipilih. Untuk informasi selengkapnya, lihat [jenis instans Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) di Panduan Pengguna [Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/). Lihat juga [Detail Jenis Instance](https://aws.amazon.com/ec2/instance-types/) [dan Penjelajah Jenis Instance](https://aws.amazon.com/ec2/instance-explorer/).
+ Anda juga dapat melampirkan [peran IAM](net-dg-hosm.md) ke instance saat meluncurkannya. Untuk melakukannya, buat [IamInstanceProfileSpecification](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TIamInstanceProfileSpecification.html)objek yang `Name` propertinya disetel ke nama peran IAM. Kemudian tambahkan objek itu ke `IamInstanceProfile` properti [RunInstancesRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TRunInstancesRequest.html)objek.
**catatan**  
Untuk meluncurkan instans EC2 yang memiliki peran IAM terpasang, konfigurasi pengguna IAM harus menyertakan izin tertentu. Untuk informasi selengkapnya tentang izin yang diperlukan, lihat [Memberi izin pengguna untuk meneruskan peran IAM ke instans](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html#permission-to-pass-iam-roles) di Panduan Pengguna [Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/).

## (opsional) Connect ke instance
<a name="connect-to-instance"></a>

Setelah sebuah instance berjalan, Anda dapat menghubungkannya dari jarak jauh dengan menggunakan klien jarak jauh yang sesuai. Untuk instance Linux dan Windows, Anda memerlukan alamat IP publik instans atau nama DNS publik. Anda juga membutuhkan yang berikut ini.

**Untuk instance Linux**

Anda dapat menggunakan klien SSH untuk terhubung ke instance Linux Anda. Pastikan bahwa grup keamanan yang Anda gunakan saat meluncurkan instans memungkinkan lalu lintas SSH pada port 22, seperti yang dijelaskan dalam[Memperbarui grup keamanan](authorize-ingress.md).

Anda juga memerlukan bagian pribadi dari key pair yang Anda gunakan untuk meluncurkan instance; yaitu, file PEM.

Untuk informasi selengkapnya, lihat [Connect ke instans Linux Anda](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/connect-to-linux-instance.html) di Panduan Pengguna Amazon EC2.

**Untuk contoh Windows**

Anda dapat menggunakan klien RDP untuk terhubung ke instans Anda. Pastikan bahwa grup keamanan yang Anda gunakan saat meluncurkan instans memungkinkan lalu lintas RDP pada port 3389, seperti yang dijelaskan dalam. [Memperbarui grup keamanan](authorize-ingress.md)

Anda juga memerlukan kata sandi Administrator. Anda dapat memperoleh ini dengan menggunakan kode contoh berikut, yang memerlukan ID instance dan bagian pribadi dari key pair yang digunakan untuk meluncurkan instance; yaitu, file PEM.

Untuk informasi selengkapnya, lihat [Connect ke instans Windows Anda](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/connecting_to_windows_instance.html) di Panduan Pengguna Amazon EC2.

**Awas**  
Kode contoh ini mengembalikan kata sandi Administrator plaintext untuk instance Anda.

### Referensi SDK
<a name="w2aac19c15c17c19b9c35c23b1"></a>

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

Elemen pemrograman:
+ [Namespace Amazon.EC2](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/NEC2.html)

  [EC2Klien Kelas Amazon](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TEC2Client.html)
+ [Namespace Amazon.EC2.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/NEC2Model.html)

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

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

### Kodenya
<a name="w2aac19c15c17c19b9c35c25b1"></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);
    }
  }

}
```

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

Ketika Anda tidak lagi membutuhkan instans EC2 Anda, pastikan untuk menghentikannya, seperti yang dijelaskan dalam. [Mengakhiri instans Amazon EC2](terminate-instance.md)

# Mengakhiri instans Amazon EC2
<a name="terminate-instance"></a>

Jika Anda tidak lagi membutuhkan satu atau lebih instans Amazon EC2, Anda dapat menghentikannya.

Contoh ini menunjukkan cara menggunakan instans AWS SDK untuk .NET untuk mengakhiri EC2. Dibutuhkan contoh ID sebagai input.

## Referensi SDK
<a name="w2aac19c15c17c19c11b7b1"></a>

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

Elemen pemrograman:
+ [Namespace Amazon.EC2](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/NEC2.html)

  [EC2Klien Kelas Amazon](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TEC2Client.html)
+ [Namespace Amazon.EC2.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/NEC2Model.html)

  Kelas [TerminateInstancesRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TTerminateInstancesRequest.html)

  Kelas [TerminateInstancesResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TTerminateInstancesResponse.html)

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

namespace EC2TerminateInstance
{
  class Program
  {
    static async Task Main(string[] args)
    {
      if((args.Length == 1) && (args[0].StartsWith("i-")))
      {
        // Terminate the instance
        var ec2Client = new AmazonEC2Client();
        await TerminateInstance(ec2Client, args[0]);
      }
      else
      {
        Console.WriteLine("\nCommand-line argument missing or incorrect.");
        Console.WriteLine("\nUsage: EC2TerminateInstance instance-ID");
        Console.WriteLine("  instance-ID - The EC2 instance you want to terminate.");
        return;
      }
    }

    //
    // Method to terminate an EC2 instance
    private static async Task TerminateInstance(IAmazonEC2 ec2Client, string instanceID)
    {
      var request = new TerminateInstancesRequest{
        InstanceIds = new List<string>() { instanceID }};
      TerminateInstancesResponse response =
        await ec2Client.TerminateInstancesAsync(new TerminateInstancesRequest{
          InstanceIds = new List<string>() { instanceID }
        });
      foreach (InstanceStateChange item in response.TerminatingInstances)
      {
        Console.WriteLine("Terminated instance: " + item.InstanceId);
        Console.WriteLine("Instance state: " + item.CurrentState.Name);
      }
    }
  }
}
```

Setelah Anda menjalankan contoh, sebaiknya masuk ke [konsol Amazon EC2](https://console.aws.amazon.com/ec2/) untuk memverifikasi bahwa [instans EC2 telah dihentikan](https://console.aws.amazon.com/ec2/v2/home#Instances).

# Tutorial Instans Spot Amazon EC2
<a name="how-to-spot-instances"></a>

Tutorial ini menunjukkan cara menggunakan AWS SDK untuk .NET untuk mengelola Instans Spot Amazon EC2.

## Ikhtisar
<a name="tutor-spot-net-overview"></a>

Instans Spot memungkinkan Anda meminta kapasitas Amazon EC2 yang tidak digunakan dengan harga kurang dari harga Sesuai Permintaan. Ini secara signifikan dapat menurunkan biaya EC2 Anda untuk aplikasi yang dapat terganggu.

Berikut ini adalah ringkasan tingkat tinggi tentang bagaimana Instans Spot diminta dan digunakan.

1. Buat permintaan Instans Spot, tentukan harga maksimum yang bersedia Anda bayar.

1. Ketika permintaan terpenuhi, jalankan instance seperti yang Anda lakukan pada instans Amazon EC2 lainnya.

1. Jalankan instance selama yang Anda inginkan dan kemudian hentikan, kecuali jika *Harga Spot* berubah sedemikian rupa sehingga instance dihentikan untuk Anda.

1. Bersihkan permintaan Instans Spot saat Anda tidak lagi membutuhkannya sehingga Instans Spot tidak lagi dibuat.

Ini telah menjadi ikhtisar tingkat yang sangat tinggi dari Instans Spot. Untuk mendapatkan pemahaman yang lebih baik tentang Instans Spot, lihat [Instans Spot](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-spot-instances.html) di Panduan Pengguna [Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/).

## Tentang tutorial ini
<a name="about-spot-instances-tutorial"></a>

Ketika Anda mengikuti tutorial ini, Anda menggunakan AWS SDK untuk .NET untuk melakukan hal berikut:
+ Membuat permintaan Instans Spot
+ Tentukan kapan permintaan Instans Spot telah dipenuhi
+ Batalkan permintaan Instans Spot
+ Mengakhiri instance terkait

Bagian berikut menyediakan cuplikan dan informasi lain untuk contoh ini. [Kode lengkap untuk contoh](#tutor-spot-net-main) ditampilkan setelah cuplikan, dan dapat dibangun dan dijalankan apa adanya.

**Topics**
+ [Ikhtisar](#tutor-spot-net-overview)
+ [Tentang tutorial ini](#about-spot-instances-tutorial)
+ [Prasyarat](#tutor-spot-net-prereq)
+ [Kumpulkan apa yang Anda butuhkan](#tutor-spot-net-gather)
+ [Membuat permintaan Instans Spot](#tutor-spot-net-submit)
+ [Tentukan status permintaan Instans Spot Anda](#tutor-spot-net-request-state)
+ [Bersihkan permintaan Instans Spot Anda](#tutor-spot-net-clean-up-request)
+ [Bersihkan Instans Spot Anda](#tutor-spot-net-clean-up-instance)
+ [Kode lengkap](#tutor-spot-net-main)
+ [Pertimbangan tambahan](#tutor-spot-net-additional)

## Prasyarat
<a name="tutor-spot-net-prereq"></a>

Untuk informasi tentang APIs dan prasyarat, lihat bagian induk (). [Bekerja dengan Amazon EC2](ec2-apis-intro.md)

## Kumpulkan apa yang Anda butuhkan
<a name="tutor-spot-net-gather"></a>

Untuk membuat permintaan Instans Spot, Anda memerlukan beberapa hal. 
+ Jumlah instance dan jenis instance-nya. Ada beberapa jenis contoh untuk dipilih. Untuk informasi selengkapnya, lihat [jenis instans Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) di Panduan Pengguna [Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/). Lihat juga [Detail Jenis Instance](https://aws.amazon.com/ec2/instance-types/) [dan Penjelajah Jenis Instance](https://aws.amazon.com/ec2/instance-explorer/).

  Nomor default untuk tutorial ini adalah 1.
+ Amazon Machine Image (AMI) yang akan digunakan untuk membuat instance. Untuk selengkapnya AMIs, lihat [Gambar Mesin Amazon (AMIs)](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html) di [Panduan Pengguna Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/). Secara khusus, lihat [Menemukan AMI](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/finding-an-ami.html) dan [Dibagikan AMIs](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/sharing-amis.html).
+ Harga maksimum yang bersedia Anda bayar per jam contoh. Anda dapat melihat harga untuk semua jenis instans (untuk Instans Sesuai Permintaan dan Instans Spot) di halaman [harga Amazon](https://aws.amazon.com/ec2/pricing/) EC2. Harga default untuk tutorial ini dijelaskan nanti.
+ Jika Anda ingin terhubung dari jarak jauh ke sebuah instans, grup keamanan dengan konfigurasi dan sumber daya yang sesuai. Ini dijelaskan dalam [Bekerja dengan grup keamanan di Amazon EC2](security-groups.md) dan informasi tentang [mengumpulkan apa yang Anda butuhkan](run-instance.md#run-instance-gather) dan [menghubungkan ke instance](run-instance.md#connect-to-instance) di[Meluncurkan instans Amazon EC2](run-instance.md). Untuk mempermudah, tutorial ini menggunakan grup keamanan bernama **default** yang dimiliki semua AWS akun yang lebih baru.

Ada banyak cara untuk mendekati permintaan Instans Spot. Berikut ini adalah strategi umum:
+ Buat permintaan yang pasti biayanya kurang dari harga sesuai permintaan.
+ Buat permintaan berdasarkan nilai perhitungan yang dihasilkan.
+ Buat permintaan untuk memperoleh kapasitas komputasi secepat mungkin.

Penjelasan berikut mengacu pada [riwayat harga Instans Spot](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-spot-instances-history.html) di Panduan Pengguna [Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/).

### Mengurangi biaya di bawah On-Demand
<a name="reduce-cost"></a>

Anda memiliki pekerjaan pemrosesan batch yang akan memakan waktu beberapa jam atau hari untuk dijalankan. Namun, Anda fleksibel sehubungan dengan kapan dimulai dan berakhir. Anda ingin melihat apakah Anda dapat menyelesaikannya dengan harga kurang dari biaya Instans Sesuai Permintaan.

Anda memeriksa riwayat Harga Spot untuk jenis instans dengan menggunakan konsol Amazon EC2 atau Amazon EC2 API. Setelah menganalisis riwayat harga untuk jenis instans yang diinginkan di Availability Zone tertentu, Anda memiliki dua pendekatan alternatif untuk permintaan Anda:
+ Tentukan permintaan di ujung atas kisaran Harga Spot, yang masih di bawah harga Sesuai Permintaan, mengantisipasi bahwa permintaan Instans Spot satu kali Anda kemungkinan besar akan terpenuhi dan berjalan untuk waktu komputasi yang cukup berturut-turut untuk menyelesaikan pekerjaan.
+ Tentukan permintaan di ujung bawah kisaran harga, dan rencanakan untuk menggabungkan banyak instance yang diluncurkan dari waktu ke waktu melalui permintaan persisten. Contoh akan berjalan cukup lama, secara agregat, untuk menyelesaikan pekerjaan dengan biaya total yang lebih rendah.

### Bayar tidak lebih dari nilai hasilnya
<a name="value-of-result"></a>

Anda memiliki pekerjaan pemrosesan data untuk dijalankan. Anda memahami nilai hasil pekerjaan dengan cukup baik untuk mengetahui berapa nilainya dalam hal biaya komputasi.

Setelah menganalisis riwayat Harga Spot untuk jenis instans Anda, Anda memilih harga di mana biaya waktu komputasi tidak lebih dari nilai hasil pekerjaan. Anda membuat permintaan persisten dan mengizinkannya berjalan sebentar-sebentar karena Harga Spot berfluktuasi pada atau di bawah permintaan Anda.

### Memperoleh kapasitas komputasi dengan cepat
<a name="acquire-quickly"></a>

Anda memiliki kebutuhan jangka pendek yang tidak terduga untuk kapasitas tambahan yang tidak tersedia melalui Instans Sesuai Permintaan. Setelah menganalisis riwayat Harga Spot untuk jenis instans Anda, Anda memilih harga di atas harga historis tertinggi untuk meningkatkan kemungkinan permintaan Anda akan terpenuhi dengan cepat dan terus menghitung hingga selesai.

Setelah Anda mengumpulkan apa yang Anda butuhkan dan memilih strategi, Anda siap untuk meminta Instans Spot. Untuk tutorial ini, harga spot-instance maksimum default ditetapkan sama dengan harga On-Demand (yaitu \$10,003 untuk tutorial ini). Menetapkan harga dengan cara ini memaksimalkan kemungkinan permintaan akan dipenuhi.

## Membuat permintaan Instans Spot
<a name="tutor-spot-net-submit"></a>

Cuplikan berikut menunjukkan cara membuat permintaan Instance Spot dengan elemen yang Anda kumpulkan sebelumnya.

Contoh [di akhir topik ini](#tutor-spot-net-main) menunjukkan cuplikan ini digunakan.

```
    //
    // Method to create a Spot Instance request
    private static async Task<SpotInstanceRequest> CreateSpotInstanceRequest(
      IAmazonEC2 ec2Client, string amiId, string securityGroupName,
      InstanceType instanceType, string spotPrice, int instanceCount)
    {
      var launchSpecification = new LaunchSpecification{
        ImageId = amiId,
        InstanceType = instanceType
      };
      launchSpecification.SecurityGroups.Add(securityGroupName);
      var request = new RequestSpotInstancesRequest{
        SpotPrice = spotPrice,
        InstanceCount = instanceCount,
        LaunchSpecification = launchSpecification
      };

      RequestSpotInstancesResponse result =
        await ec2Client.RequestSpotInstancesAsync(request);
      return result.SpotInstanceRequests[0];
    }
```

Nilai penting yang dikembalikan dari metode ini adalah ID permintaan Instance Spot, yang terkandung dalam `SpotInstanceRequestId` anggota [SpotInstanceRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TSpotInstanceRequest.html)objek yang dikembalikan.

**catatan**  
Anda akan dikenakan biaya untuk Instans Spot apa pun yang diluncurkan. Untuk menghindari biaya yang tidak perlu, pastikan untuk [membatalkan permintaan apa pun](#tutor-spot-net-clean-up-request) dan [menghentikan instance apa pun](#tutor-spot-net-clean-up-instance).

## Tentukan status permintaan Instans Spot Anda
<a name="tutor-spot-net-request-state"></a>

Cuplikan berikut menunjukkan cara mendapatkan informasi tentang permintaan Instans Spot Anda. Anda dapat menggunakan informasi tersebut untuk membuat keputusan tertentu dalam kode Anda, seperti apakah akan terus menunggu permintaan Instans Spot dipenuhi.

Contoh [di akhir topik ini](#tutor-spot-net-main) menunjukkan cuplikan ini digunakan.

```
    //
    // Method to get information about a Spot Instance request, including the status,
    // instance ID, etc.
    // It gets the information for a specific request (as opposed to all requests).
    private static async Task<SpotInstanceRequest> GetSpotInstanceRequestInfo(
      IAmazonEC2 ec2Client, string requestId)
    {
      var describeRequest = new DescribeSpotInstanceRequestsRequest();
      describeRequest.SpotInstanceRequestIds.Add(requestId);

      DescribeSpotInstanceRequestsResponse describeResponse =
        await ec2Client.DescribeSpotInstanceRequestsAsync(describeRequest);
      return describeResponse.SpotInstanceRequests[0];
    }
```

Metode ini mengembalikan informasi tentang permintaan Instans Spot seperti ID instance, statusnya, dan kode status. Untuk informasi selengkapnya tentang kode status permintaan Instans Spot, lihat [Status permintaan Spot](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-bid-status.html#spot-instance-bid-status-understand) di [Panduan Pengguna Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/).

## Bersihkan permintaan Instans Spot Anda
<a name="tutor-spot-net-clean-up-request"></a>

Bila Anda tidak perlu lagi meminta Instans Spot, penting untuk membatalkan permintaan yang belum selesai untuk mencegah permintaan tersebut terpenuhi kembali. Cuplikan berikut menunjukkan cara membatalkan permintaan Instans Spot.

Contoh [di akhir topik ini](#tutor-spot-net-main) menunjukkan cuplikan ini digunakan.

```
    //
    // Method to cancel a Spot Instance request
    private static async Task CancelSpotInstanceRequest(
      IAmazonEC2 ec2Client, string requestId)
    {
      var cancelRequest = new CancelSpotInstanceRequestsRequest();
      cancelRequest.SpotInstanceRequestIds.Add(requestId);

      await ec2Client.CancelSpotInstanceRequestsAsync(cancelRequest);
    }
```

## Bersihkan Instans Spot Anda
<a name="tutor-spot-net-clean-up-instance"></a>

Untuk menghindari biaya yang tidak perlu, penting bagi Anda untuk menghentikan instans apa pun yang dimulai dari permintaan Instans Spot; hanya membatalkan permintaan Instans Spot tidak akan menghentikan instans Anda, yang berarti Anda akan terus dikenakan biaya untuk itu. Cuplikan berikut menunjukkan cara menghentikan instance setelah mendapatkan pengenal instans untuk Instance Spot yang aktif.

Contoh [di akhir topik ini](#tutor-spot-net-main) menunjukkan cuplikan ini digunakan.

```
    //
    // Method to terminate a Spot Instance
    private static async Task TerminateSpotInstance(
      IAmazonEC2 ec2Client, string requestId)
    {
      var describeRequest = new DescribeSpotInstanceRequestsRequest();
      describeRequest.SpotInstanceRequestIds.Add(requestId);

      // Retrieve the Spot Instance request to check for running instances.
      DescribeSpotInstanceRequestsResponse describeResponse =
        await ec2Client.DescribeSpotInstanceRequestsAsync(describeRequest);

      // If there are any running instances, terminate them
      if(   (describeResponse.SpotInstanceRequests[0].Status.Code
              == "request-canceled-and-instance-running")
         || (describeResponse.SpotInstanceRequests[0].State == SpotInstanceState.Active))
      {
        TerminateInstancesResponse response =
          await ec2Client.TerminateInstancesAsync(new TerminateInstancesRequest{
            InstanceIds = new List<string>(){
              describeResponse.SpotInstanceRequests[0].InstanceId } });
        foreach (InstanceStateChange item in response.TerminatingInstances)
        {
          Console.WriteLine($"\n  Terminated instance: {item.InstanceId}");
          Console.WriteLine($"  Instance state: {item.CurrentState.Name}\n");
        }
      }
    }
```

## Kode lengkap
<a name="tutor-spot-net-main"></a>

Contoh kode berikut memanggil metode yang dijelaskan sebelumnya untuk membuat dan membatalkan permintaan Instans Spot dan mengakhiri Instance Spot.

### Referensi SDK
<a name="w2aac19c15c17c21c43b5b1"></a>

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

Elemen pemrograman:
+ [Namespace Amazon.EC2](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/NEC2.html)

  [EC2Klien Kelas Amazon](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TEC2Client.html)

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

  Kelas [CancelSpotInstanceRequestsRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TCancelSpotInstanceRequestsRequest.html)

  Kelas [DescribeSpotInstanceRequestsRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TDescribeSpotInstanceRequestsRequest.html)

  Kelas [DescribeSpotInstanceRequestsResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TDescribeSpotInstanceRequestsResponse.html)

  Kelas [InstanceStateChange](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TInstanceStateChange.html)

  Kelas [LaunchSpecification](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TLaunchSpecification.html)

  Kelas [RequestSpotInstancesRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TRequestSpotInstancesRequest.html)

  Kelas [RequestSpotInstancesResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TRequestSpotInstancesResponse.html)

  Kelas [SpotInstanceRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TSpotInstanceRequest.html)

  Kelas [TerminateInstancesRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TTerminateInstancesRequest.html)

  Kelas [TerminateInstancesResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/TTerminateInstancesResponse.html)

### Kodenya
<a name="w2aac19c15c17c21c43b7b1"></a>

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

namespace EC2SpotInstanceRequests
{
  class Program
  {
    static async Task Main(string[] args)
    {
      // Some default values.
      // These could be made into command-line arguments instead.
      var instanceType = InstanceType.T1Micro;
      string securityGroupName = "default";
      string spotPrice = "0.003";
      int instanceCount = 1;

      // Parse the command line arguments
      if((args.Length != 1) || (!args[0].StartsWith("ami-")))
      {
        Console.WriteLine("\nUsage: EC2SpotInstanceRequests ami");
        Console.WriteLine("  ami: the Amazon Machine Image to use for the Spot Instances.");
        return;
      }

      // Create the Amazon EC2 client.
      var ec2Client = new AmazonEC2Client();

      // Create the Spot Instance request and record its ID
      Console.WriteLine("\nCreating spot instance request...");
      var req = await CreateSpotInstanceRequest(
        ec2Client, args[0], securityGroupName, instanceType, spotPrice, instanceCount);
      string requestId = req.SpotInstanceRequestId;

      // Wait for an EC2 Spot Instance to become active
      Console.WriteLine(
        $"Waiting for Spot Instance request with ID {requestId} to become active...");
      int wait = 1;
      var start = DateTime.Now;
      while(true)
      {
        Console.Write(".");

        // Get and check the status to see if the request has been fulfilled.
        var requestInfo = await GetSpotInstanceRequestInfo(ec2Client, requestId);
        if(requestInfo.Status.Code == "fulfilled")
        {
          Console.WriteLine($"\nSpot Instance request {requestId} " +
            $"has been fulfilled by instance {requestInfo.InstanceId}.\n");
          break;
        }

        // Wait a bit and try again, longer each time (1, 2, 4, ...)
        Thread.Sleep(wait);
        wait = wait * 2;
      }

      // Show the user how long it took to fulfill the Spot Instance request.
      TimeSpan span = DateTime.Now.Subtract(start);
      Console.WriteLine($"That took {span.TotalMilliseconds} milliseconds");

      // Perform actions here as needed.
      // For this example, simply wait for the user to hit a key.
      // That gives them a chance to look at the EC2 console to see
      // the running instance if they want to.
      Console.WriteLine("Press any key to start the cleanup...");
      Console.ReadKey(true);

      // Cancel the request.
      // Do this first to make sure that the request can't be re-fulfilled
      // once the Spot Instance has been terminated.
      Console.WriteLine("Canceling Spot Instance request...");
      await CancelSpotInstanceRequest(ec2Client, requestId);

      // Terminate the Spot Instance that's running.
      Console.WriteLine("Terminating the running Spot Instance...");
      await TerminateSpotInstance(ec2Client, requestId);

      Console.WriteLine("Done. Press any key to exit...");
      Console.ReadKey(true);
    }


    //
    // Method to create a Spot Instance request
    private static async Task<SpotInstanceRequest> CreateSpotInstanceRequest(
      IAmazonEC2 ec2Client, string amiId, string securityGroupName,
      InstanceType instanceType, string spotPrice, int instanceCount)
    {
      var launchSpecification = new LaunchSpecification{
        ImageId = amiId,
        InstanceType = instanceType
      };
      launchSpecification.SecurityGroups.Add(securityGroupName);
      var request = new RequestSpotInstancesRequest{
        SpotPrice = spotPrice,
        InstanceCount = instanceCount,
        LaunchSpecification = launchSpecification
      };

      RequestSpotInstancesResponse result =
        await ec2Client.RequestSpotInstancesAsync(request);
      return result.SpotInstanceRequests[0];
    }


    //
    // Method to get information about a Spot Instance request, including the status,
    // instance ID, etc.
    // It gets the information for a specific request (as opposed to all requests).
    private static async Task<SpotInstanceRequest> GetSpotInstanceRequestInfo(
      IAmazonEC2 ec2Client, string requestId)
    {
      var describeRequest = new DescribeSpotInstanceRequestsRequest();
      describeRequest.SpotInstanceRequestIds.Add(requestId);

      DescribeSpotInstanceRequestsResponse describeResponse =
        await ec2Client.DescribeSpotInstanceRequestsAsync(describeRequest);
      return describeResponse.SpotInstanceRequests[0];
    }


    //
    // Method to cancel a Spot Instance request
    private static async Task CancelSpotInstanceRequest(
      IAmazonEC2 ec2Client, string requestId)
    {
      var cancelRequest = new CancelSpotInstanceRequestsRequest();
      cancelRequest.SpotInstanceRequestIds.Add(requestId);

      await ec2Client.CancelSpotInstanceRequestsAsync(cancelRequest);
    }


    //
    // Method to terminate a Spot Instance
    private static async Task TerminateSpotInstance(
      IAmazonEC2 ec2Client, string requestId)
    {
      var describeRequest = new DescribeSpotInstanceRequestsRequest();
      describeRequest.SpotInstanceRequestIds.Add(requestId);

      // Retrieve the Spot Instance request to check for running instances.
      DescribeSpotInstanceRequestsResponse describeResponse =
        await ec2Client.DescribeSpotInstanceRequestsAsync(describeRequest);

      // If there are any running instances, terminate them
      if(   (describeResponse.SpotInstanceRequests[0].Status.Code
              == "request-canceled-and-instance-running")
         || (describeResponse.SpotInstanceRequests[0].State == SpotInstanceState.Active))
      {
        TerminateInstancesResponse response =
          await ec2Client.TerminateInstancesAsync(new TerminateInstancesRequest{
            InstanceIds = new List<string>(){
              describeResponse.SpotInstanceRequests[0].InstanceId } });
        foreach (InstanceStateChange item in response.TerminatingInstances)
        {
          Console.WriteLine($"\n  Terminated instance: {item.InstanceId}");
          Console.WriteLine($"  Instance state: {item.CurrentState.Name}\n");
        }
      }
    }
  }
}
```

## Pertimbangan tambahan
<a name="tutor-spot-net-additional"></a>
+ Setelah Anda menjalankan tutorial, sebaiknya masuk ke [konsol Amazon EC2](https://console.aws.amazon.com/ec2/) untuk memverifikasi bahwa [permintaan Instans Spot](https://console.aws.amazon.com/ec2/home#SpotInstances:) telah dibatalkan dan [Instans Spot telah dihentikan](https://console.aws.amazon.com/ec2/v2/home#Instances).