Home
> Uncategorized > Start and Stop an #AWS #EC2 instance using the C# SDK
Start and Stop an #AWS #EC2 instance using the C# SDK

Automation of EC2 instances is really important if you want to optimize costs. Perhaps you have a server that does not need to be online 100% of the time, perhaps just during peak hours, or perhaps, when running a scheduled task.
You can use C# to query the state of an instance, and start and stop it. You will need to generate your own Access keys in AWS IAM, and the instance ID and region will change based on your setup,
Add the Nuget Package AWSSDK.EC2
Here is the code to log in to AWS
const string accessKey = "....";
const string secretKey = ".....";
AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
var config = new AmazonEC2Config
{
RegionEndpoint = Amazon.RegionEndpoint.GetBySystemName("eu-west-2")
};
var client = new AmazonEC2Client(credentials, config);
var response = client.DescribeInstanceStatus(new DescribeInstanceStatusRequest { IncludeAllInstances = true});
var state = response.InstanceStatuses.First(i => i.InstanceId == "i-0fb....").InstanceState.Name.ToString();
Console.WriteLine("Instance is " + state);
then to start the instance it’s :
client.StartInstances(new StartInstancesRequest(new List<string> { "i-0fb9f4....." }));
And to stop the instance it’s:
client.StopInstances(new StopInstancesRequest(new List<string> {"i-0fb9....."}));
Easy done!
Categories: Uncategorized
Comments (0)
Trackbacks (0)
Leave a comment
Trackback