AWS SDK for C++ (v1) With Wasabi
    • 26 Sep 2024
    • 8 Minutes to read
    • PDF

    AWS SDK for C++ (v1) With Wasabi

    • PDF

    Article summary

    How do I use AWS SDK for C++ (v1) with Wasabi?

    AWS SDK for C++ v1 is validated for use with Wasabi. 

    Using the C++ SDK

    Execute the following steps:

    1. Install the AWS SDK for C++ using CMAKE.

    2. (Optional) Configure an additional AWS CLI profile for Wasabi account using the Wasabi keys.

    In this example, we set the profile name as "wasabi" in the "~/.aws/credentials" file. To help you use this SDK with Wasabi, we provided examples for both IAM and S3: 

    • Setting the Credentials

    • Connecting to IAM and S3 Endpoints

    • Creating a User Using IAM

    • Creating a Bucket

    • Uploading an Object to the Bucket

    • Reading an Object From the Bucket

    • Deleting an Object From the Bucket

    Additional examples are available from the AWS documentation.

    The examples use Wasabi's us-east-1 storage region. For other Wasabi storage regions, use the appropriate Wasabi service URL.

    Send all IAM requests to iam.wasabisys.com


    The following is an example CMakeLists.txt file.

    cmake_minimum_required(VERSION 3.5)
    project(aws-sdk-cpp-sample)//This is an example name
    
    # Set the C++ standard
    set(CMAKE_CXX_STANDARD 11)
    
    # Find the AWS SDK for C++
    find_package(AWSSDK REQUIRED COMPONENTS s3 iam)
    
    # Add the executable
    add_executable(${PROJECT_NAME} main.cpp) //change according to the function file name
    
    # Link the AWS SDK for C++ libraries
    target_link_libraries(${PROJECT_NAME} ${AWSSDK_LINK_LIBRARIES})

    Setting the Credentials

    #include <aws/core/Aws.h> 
    #include <aws/core/auth/AWSCredentialsProvider.h> 
    #include <aws/core/client/ClientConfiguration.h> 
    #include <aws/iam/IAMClient.h> 
    #include <aws/s3/S3Client.h> 
    #include <memory> 
    
    int main() { 
    Aws::SDKOptions options; 
    Aws::InitAPI(options); 
    
    // Specify the profile name from which credentials will be loaded 
    const Aws::String profileName = "wasabi"; 
    
    // Create a client configuration 
    Aws::Client::ClientConfiguration clientConfig; 
    
    // Create a credentials provider using the specified profile name 
    auto credentialsProvider = Aws::MakeShared<Aws::Auth::ProfileConfigFileAWSCredentialsProvider>(profileName.c_str()); 
    
    // IAM client setup 
    Aws::IAM::IAMClient iamClient(credentialsProvider, clientConfig); 
    
    // S3 client setup 
    Aws::S3::S3Client s3Client(credentialsProvider, clientConfig, Aws::Client::AWSAuthV4Signer::PayloadSigningPolicy::Never, false); 
    
    // Continue with your code... 
    Aws::ShutdownAPI(options); 
    return 0; 
    } 

    Connecting to IAM and S3 Endpoints

    IAM

    #include <aws/core/Aws.h>
    #include <aws/core/auth/AWSCredentialsProvider.h>
    #include <aws/core/client/ClientConfiguration.h>
    #include <aws/iam/IAMClient.h>
    #include <aws/iam/model/GetUserRequest.h>
    #include <aws/iam/model/GetUserResult.h>
    #include <iostream>
    #include <memory>
    
    int main() {
    
        Aws::SDKOptions options;
        Aws::InitAPI(options);
        {
    
            const Aws::String profileName = "wasabi";
            Aws::Client::ClientConfiguration clientConfig;
            clientConfig.endpointOverride = "https://iam.wasabisys.com";
            auto credentialsProvider = std::make_shared<Aws::Auth::ProfileConfigFileAWSCredentialsProvider>(profileName.c_str());
            Aws::IAM::IAMClient iamClient(credentialsProvider, clientConfig);
    
           // Test by using the current user, don't remember the username
    
            Aws::IAM::Model::GetUserRequest request;
            auto outcome = iamClient.GetUser(request);
    
            if (outcome.IsSuccess()) {
                std::cout << "Connection successful" << std::endl;
            } else {
                std::cerr << "Connection failed: " << outcome.GetError().GetMessage() << std::endl;
            }
        }
    
        Aws::ShutdownAPI(options);
        return 0;
    }

    S3

    #include <aws/core/Aws.h>
    #include <aws/core/auth/AWSCredentialsProvider.h>
    #include <aws/core/client/ClientConfiguration.h>
    #include <aws/s3/S3Client.h>
    #include <aws/s3/model/ListBucketsResult.h>
    #include <iostream>
    #include <memory>
    
    int main() {
        Aws::SDKOptions options;
        Aws::InitAPI(options);
        {
            const Aws::String profileName = "wasabi";
            Aws::Client::ClientConfiguration clientConfig;
            clientConfig.endpointOverride = "https://s3.wasabisys.com";
            auto credentialsProvider = std::make_shared<Aws::Auth::ProfileConfigFileAWSCredentialsProvider>(profileName.c_str());
            Aws::S3::S3Client s3Client(credentialsProvider, clientConfig, Aws::Client::AWSAuthV4Signer::PayloadSigningPolicy::Never, false);
    
            // Testing connection using list buckets.
            auto outcome = s3Client.ListBuckets();
    
            if (outcome.IsSuccess()) {
                std::cout << "List of buckets:" << std::endl;
                const auto& buckets = outcome.GetResult().GetBuckets();
                for (const auto& bucket : buckets) {
                    std::cout << "Bucket: " << bucket.GetName() << std::endl;
                }
            } else {
                std::cerr << "Failed to list buckets: " << outcome.GetError().GetMessage() << std::endl;
            }
        }
        Aws::ShutdownAPI(options);
        return 0;
    }

    Creating a User Using IAM

    #include <aws/core/Aws.h>
    #include <aws/core/auth/AWSCredentialsProvider.h>
    #include <aws/core/client/ClientConfiguration.h>
    #include <aws/iam/IAMClient.h>
    #include <aws/iam/model/CreateUserRequest.h>
    #include <iostream>
    #include <memory>
    
    bool createIAMUser(const Aws::String& userName, const Aws::String& profileName, const Aws::String& endpointOverride) {
        // Initialize AWS SDK
        Aws::SDKOptions options;
        Aws::InitAPI(options);
    
        // Set up client configuration
        Aws::Client::ClientConfiguration clientConfig;
        clientConfig.endpointOverride = endpointOverride;
    
        // Set up credentials provider using profile name
        auto credentialsProvider = std::make_shared<Aws::Auth::ProfileConfigFileAWSCredentialsProvider>(profileName.c_str());
    
        // Set up IAM client
        Aws::IAM::IAMClient iamClient(credentialsProvider, clientConfig);
    
        // Create IAM user request
        Aws::IAM::Model::CreateUserRequest createRequest;
        createRequest.SetUserName(userName);
    
        // Send the request to create the IAM user
        auto outcome = iamClient.CreateUser(createRequest);
    
        // Check if the operation was successful
        if (!outcome.IsSuccess()) {
            auto err = outcome.GetError();
            std::cerr << "Failed to create IAM user " << userName << ": " << err.GetExceptionName() << ": " << err.GetMessage() << std::endl;
            Aws::ShutdownAPI(options);
            return false;
        }
    
        std::cout << "Successfully created IAM user " << userName << std::endl;
    
        // Clean up and shutdown the AWS SDK
        Aws::ShutdownAPI(options);
        return true;
    }
    
    int main() {
        const Aws::String userName = "your-iam-user-name";
        const Aws::String profileName = "wasabi";
        const Aws::String endpointOverride = "https://iam.wasabisys.com";
    
        if (createIAMUser(userName, profileName, endpointOverride)) {
            std::cout << "IAM user created successfully!" << std::endl;
        } else {
            std::cerr << "Failed to create IAM user." << std::endl;
        }
    
        return 0;
    }

    Creating a Bucket

    #include <iostream>
    #include <aws/core/Aws.h>
    #include <aws/s3/S3Client.h>
    #include <aws/s3/model/CreateBucketRequest.h>
    #include <aws/s3/model/BucketLocationConstraint.h>
    #include <aws/core/auth/AWSCredentialsProvider.h>
    #include <aws/core/client/ClientConfiguration.h>
    
    bool createBucket(const Aws::String& bucketName, const Aws::String&Region, const Aws::String& profileName, const Aws::String& endpointOverride) {
    
    // Initialize AWS SDK
    Aws::SDKOptions options;
    Aws::InitAPI(options);
    
    // Set up client configuration
    Aws::Client::ClientConfiguration clientConfig;
    clientConfig.region = Region;
    clientConfig.endpointOverride = endpointOverride;
    
    // Set up credentials provider using profile name
    auto credentialsProvider = std::make_shared<Aws::Auth::ProfileConfigFileAWSCredentialsProvider>(profileName.c_str());
    
    // Set up S3 client
    Aws::S3::S3Client s3Client(credentialsProvider, clientConfig, Aws::Client::AWSAuthV4Signer::PayloadSigningPolicy::Never, false);
    
    // Create bucket request
    Aws::S3::Model::CreateBucketRequest request;
    request.SetBucket(bucketName);
    
    // If the region is not us-east-1, set the location constraint
    if (Region != "us-east-1") {
    Aws::S3::Model::CreateBucketConfiguration createBucketConfig;
    createBucketConfig.SetLocationConstraint(
    Aws::S3::Model::BucketLocationConstraintMapper::GetBucketLocationConstraintForName(Region));
    request.SetCreateBucketConfiguration(createBucketConfig);
    }
    
    // Send the request to create the bucket
    auto outcome = s3Client.CreateBucket(request);
    
    // Check if the operation was successful
    if (!outcome.IsSuccess()) {
    auto err = outcome.GetError();
    std::cerr << "Failed to create bucket: " << err.GetExceptionName() << ": " << err.GetMessage() << std::endl;
    Aws::ShutdownAPI(options);
    return false;
    }
    std::cout << "Bucket " << bucketName << " created successfully in region " << Region << std::endl;
    
    // Clean up and shutdown the AWS SDK
    Aws::ShutdownAPI(options);
    return true;
    }
    
    int main() {
    
    const Aws::String bucketName = "<bucket-name>";
    const Aws::String Region = "us-east-1"; // Change this to your desired AWS region
    const Aws::String profileName = "wasabi";
    const Aws::String endpointOverride = "https://s3.wasabisys.com"; //change the Endpoint according to the region
    
    if (createBucket(bucketName, Region, profileName, endpointOverride)) {
    std::cout << "Bucket created successfully!" << std::endl;
    } else {
    std::cerr << "Failed to create bucket." << std::endl;
    }
    return 0;
    }

    Upload an Object to the Bucket

    #include <aws/core/Aws.h>
    #include <aws/core/auth/AWSCredentialsProvider.h>
    #include <aws/core/client/ClientConfiguration.h>
    #include <aws/s3/S3Client.h>
    #include <aws/s3/model/PutObjectRequest.h>
    #include <iostream>
    #include <fstream>
    
    bool uploadFileToS3WithWasabiProfile(const Aws::String& bucketName,
    const Aws::String& filePath,
    const Aws::String& awsRegion) {
    // Initialize AWS SDK
    Aws::SDKOptions options;
    Aws::InitAPI(options);
    
    // Set the AWS profile name
    const Aws::String profileName = "wasabi";
    
    // Set up client configuration
    Aws::Client::ClientConfiguration clientConfig;
    clientConfig.endpointOverride = "https://s3.wasabisys.com";
    
    // Set up credentials provider using profile name
    auto credentialsProvider = Aws::MakeShared<Aws::Auth::ProfileConfigFileAWSCredentialsProvider>("profile_provider");
    
    // Set up S3 client
    Aws::S3::S3Client s3Client(clientConfig); // Only pass client configuration
    
    // Open the file for upload
    std::ifstream fileStream(filePath.c_str(), std::ios::binary); // Open the file
    if (!fileStream.is_open()) {
    std::cerr << "Failed to open file: " << filePath << std::endl;
    Aws::ShutdownAPI(options);
    return false;
    }
    
    // Upload the file
    Aws::S3::Model::PutObjectRequest request;
    request.SetBucket(bucketName);
    request.SetKey("<key-name>"); // Set the key name
    
    // Set the body of the request using the file stream
    auto bodyStream = Aws::MakeShared<Aws::FStream>("UploadFile", filePath.c_str(), std::ios_base::in);
    request.SetBody(bodyStream);
    
    auto outcome = s3Client.PutObject(request);
    fileStream.close();
    
    if (!outcome.IsSuccess()) {
    std::cerr << "Failed to upload file: " << outcome.GetError().GetMessage() << std::endl;
    Aws::ShutdownAPI(options);
    return false;
    }
    
    Aws::ShutdownAPI(options);
    return true;
    }
    
    int main() {
    Aws::SDKOptions options;
    Aws::InitAPI(options);
    {
    const Aws::String bucketName = "<bucket-name>";
    const Aws::String filePath = "/path/to/your/file"; // Provide the full file path here including the file name/Key name
    
    if (uploadFileToS3WithWasabiProfile(bucketName, filePath, "us-east-1")) {
    std::cout << "File uploaded successfully to S3!" << std::endl;
    } else {
    std::cerr << "Failed to upload file to S3." << std::endl;
    }
    }
    Aws::ShutdownAPI(options);
    
    return 0;
    }

    Reading an Object From the Bucket

    #include <aws/core/Aws.h>
    #include <aws/core/auth/AWSCredentialsProvider.h>
    #include <aws/core/client/ClientConfiguration.h>
    #include <aws/s3/S3Client.h>
    #include <aws/s3/model/GetObjectRequest.h>
    #include <iostream>
    #include <fstream>
    #include <sstream>
    #include <aws/core/utils/logging/LogLevel.h>
    
    bool getObjectFromS3(const Aws::String& objectKey, const Aws::String& fromBucket, Aws::S3::S3Client& s3Client) {
        // Create GetObjectRequest
        Aws::S3::Model::GetObjectRequest request;
        request.SetBucket(fromBucket);
        request.SetKey(objectKey);
    
        // Get the object
        auto outcome = s3Client.GetObject(request);
    
        // Check if the operation was successful
        if (!outcome.IsSuccess()) {
            auto err = outcome.GetError();
            std::cerr << "Failed to get object '" << objectKey << "' from bucket '" << fromBucket << "': " << err.GetExceptionName() << ": " << err.GetMessage() << std::endl;
            return false;
        }
    
        // Read the content of the object
        const Aws::IOStream& bodyStream = outcome.GetResult().GetBody();
        std::stringstream ss;
        ss << bodyStream.rdbuf();
        std::string content = ss.str();
    
        // Print the content of the object
        std::cout << "Content of object '" << objectKey << "':" << std::endl;
        std::cout << content << std::endl;
    
        return true;
    }
    int main() {
    
        std::string profileName = "wasabi";
        setenv("AWS_PROFILE", profileName.c_str(), 1);
    
        // Initialize AWS SDK
        Aws::SDKOptions options;
        Aws::InitAPI(options);
    
        // Specify the object key and bucket name
        const Aws::String objectKey = "<key-name>";
        const Aws::String bucketName = "<bucket-name>";
    
        // Set up client configuration
        Aws::Client::ClientConfiguration clientConfig;
        clientConfig.endpointOverride = "s3.wasabisys.com";
        clientConfig.scheme = Aws::Http::Scheme::HTTPS;
        clientConfig.region = "us-east-1";
    
        // Create S3 client with client configuration
        Aws::S3::S3Client s3Client(clientConfig);
    
        // Read the object from S3
        if (getObjectFromS3(objectKey, bucketName, s3Client)) {
            std::cout << "Object downloaded successfully!" << std::endl;
        } else {
            std::cerr << "Failed to download object." << std::endl;
        }
    
        // Shutdown AWS SDK
        Aws::ShutdownAPI(options);
    
        return 0;
    }

    Deleting an Object From the Bucket

    #include <aws/core/Aws.h>
    #include <aws/core/auth/AWSCredentialsProvider.h>
    #include <aws/core/client/ClientConfiguration.h>
    #include <aws/s3/S3Client.h>
    #include <aws/s3/model/DeleteObjectRequest.h>
    #include <iostream>
    
    bool deleteObjectFromS3WithWasabiProfile(const Aws::String& objectKey,
    const Aws::String&fromBucket,const Aws::String& Region) {
        // Initialize AWS SDK
        Aws::SDKOptions options;
        Aws::InitAPI(options);
    
        // Set up client configuration
        Aws::Client::ClientConfiguration clientConfig;
        clientConfig.endpointOverride = "https://s3.wasabisys.com";
    
        // Set up credentials provider using profile name
        auto credentialsProvider = Aws::MakeShared<Aws::Auth::ProfileConfigFileAWSCredentialsProvider>("wasabi");
     
        // Set up S3 client
        Aws::S3::S3Client s3Client(clientConfig);
    
        // Delete the object
        Aws::S3::Model::DeleteObjectRequest request;
        request.SetKey(objectKey);
        request.SetBucket(fromBucket);
    
        auto outcome = s3Client.DeleteObject(request);
    
        if (!outcome.IsSuccess()) {
            std::cerr << "Failed to delete object: " << outcome.GetError().GetMessage() << std::endl;
            Aws::ShutdownAPI(options);
            return false;
        }
    
        std::cout << "Object deleted successfully from S3!" << std::endl;
    
        // Clean up and shutdown the AWS SDK
        Aws::ShutdownAPI(options);
        return true;
    }
    
    int main() {
        Aws::SDKOptions options;
        Aws::InitAPI(options);
        {
            const Aws::String objectKey = "<key-name>"; // Provide the object key here
            const Aws::String fromBucket = "<bucket-name>"; // Provide the bucket name here
            const Aws::String Region = "us-east-1"; // Provide the AWS region here
    
            if (deleteObjectFromS3WithWasabiProfile(objectKey, fromBucket, Region)) {
                std::cout << "Object deleted successfully from S3!" << std::endl;
            } else {
                std::cerr << "Failed to delete object from S3." << std::endl;
            }
        }
        Aws::ShutdownAPI(options);
    
        return 0;
    }