Work with Amazon EC2 key pairs - AWS SDK for Java version 2

Work with Amazon EC2 key pairs

Create 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.regions.Region; import software.amazon.awssdk.services.ec2.Ec2Client; import software.amazon.awssdk.services.ec2.model.CreateKeyPairRequest; import software.amazon.awssdk.services.ec2.model.CreateKeyPairResponse; import software.amazon.awssdk.services.ec2.model.Ec2Exception;

Code

public static void createEC2KeyPair(Ec2Client ec2,String keyName ) { try { CreateKeyPairRequest request = CreateKeyPairRequest.builder() .keyName(keyName).build(); CreateKeyPairResponse response = ec2.createKeyPair(request); System.out.printf( "Successfully created key pair named %s", keyName); } catch (Ec2Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); }

See the complete example on GitHub.

Describe 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.regions.Region; import software.amazon.awssdk.services.ec2.Ec2Client; import software.amazon.awssdk.services.ec2.model.DescribeKeyPairsResponse; import software.amazon.awssdk.services.ec2.model.KeyPairInfo; import software.amazon.awssdk.services.ec2.model.Ec2Exception;

Code

public static void describeEC2Keys( Ec2Client ec2){ try { DescribeKeyPairsResponse response = ec2.describeKeyPairs(); for(KeyPairInfo keyPair : response.keyPairs()) { System.out.printf( "Found key pair with name %s " + "and fingerprint %s", keyPair.keyName(), keyPair.keyFingerprint()); System.out.println(""); } } catch (Ec2Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); }

See the complete example on GitHub.

Delete 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.regions.Region; import software.amazon.awssdk.services.ec2.Ec2Client; import software.amazon.awssdk.services.ec2.model.DeleteKeyPairRequest; import software.amazon.awssdk.services.ec2.model.DeleteKeyPairResponse; import software.amazon.awssdk.services.ec2.model.Ec2Exception;

Code

public static void deleteKeys(Ec2Client ec2, String keyName) { try { DeleteKeyPairRequest request = DeleteKeyPairRequest.builder() .keyName(keyName) .build(); DeleteKeyPairResponse response = ec2.deleteKeyPair(request);

See the complete example on GitHub.

More information