User guide
Create a Key Pair
You must specify a key pair when you launch an EC2 instance and then specify the private key of the
key pair when you connect to the instance.You can create a key pair or use an existing key pair that
you've used when launching other instances. For more information, see Amazon EC2 Key Pairs in the
Amazon EC2 User Guide for Linux Instances.
To create a key pair and save the private key
1. Create and initialize a CreateKeyPairRequest instance. Use the withKeyName method to set the key
pair name, as follows:
CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest();
createKeyPairRequest.withKeyName(keyName);
Important
Key pair names must be unique. If you attempt to create a key pair with the same key name
as an existing key pair, you'll get an exception.
2. Pass the request object to the createKeyPair method. The method returns a CreateKeyPairResult
instance, as follows:
CreateKeyPairResult createKeyPairResult =
amazonEC2Client.createKeyPair(createKeyPairRequest);
3. Call the result object's getKeyPair method to obtain a KeyPair object. Call the KeyPair object's
getKeyMaterial method to obtain the unencrypted PEM-encoded private key, as follows:
KeyPair keyPair = new KeyPair();
keyPair = createKeyPairResult.getKeyPair();
String privateKey = keyPair.getKeyMaterial();
Run an Amazon EC2 Instance
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.
To launch an Amazon EC2 instance
1. Create and initialize a RunInstancesRequest instance. 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.
RunInstancesRequest runInstancesRequest =
new RunInstancesRequest();
runInstancesRequest.withImageId("ami-4b814f22")
.withInstanceType("m1.small")
.withMinCount(1)
Version v1.0.0
29
AWS SDK for Java Developer Guide
Tutorial: Starting an EC2 Instance