• 沒有找到結果。

Monitor the instance

在文檔中 AWS SDK for .NET (頁 120-126)

instanceIds.Add(item.InstanceId);

Console.WriteLine($" New instance: {item.InstanceId}");

}

return instanceIds;

}

Monitor the instance

The following snippet monitors the instance until it's out of the "Pending" state.

The example near the end of this topic (p. 115) shows this snippet in use.

See the InstanceState class for the valid values of the Instance.State.Code property.

//

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

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;

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

Amazon EC2

Console.WriteLine($" Key pair name: {i.KeyName}");

} }

Complete code

This section shows relevant references and the complete code for this example.

SDK references

NuGet packages:

• AWSSDK.EC2

Programming elements:

• Namespace Amazon.EC2 Class AmazonEC2Client Class InstanceType

• Namespace Amazon.EC2.Model Class DescribeInstancesRequest Class DescribeInstancesResponse Class Instance

Class InstanceNetworkInterfaceSpecification Class RunInstancesRequest

Class RunInstancesResponse

The code

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;

}

Amazon EC2

// 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(

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,

if(!string.IsNullOrEmpty(subnetID)) {

request.NetworkInterfaces =

new List<InstanceNetworkInterfaceSpecification>() { new InstanceNetworkInterfaceSpecification() {

// Properties specifically for EC2-Classic else

{

request.SecurityGroupIds = groupIDs;

}

return request;

Amazon EC2

}

//

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

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;

Console.WriteLine("\nNo more instances are pending.");

foreach(Instance i in responseDescribe.Reservations[0].Instances) {

Console.WriteLine($"For {i.InstanceId}:");

Amazon EC2

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>]" +

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

Amazon EC2

}

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

} } }

Additional considerations

• When checking the state of an EC2 instance, you can add a filter to the Filter property of the DescribeInstancesRequest object. Using this technique, you can limit the request to certain instances;

for example, instances with a particular user-specified tag.

• For brevity, some properties were given typical values. Any or all of these properties can instead be determined programmatically or by user input.

• The values you can use for the MinCount and MaxCount properties of the RunInstancesRequest object are determined by the target Availability Zone and the maximum number of instances you’re allowed for the instance type. For more information, see How many instances can I run in Amazon EC2 in the Amazon EC2 General FAQ.

• If you want to use a different instance type than this example, there are several instance types to choose from, which you can see in the EC2 user guide for Linux or the EC2 user guide for Windows.

• You can also attach an IAM role (p. 149) to an instance when you launch it. To do so, create an IamInstanceProfileSpecification object whose Name property is set to the name of an IAM role. Then add that object to the IamInstanceProfile property of the RunInstancesRequest object.

Note

To launch an EC2 instance that has an IAM role attached, an IAM user's configuration must include certain permissions. For more information about the required permissions, see the EC2 user guide for Linux or the EC2 user guide for Windows.

Amazon EC2

在文檔中 AWS SDK for .NET (頁 120-126)