Working with Amazon EC2 Key Pairs - AWS SDK for Java 1.x

We announced the upcoming end-of-support for AWS SDK for Java (v1). We recommend that you migrate to AWS SDK for Java v2. For dates, additional details, and information on how to migrate, please refer to the linked announcement.

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