Menu
AWS SDK for Java
Developer Guide

Working with Amazon EC2 Key Pairs

Creating a Key Pair

To create a key pair, call the AmazonEC2Client's createKeyPair method with a CreateKeyPairRequest that contains the key's name.

Imports

Copy
import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.AmazonEC2ClientBuilder; import com.amazonaws.services.ec2.model.CreateKeyPairRequest; import com.amazonaws.services.ec2.model.CreateKeyPairResult;

Code

Copy
final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); CreateKeyPairRequest request = new CreateKeyPairRequest() .withKeyName(key_name); CreateKeyPairResult response = ec2.createKeyPair(request);

See the complete example.

Describing Key Pairs

To list your key pairs or to get information about them, call the AmazonEC2Client's describeKeyPairs method. It returns a DescribeKeyPairsRequest that you can use to access the list of key pairs by calling its getKeyPairs method, which returns a list of KeyPairInfo objects.

Imports

Copy
import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.AmazonEC2ClientBuilder; import com.amazonaws.services.ec2.model.DescribeKeyPairsResult; import com.amazonaws.services.ec2.model.KeyPairInfo;

Code

Copy
final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); DescribeKeyPairsResult response = ec2.describeKeyPairs(); for(KeyPairInfo key_pair : response.getKeyPairs()) { System.out.printf( "Found key pair with name %s " + "and fingerprint %s", key_pair.getKeyName(), key_pair.getKeyFingerprint()); }

See the complete example.

Deleting a Key Pair

To delete a key pair, call the AmazonEC2Client's deleteKeyPair method, passing it a DeleteKeyPairRequest that contains the name of the key pair to delete.

Imports

Copy
import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.AmazonEC2ClientBuilder; import com.amazonaws.services.ec2.model.DeleteKeyPairRequest; import com.amazonaws.services.ec2.model.DeleteKeyPairResult;

Code

Copy
final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); DeleteKeyPairRequest request = new DeleteKeyPairRequest() .withKeyName(key_name); DeleteKeyPairResult response = ec2.deleteKeyPair(request);

See the complete example.

More Information