How to start an Amazon EC2 instance programmatically in .NET

前端 未结 5 1767
醉话见心
醉话见心 2020-12-28 09:03

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 b

相关标签:
5条回答
  • 2020-12-28 09:32

    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
         ...
    }
    
    0 讨论(0)
  • 2020-12-28 09:33

    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")
    ); 
    
    0 讨论(0)
  • 2020-12-28 09:35

    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 }
                });
    
            }
    
        }
    
    0 讨论(0)
  • 2020-12-28 09:36

    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;
                        }
                    }
    
    0 讨论(0)
  • 2020-12-28 09:38

    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.

    0 讨论(0)
提交回复
热议问题