Menu
AWS SDK for C++
Developer Guide

Working with Amazon EC2 Key Pairs

Note

These code snippets assume that you understand the material in Getting Started Using the AWS SDK for C++ and have configured default AWS credentials using the information in Providing AWS Credentials.

Creating a Key Pair

To create a key pair, call the EC2Client's CreateKeyPair function with a CreateKeyPairRequest that contains the key's name.

Includes

Copy
#include <aws/core/Aws.h> #include <aws/ec2/EC2Client.h> #include <aws/ec2/model/CreateKeyPairRequest.h> #include <aws/ec2/model/CreateKeyPairResponse.h> #include <iostream>

Code

Copy
Aws::EC2::EC2Client ec2; Aws::EC2::Model::CreateKeyPairRequest request; request.SetKeyName(pair_name); auto outcome = ec2.CreateKeyPair(request); if (!outcome.IsSuccess()) { std::cout << "Failed to create key pair:" << outcome.GetError().GetMessage() << std::endl; } else { std::cout << "Successfully created key pair named " << pair_name << std::endl; }

See the complete example.

Describing Key Pairs

To list your key pairs or to get information about them, call the EC2Client's DescribeKeyPairs function with a DescribeKeyPairsRequest.

You will receive a DescribeKeyPairsResponse that you can use to access the list of key pairs by calling its GetKeyPairs function, which returns a list of KeyPairInfo objects.

Includes

Copy
#include <aws/core/Aws.h> #include <aws/ec2/EC2Client.h> #include <aws/ec2/model/DescribeKeyPairsRequest.h> #include <aws/ec2/model/DescribeKeyPairsResponse.h> #include <iostream> #include <iomanip>

Code

Copy
const auto &key_pairs = outcome.GetResult().GetKeyPairs(); for (const auto &key_pair : key_pairs) { std::cout << std::left << std::setw(32) << key_pair.GetKeyName() << std::setw(64) << key_pair.GetKeyFingerprint() << std::endl; } } else { std::cout << "Failed to describe key pairs:" << outcome.GetError().GetMessage() << std::endl; }

See the complete example.

Deleting a Key Pair

To delete a key pair, call the EC2Client's DeleteKeyPair function, passing it a DeleteKeyPairRequest that contains the name of the key pair to delete.

Includes

Copy
#include <aws/core/Aws.h> #include <aws/ec2/EC2Client.h> #include <aws/ec2/model/DeleteKeyPairRequest.h> #include <iostream>

Code

Copy
Aws::EC2::Model::DeleteKeyPairRequest request; request.SetKeyName(pair_name); auto outcome = ec2.DeleteKeyPair(request); if (!outcome.IsSuccess()) { std::cout << "Failed to delete key pair " << pair_name << ":" << outcome.GetError().GetMessage() << std::endl; } else { std::cout << "Successfully deleted key pair named " << pair_name << std::endl; }

See the complete example.

More Information