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.
2.) Create new user for your application (for example dotnetuser).
Select Your Accoutnt / Security Credentials from main menu and create new user.
Don’t forget to save access key id and secret key.
You will use them to connect to AWS.
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
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
<configuration> <appSettings> <add key="AWSProfileName" value="profile-name"/> </appSettings> </configuration>
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 startRequest.InstanceIds.Add("i-4d2213bb"); ec2.StartInstances(startRequest); //This code will stop your EC2 instance. StopInstancesRequest stopRequest = new StopInstancesRequest();
//change instance id stopRequest.InstanceIds.Add("i-4d2213bb"); ec2.StopInstances(stopRequest);
That’s all folks!
Good blog post, Igor. Unfortunately, your example uses Amazon.Util.ProfileManager.RegisterProfile, which is unnecessary and potentially can cause runtime problems. This blog post provides some more detail: http://blogs.aws.amazon.com/net/post/Tx3VJIHQF8Q0YSX/RegisterProfile
Given that the application already has access to AWS access and secret keys, you can simplify your code simple as follows:
AWSCredentials credentials = new BasicAWSCredentials(“access_key_id”, “secret_key”);
Pavel thank you for your feedback.
I needed a way to create a profile in the code.
Amazon Credentials are not stored locally.
I will change example with your remarks.