User guide
To create a key pair and obtain 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);
2. Pass the request object to the createKeyPair method. The method returns a CreateKeyPairResult
instance, as follows:
CreateKeyPairResult createKeyPairResult =
amazonEC2Client.createKeyPair(createKeyPairRequest);
Key pair names must be unique. If you attempt to create a key pair with the same key name as an
existing key pair, createKeyPair returns an exception.
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();
Calling createKeyPair is the only way to obtain the private key programmatically.
Before logging onto an Amazon EC2 instance, you must create the instance and ensure that it is running.
For information on how to run an Amazon EC2 instance, see Run an Amazon EC2 Instance (p. 27).
For information on how to use your key pair to connect to your Amazon EC2 instance, see Connect to
Your Amazon EC2 Instance (p. 28).
Run an Amazon EC2 Instance
Before running an Amazon EC2 instance, ensure that you have created a security group and a key pair
for your instance. For information about creating a key pair, see Create a Key Pair (p. 26). For information
about creating a security group, see Create an Amazon EC2 Security Group (p. 24).
To run an Amazon EC2 instance
1. Create and initialize a RunInstancesRequest instance. Specify the Amazon Machine Image (AMI)
(withImageId), the instance type (withInstanceType), the minimum (withMinCount) and maximum
(withMaxCount) number of instances to run, key pair name (withKeyName), and the name of one or
more security groups (withSecurityGroups), as follows:
RunInstancesRequest runInstancesRequest =
Version v1.0.0
27
AWS SDK for Java Developer Guide
Starting an Amazon EC2 Instance