简体   繁体   中英

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.

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.

在此处输入图片说明

在此处输入图片说明

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.

Be mindful that Amazon AWS instances exist only in one region.. If your instance id i-12345 is in the EU-West-1 region, and you just make a new EC2Client and tell the client to start i-12345 it may well complain that it cannot find that instance, because the client started up in the us-east-1 region, which does not have i-12345 instance

Your call that creates the cient should specify the region, if it is not the default region (I've no idea which AWS region is default, so i specify every time):

AmazonEC2 ec2 = AWSClientFactory.CreateAmazonEC2Client(
 new Amazon.EC2.AmazonEC2Config().WithServiceURL("https://eu-west-1.ec2.amazonaws.com")
); 

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
     ...
}

try this.

var startRequest = new StartInstancesRequest
                    {
                        InstanceIds = new List<string>() { instanceId }
                    };
                bool isError = true;
                StartInstancesResponse startInstancesResponse = null;
                while (isError)
                {
                    try
                    {
                        startInstancesResponse=amazonEc2client.StartInstances(startRequest);
                        isError = false;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message + "\n" + ex.StackTrace);
                        isError = true;
                    }
                }

Ok, this is the FULL, end-to-end instructions. 1. Install AWSSDK.Core and AWSSDK.EC2 using Nuget Package Manager.
2. Then copy this whole class to your project. AccessKey and Secret are obtained in AWS IAM. You will need to ensure the user you create has "AmazonEC2FullAccess" (You can probably use a lower-level permission policy, I am just lazy here :D). region is your AW S EC2 instance region. and Instance ID can be found in the EC2 dashboard list. Simple, works perfectly... You can also write extra code to manage the response object. 3. Be mindful if you are behind a proxy, you will have to configure it (I havent included code here).

public class AWSClass : IDisposable
    {
        Amazon.EC2.AmazonEC2Client _client;

        public AWSClass(string region, string AccessKey, string Secret)
        {
            RegionEndpoint EndPoint = RegionEndpoint.GetBySystemName(region);
            Amazon.Runtime.BasicAWSCredentials Credentials = new Amazon.Runtime.BasicAWSCredentials(AccessKey, Secret);
            _client = new AmazonEC2Client(Credentials, EndPoint);
        }

        public void Dispose()
        {
            _client = null;
        }

        public void StopInstance(string InstanceID)
        {
            StopInstancesResponse response = _client.StopInstances(new StopInstancesRequest
            {
                InstanceIds = new List<string> {InstanceID }
            });
            //Can also do something with the response object too
        }

        public void StartInstance(string InstanceID)
        {
            StartInstancesResponse response = _client.StartInstances(new StartInstancesRequest
            {
                InstanceIds = new List<string> { InstanceID }
            });

        }

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM