The Amazon SDK for Java 1.x has entered maintenance mode as of July 31, 2024,
and will reach end-of-support
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
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
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 DescribeKeyPairsResult that you can use to access the list of key pairs by calling its getKeyPairs
method, which returns a list of KeyPairInfo objects.
Imports
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
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
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
final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); DeleteKeyPairRequest request = new DeleteKeyPairRequest() .withKeyName(key_name); DeleteKeyPairResult response = ec2.deleteKeyPair(request);
See the complete example
More Information
-
Amazon EC2 Key Pairs
in the Amazon EC2 User Guide for Linux Instances -
CreateKeyPair
in the Amazon EC2 API Reference -
DescribeKeyPairs
in the Amazon EC2 API Reference -
DeleteKeyPair
in the Amazon EC2 API Reference