How to start an Amazon EC2 instance programmatically in .NET

前端 未结 5 1794
醉话见心
醉话见心 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: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 {InstanceID }
                });
                //Can also do something with the response object too
            }
    
            public void StartInstance(string InstanceID)
            {
                StartInstancesResponse response = _client.StartInstances(new StartInstancesRequest
                {
                    InstanceIds = new List { InstanceID }
                });
    
            }
    
        }
    

提交回复
热议问题