User guide
This example saves the private key in the current directory, using the name of the key pair as the base
file name of the .pem file.
if (myKeyPair == null)
{
var newKeyRequest = new CreateKeyPairRequest()
{
KeyName = keyPairName
};
var ckpResponse = ec2Client.CreateKeyPair(newKeyRequest);
Console.WriteLine();
Console.WriteLine("New key: " + keyPairName);
// Save the private key in a .pem file
using (FileStream s = new FileStream(keyPairName + ".pem", FileMode.Create))
using (StreamWriter writer = new StreamWriter(s))
{
writer.WriteLine(ckpResponse.KeyPair.KeyMaterial);
}
}
Launch an EC2 Instance Using the SDK for .NET
Use the following procedure to launch one or more identically configured EC2 instances from the same
Amazon Machine Image (AMI). After you create your EC2 instances, you can check their status. After
your EC2 instances are running, you can connect to them.
Contents
• Launching an EC2 Instance (p. 74)
• Checking the State of Your Instance (p. 78)
• Connecting to Your Running Instance (p. 79)
Launching an EC2 Instance
You launch an instance in either EC2-Classic or EC2-VPC. For more information about EC2-Classic and
EC2-VPC, see Supported Platforms in the Amazon EC2 User Guide for Microsoft Windows Instances.
To launch an EC2 instance in EC2-Classic
1. Create and initialize a RunInstancesRequest object. Make sure that the AMI, key pair, and security
group that you specify exist in the region that you specified when you created the client object.
string amiID = "ami-e189c8d1";
string keyPairName = "my-sample-key";
List<string> groups = new List<string>() { mySG.GroupId };
var launchRequest = new RunInstancesRequest()
{
ImageId = amiID,
InstanceType = "t1.micro",
MinCount = 1,
MaxCount = 1,
KeyName = keyPairName,
Version v2.0.0
74
AWS SDK for .NET Developer Guide
Tutorial: Creating Amazon EC2 Instances