Controlling Amazon EC2 instances using the AWSSDK C# API

I’ve recently had to query the status of EC2 instances and then be able to controlling them as required.

1.) Create Amazon free account or use your existing Amazon AWS account.

Controlling Amazon EC2 instances using the AWSSDK

2.) Create new user for your application (for example dotnetuser).

Select Your Accoutnt / Security Credentials from main menu and create new user.

Controlling Amazon EC2 instances using the AWSSDK


Don’t forget to save access key id and secret key.

You will use them to connect to AWS.

Controlling Amazon EC2 instances using the AWSSDK

3.) Download and install AWS SDK for .NET.

More info about AWS SDK:

4.) You are ready to write code. Create blank console application and add reference to AWS SDK.

AWS SDK is installed usually on this location:

C:\Program Files (x86)\AWS SDK for .NET\bin\Net45

Required usings:

using Amazon;
using Amazon.EC2;
using Amazon.EC2.Model;
using Amazon.SimpleDB;
using Amazon.SimpleDB.Model;
using Amazon.S3;
using Amazon.S3.Model;
using Amazon.Runtime;

Copy this code into you Main function and change credentials with yours:

Amazon.Util.ProfileManager.RegisterProfile("dotnetuser", "access_key_id", "secret_key");
AWSCredentials credentials = new StoredProfileAWSCredentials("dotnetuser");

Using RegisterProfile can cause runtime problems (Thanks to Pavel Safronov)

You can access your profile by specifying it in app.config/web.config file

      <add key="AWSProfileName" value="profile-name"/>

Or explicitly

var credentials = new Amazon.Runtime.StoredProfileAWSCredentials("profile-name");

Define region and create EC2 client:

RegionEndpoint re = RegionEndpoint.USWest2;

IAmazonEC2 ec2 = AWSClientFactory.CreateAmazonEC2Client(credentials,re);
DescribeInstancesRequest ec2Request = new DescribeInstancesRequest();
//This code will start your EC2 instance.

StartInstancesRequest startRequest = new StartInstancesRequest();
//change instance id

//This code will stop your EC2 instance.

StopInstancesRequest stopRequest = new StopInstancesRequest();
//change instance id

That’s all folks!