AWS SDK for Java
Developer Guide

Working with Amazon EC2 Key Pairs

Important

This is a preview release and is not recommended for production environments.

Creating a Key Pair

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

Imports

import software.amazon.awssdk.services.ec2.Ec2Client; import software.amazon.awssdk.services.ec2.model.CreateKeyPairRequest; import software.amazon.awssdk.services.ec2.model.CreateKeyPairResponse;

Code

Ec2Client ec2 = Ec2Client.create(); CreateKeyPairRequest request = CreateKeyPairRequest.builder() .keyName(key_name).build(); CreateKeyPairResponse response = ec2.createKeyPair(request);

See the complete example on GitHub.

Describing Key Pairs

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

Imports

import software.amazon.awssdk.services.ec2.Ec2Client; import software.amazon.awssdk.services.ec2.model.DescribeKeyPairsResponse; import software.amazon.awssdk.services.ec2.model.KeyPairInfo;

Code

Client ec2 = Ec2Client.create(); DescribeKeyPairsResponse response = ec2.describeKeyPairs(); for(KeyPairInfo key_pair : response.keyPairs()) { System.out.printf( "Found key pair with name %s " + "and fingerprint %s", key_pair.keyName(), key_pair.keyFingerprint()); System.out.println(""); }

See the complete example on GitHub.

Deleting a Key Pair

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

Imports

import software.amazon.awssdk.services.ec2.Ec2Client; import software.amazon.awssdk.services.ec2.model.DeleteKeyPairRequest; import software.amazon.awssdk.services.ec2.model.DeleteKeyPairResponse;

Code

Ec2Client ec2 = Ec2Client.create(); DeleteKeyPairRequest request = DeleteKeyPairRequest.builder() .keyName(key_name) .build(); DeleteKeyPairResponse response = ec2.deleteKeyPair(request);

See the complete example on GitHub.

More Information