Use CreateKeyPair with an Amazon SDK or CLI - Amazon Elastic Compute Cloud
Services or capabilities described in Amazon Web Services documentation might vary by Region. To see the differences applicable to the China Regions, see Getting Started with Amazon Web Services in China (PDF).

Use CreateKeyPair with an Amazon SDK or CLI

The following code examples show how to use CreateKeyPair.

Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code example:

.NET
Amazon SDK for .NET
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

/// <summary> /// Create an Amazon EC2 key pair. /// </summary> /// <param name="keyPairName">The name for the new key pair.</param> /// <returns>The Amazon EC2 key pair created.</returns> public async Task<KeyPair?> CreateKeyPair(string keyPairName) { var request = new CreateKeyPairRequest { KeyName = keyPairName, }; var response = await _amazonEC2.CreateKeyPairAsync(request); if (response.HttpStatusCode == HttpStatusCode.OK) { var kp = response.KeyPair; return kp; } else { Console.WriteLine("Could not create key pair."); return null; } } /// <summary> /// Save KeyPair information to a temporary file. /// </summary> /// <param name="keyPair">The name of the key pair.</param> /// <returns>The full path to the temporary file.</returns> public string SaveKeyPair(KeyPair keyPair) { var tempPath = Path.GetTempPath(); var tempFileName = $"{tempPath}\\{Path.GetRandomFileName()}"; var pemFileName = Path.ChangeExtension(tempFileName, "pem"); // Save the key pair to a file in a temporary folder. using var stream = new FileStream(pemFileName, FileMode.Create); using var writer = new StreamWriter(stream); writer.WriteLine(keyPair.KeyMaterial); return pemFileName; }
  • For API details, see CreateKeyPair in Amazon SDK for .NET API Reference.

Bash
Amazon CLI with Bash script
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

############################################################################### # function ec2_create_keypair # # This function creates an Amazon Elastic Compute Cloud (Amazon EC2) ED25519 or 2048-bit RSA key pair # and writes it to a file. # # Parameters: # -n key_pair_name - A key pair name. # -f file_path - File to store the key pair. # # And: # 0 - If successful. # 1 - If it fails. ############################################################################### function ec2_create_keypair() { local key_pair_name file_path response local option OPTARG # Required to use getopts command in a function. # bashsupport disable=BP5008 function usage() { echo "function ec2_create_keypair" echo "Creates an Amazon Elastic Compute Cloud (Amazon EC2) ED25519 or 2048-bit RSA key pair" echo " and writes it to a file." echo " -n key_pair_name - A key pair name." echo " -f file_path - File to store the key pair." echo "" } # Retrieve the calling parameters. while getopts "n:f:h" option; do case "${option}" in n) key_pair_name="${OPTARG}" ;; f) file_path="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 if [[ -z "$key_pair_name" ]]; then errecho "ERROR: You must provide a key name with the -n parameter." usage return 1 fi if [[ -z "$file_path" ]]; then errecho "ERROR: You must provide a file path with the -f parameter." usage return 1 fi response=$(aws ec2 create-key-pair \ --key-name "$key_pair_name" \ --query 'KeyMaterial' \ --output text) || { aws_cli_error_log ${?} errecho "ERROR: AWS reports create-access-key operation failed.$response" return 1 } if [[ -n "$file_path" ]]; then echo "$response" >"$file_path" fi return 0 }

The utility functions used in this example.

############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################## # function aws_cli_error_log() # # This function is used to log the error messages from the AWS CLI. # # The function expects the following argument: # $1 - The error code returned by the AWS CLI. # # Returns: # 0: - Success. # ############################################################################## function aws_cli_error_log() { local err_code=$1 errecho "Error code : $err_code" if [ "$err_code" == 1 ]; then errecho " One or more S3 transfers failed." elif [ "$err_code" == 2 ]; then errecho " Command line failed to parse." elif [ "$err_code" == 130 ]; then errecho " Process received SIGINT." elif [ "$err_code" == 252 ]; then errecho " Command syntax invalid." elif [ "$err_code" == 253 ]; then errecho " The system environment or configuration was invalid." elif [ "$err_code" == 254 ]; then errecho " The service returned an error." elif [ "$err_code" == 255 ]; then errecho " 255 is a catch-all error." fi return 0 }
  • For API details, see CreateKeyPair in Amazon CLI Command Reference.

C++
SDK for C++
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

Aws::EC2::EC2Client ec2Client(clientConfiguration); Aws::EC2::Model::CreateKeyPairRequest request; request.SetKeyName(keyPairName); Aws::EC2::Model::CreateKeyPairOutcome outcome = ec2Client.CreateKeyPair(request); if (!outcome.IsSuccess()) { std::cerr << "Failed to create key pair:" << outcome.GetError().GetMessage() << std::endl; } else { std::cout << "Successfully created key pair named " << keyPairName << std::endl; }
  • For API details, see CreateKeyPair in Amazon SDK for C++ API Reference.

