Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to start an Amazon EC2 instance programmatically in .NET

I have been attempting to start an instance of EC2 in C# without luck.

When passing in an instance id to start the instance I get an error that the instance cannot be found despite that I am passing in an instance ID that I have obtained from the object property.

I would be most grateful for any tips or pointers with this.

like image 960
Ben White Avatar asked Sep 14 '11 17:09

Ben White


2 Answers

Amazon made huge efforts to integrate its AWS Cloud .Net SDK To VS2008 & VS 2010

  • 1 - Download and Install the AWS SDK msi
  • 2 - Create an AWS Console project, enter your credentials
    (available from your AWS Console under your login name menu on the top right corner)
  • 3 - Add the following code (see below images).
  • 4 - Your're done. It's very straightforward.
    You can check the programmatic start/stop success by refreshing your AWS Console Screen.

enter image description here

enter image description here

AmazonEC2 ec2 = AWSClientFactory.CreateAmazonEC2Client();
//Start Your Instance
ec2.StartInstances(new StartInstancesRequest().WithInstanceId("i-00000000"));
//Stop it
ec2.StopInstances(new StopInstancesRequest().WithInstanceId("i-00000000"));

You just need to replace "i-00000000" by your instance Id (available in your AWS Management Console)

Hope this helps those googling this and stumbling upon this question (as I did myself) start off quickly.
Following these simple steps via these wizards will spare you considerable headaches.

like image 119
Mehdi LAMRANI Avatar answered Oct 15 '22 14:10

Mehdi LAMRANI


Try something like this with the AWSSDK to start new instances of an "image id":

RunInstancesResponse response = Client.RunInstances(new RunInstancesRequest()
  .WithImageId(ami_id)
  .WithInstanceType(instance_type)
  .WithKeyName(YOUR_KEYPAIR_NAME)
  .WithMinCount(1)
  .WithMaxCount(max_number_of_instances)
  .WithUserData(Convert.ToBase64String(Encoding.UTF8.GetBytes(bootScript.Replace("\r", ""))))
);

(Note: The .WithUserData() is optional and is used above to pass a short shell script.)

If the call is successful the response should contain a list of instances. You can use something like this to create a list of "instance ids":

if (response.IsSetRunInstancesResult() && response.RunInstancesResult.IsSetReservation() && response.RunInstancesResult.Reservation.IsSetRunningInstance())
{
     List<string> instance_ids = new List<string>();
     foreach (RunningInstance ri in response.RunInstancesResult.Reservation.RunningInstance)
     {
          instance_ids.Add(ri.InstanceId);
     }

     // do something with instance_ids
     ...
}
like image 40
John Lemberger Avatar answered Oct 15 '22 12:10

John Lemberger