CLI
Amazon CLI

To create a key pair

This example creates a key pair named MyKeyPair.

Command:

aws ec2 create-key-pair --key-name MyKeyPair

The output is an ASCII version of the private key and key fingerprint. You need to save the key to a file.

For more information, see Using Key Pairs in the Amazon Command Line Interface User Guide.

  • For API details, see CreateKeyPair in Amazon CLI Command Reference.

Java
SDK for Java 2.x
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

public static void createKeyPair(Ec2Client ec2, String keyName, String fileName) { try { CreateKeyPairRequest request = CreateKeyPairRequest.builder() .keyName(keyName) .build(); CreateKeyPairResponse response = ec2.createKeyPair(request); String content = response.keyMaterial(); BufferedWriter writer = new BufferedWriter(new FileWriter(fileName)); writer.write(content); writer.close(); System.out.println("Successfully created key pair named " + keyName); } catch (Ec2Exception | IOException e) { System.err.println(e.getMessage()); System.exit(1); } }
  • For API details, see CreateKeyPair in Amazon SDK for Java 2.x API Reference.

JavaScript
SDK for JavaScript (v3)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

import { CreateKeyPairCommand } from "@aws-sdk/client-ec2"; import { client } from "../libs/client.js"; export const main = async () => { try { // Create a key pair in Amazon EC2. const { KeyMaterial, KeyName } = await client.send( // A unique name for the key pair. Up to 255 ASCII characters. new CreateKeyPairCommand({ KeyName: "KEY_PAIR_NAME" }), ); // This logs your private key. Be sure to save it. console.log(KeyName); console.log(KeyMaterial); } catch (err) { console.error(err); } };
  • For API details, see CreateKeyPair in Amazon SDK for JavaScript API Reference.

Kotlin
SDK for Kotlin
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

suspend fun createEC2KeyPair(keyNameVal: String) { val request = CreateKeyPairRequest { keyName = keyNameVal } Ec2Client { region = "us-west-2" }.use { ec2 -> val response = ec2.createKeyPair(request) println("The key ID is ${response.keyPairId}") } }
  • For API details, see CreateKeyPair in Amazon SDK for Kotlin API reference.

PowerShell
Tools for PowerShell

Example 1: This example creates a key pair and captures the PEM-encoded RSA private key in a file with the specified name. When you are using PowerShell, the encoding must be set to ascii to generate a valid key. For more information, see Create, Display, and Delete Amazon EC2 Key Pairs (https://docs.aws.amazon.com/cli/latest/userguide/cli-services-ec2-keypairs.html) in the Amazon Command Line Interface User Guide.

(New-EC2KeyPair -KeyName "my-key-pair").KeyMaterial | Out-File -Encoding ascii -FilePath C:\path\my-key-pair.pem
  • For API details, see CreateKeyPair in Amazon Tools for PowerShell Cmdlet Reference.

Python
SDK for Python (Boto3)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

class KeyPairWrapper: """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) key pair actions.""" def __init__(self, ec2_resource, key_file_dir, key_pair=None): """ :param ec2_resource: A Boto3 Amazon EC2 resource. This high-level resource is used to create additional high-level objects that wrap low-level Amazon EC2 service actions. :param key_file_dir: The folder where the private key information is stored. This should be a secure folder. :param key_pair: A Boto3 KeyPair object. This is a high-level object that wraps key pair actions. """ self.ec2_resource = ec2_resource self.key_pair = key_pair self.key_file_path = None self.key_file_dir = key_file_dir @classmethod def from_resource(cls): ec2_resource = boto3.resource("ec2") return cls(ec2_resource, tempfile.TemporaryDirectory()) def create(self, key_name): """ Creates a key pair that can be used to securely connect to an EC2 instance. The returned key pair contains private key information that cannot be retrieved again. The private key data is stored as a .pem file. :param key_name: The name of the key pair to create. :return: A Boto3 KeyPair object that represents the newly created key pair. """ try: self.key_pair = self.ec2_resource.create_key_pair(KeyName=key_name) self.key_file_path = os.path.join( self.key_file_dir.name, f"{self.key_pair.name}.pem" ) with open(self.key_file_path, "w") as key_file: key_file.write(self.key_pair.key_material) except ClientError as err: logger.error( "Couldn't create key %s. Here's why: %s: %s", key_name, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return self.key_pair
  • For API details, see CreateKeyPair in Amazon SDK for Python (Boto3) API Reference.

Ruby
SDK for Ruby
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

# This code example does the following: # 1. Creates a key pair in Amazon Elastic Compute Cloud (Amazon EC2). # 2. Displays information about available key pairs. # 3. Deletes the key pair. require "aws-sdk-ec2" # @param ec2_client [Aws::EC2::Client] An initialized EC2 client. # @param key_pair_name [String] The name for the key pair and private # key file. # @return [Boolean] true if the key pair and private key file were # created; otherwise, false. # @example # exit 1 unless key_pair_created?( # Aws::EC2::Client.new(region: 'us-west-2'), # 'my-key-pair' # ) def key_pair_created?(ec2_client, key_pair_name) key_pair = ec2_client.create_key_pair(key_name: key_pair_name) puts "Created key pair '#{key_pair.key_name}' with fingerprint " \ "'#{key_pair.key_fingerprint}' and ID '#{key_pair.key_pair_id}'." filename = File.join(Dir.home, key_pair_name + ".pem") File.open(filename, "w") { |file| file.write(key_pair.key_material) } puts "Private key file saved locally as '#{filename}'." return true rescue Aws::EC2::Errors::InvalidKeyPairDuplicate puts "Error creating key pair: a key pair named '#{key_pair_name}' " \ "already exists." return false rescue StandardError => e puts "Error creating key pair or saving private key file: #{e.message}" return false end # Displays information about available key pairs in # Amazon Elastic Compute Cloud (Amazon EC2). # # @param ec2_client [Aws::EC2::Client] An initialized EC2 client. # @example # describe_key_pairs(Aws::EC2::Client.new(region: 'us-west-2')) def describe_key_pairs(ec2_client) result = ec2_client.describe_key_pairs if result.key_pairs.count.zero? puts "No key pairs found." else puts "Key pair names:" result.key_pairs.each do |key_pair| puts key_pair.key_name end end rescue StandardError => e puts "Error getting information about key pairs: #{e.message}" end # Deletes a key pair in Amazon Elastic Compute Cloud (Amazon EC2). # # Prerequisites: # # - The key pair to delete. # # @param ec2_client [Aws::EC2::Client] An initialized EC2 client. # @param key_pair_name [String] The name of the key pair to delete. # @return [Boolean] true if the key pair was deleted; otherwise, false. # @example # exit 1 unless key_pair_deleted?( # Aws::EC2::Client.new(region: 'us-west-2'), # 'my-key-pair' # ) def key_pair_deleted?(ec2_client, key_pair_name) ec2_client.delete_key_pair(key_name: key_pair_name) return true rescue StandardError => e puts "Error deleting key pair: #{e.message}" return false end # Example usage: def run_me key_pair_name = "" region = "" # Print usage information and then stop. if ARGV[0] == "--help" || ARGV[0] == "-h" puts "Usage: ruby ec2-ruby-example-key-pairs.rb KEY_PAIR_NAME REGION" puts "Example: ruby ec2-ruby-example-key-pairs.rb my-key-pair us-west-2" exit 1 # If no values are specified at the command prompt, use these default values. # Replace us-west-2 with the AWS Region you're using for Amazon EC2. elsif ARGV.count.zero? key_pair_name = "my-key-pair" region = "us-west-2" # Otherwise, use the values as specified at the command prompt. else key_pair_name = ARGV[0] region = ARGV[1] end ec2_client = Aws::EC2::Client.new(region: region) puts "Displaying existing key pair names before creating this key pair..." describe_key_pairs(ec2_client) puts "-" * 10 puts "Creating key pair..." unless key_pair_created?(ec2_client, key_pair_name) puts "Stopping program." exit 1 end puts "-" * 10 puts "Displaying existing key pair names after creating this key pair..." describe_key_pairs(ec2_client) puts "-" * 10 puts "Deleting key pair..." unless key_pair_deleted?(ec2_client, key_pair_name) puts "Stopping program. You must delete the key pair yourself." exit 1 end puts "Key pair deleted." puts "-" * 10 puts "Now that the key pair is deleted, " \ "also deleting the related private key pair file..." filename = File.join(Dir.home, key_pair_name + ".pem") File.delete(filename) if File.exist?(filename) puts "Could not delete file at '#{filename}'. You must delete it yourself." else puts "File deleted." end puts "-" * 10 puts "Displaying existing key pair names after deleting this key pair..." describe_key_pairs(ec2_client) end run_me if $PROGRAM_NAME == __FILE__
  • For API details, see CreateKeyPair in Amazon SDK for Ruby API Reference.

SAP ABAP
SDK for SAP ABAP
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

TRY. oo_result = lo_ec2->createkeypair( iv_keyname = iv_key_name ). " oo_result is returned for testing purposes. " MESSAGE 'Amazon EC2 key pair created.' TYPE 'I'. CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception). DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|. MESSAGE lv_error TYPE 'E'. ENDTRY.
  • For API details, see CreateKeyPair in Amazon SDK for SAP ABAP API reference.

For a complete list of Amazon SDK developer guides and code examples, see Create Amazon EC2 resources using an Amazon SDK. This topic also includes information about getting started and details about previous SDK versions.