Amazon EC2 examples using SDK for C++ - Amazon SDK for C++
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).

Amazon EC2 examples using SDK for C++

The following code examples show you how to perform actions and implement common scenarios by using the Amazon SDK for C++ with Amazon EC2.

Actions are code excerpts from larger programs and must be run in context. While actions show you how to call individual service functions, you can see actions in context in their related scenarios and cross-service examples.

Scenarios are code examples that show you how to accomplish a specific task by calling multiple functions within the same service.

Each example includes a link to GitHub, where you can find instructions on how to set up and run the code in context.

Get started

The following code examples show how to get started using Amazon EC2.

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.

Code for the CMakeLists.txt CMake file.

# Set the minimum required version of CMake for this project. cmake_minimum_required(VERSION 3.13) # Set the AWS service components used by this project. set(SERVICE_COMPONENTS ec2) # Set this project's name. project("hello_ec2") # Set the C++ standard to use to build this target. # At least C++ 11 is required for the AWS SDK for C++. set(CMAKE_CXX_STANDARD 11) # Use the MSVC variable to determine if this is a Windows build. set(WINDOWS_BUILD ${MSVC}) if (WINDOWS_BUILD) # Set the location where CMake can find the installed libraries for the AWS SDK. string(REPLACE ";" "/aws-cpp-sdk-all;" SYSTEM_MODULE_PATH "${CMAKE_SYSTEM_PREFIX_PATH}/aws-cpp-sdk-all") list(APPEND CMAKE_PREFIX_PATH ${SYSTEM_MODULE_PATH}) endif () # Find the AWS SDK for C++ package. find_package(AWSSDK REQUIRED COMPONENTS ${SERVICE_COMPONENTS}) if (WINDOWS_BUILD AND AWSSDK_INSTALL_AS_SHARED_LIBS) # Copy relevant AWS SDK for C++ libraries into the current binary directory for running and debugging. # set(BIN_SUB_DIR "/Debug") # If you are building from the command line, you may need to uncomment this # and set the proper subdirectory to the executables' location. AWSSDK_CPY_DYN_LIBS(SERVICE_COMPONENTS "" ${CMAKE_CURRENT_BINARY_DIR}${BIN_SUB_DIR}) endif () add_executable(${PROJECT_NAME} hello_ec2.cpp) target_link_libraries(${PROJECT_NAME} ${AWSSDK_LINK_LIBRARIES})

Code for the hello_ec2.cpp source file.

#include <aws/core/Aws.h> #include <aws/ec2/EC2Client.h> #include <aws/ec2/model/DescribeInstancesRequest.h> #include <iomanip> #include <iostream> /* * A "Hello EC2" starter application which initializes an Amazon Elastic Compute Cloud (Amazon EC2) client and describes * the Amazon EC2 instances. * * main function * * Usage: 'hello_ec2' * */ int main(int argc, char **argv) { Aws::SDKOptions options; // Optionally change the log level for debugging. // options.loggingOptions.logLevel = Utils::Logging::LogLevel::Debug; Aws::InitAPI(options); // Should only be called once. int result = 0; { Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Aws::EC2::EC2Client ec2Client(clientConfig); Aws::EC2::Model::DescribeInstancesRequest request; bool header = false; bool done = false; while (!done) { auto outcome = ec2Client.DescribeInstances(request); if (outcome.IsSuccess()) { if (!header) { std::cout << std::left << std::setw(48) << "Name" << std::setw(20) << "ID" << std::setw(25) << "Ami" << std::setw(15) << "Type" << std::setw(15) << "State" << std::setw(15) << "Monitoring" << std::endl; header = true; } const std::vector<Aws::EC2::Model::Reservation> &reservations = outcome.GetResult().GetReservations(); for (const auto &reservation: reservations) { const std::vector<Aws::EC2::Model::Instance> &instances = reservation.GetInstances(); for (const auto &instance: instances) { Aws::String instanceStateString = Aws::EC2::Model::InstanceStateNameMapper::GetNameForInstanceStateName( instance.GetState().GetName()); Aws::String typeString = Aws::EC2::Model::InstanceTypeMapper::GetNameForInstanceType( instance.GetInstanceType()); Aws::String monitorString = Aws::EC2::Model::MonitoringStateMapper::GetNameForMonitoringState( instance.GetMonitoring().GetState()); Aws::String name = "Unknown"; const std::vector<Aws::EC2::Model::Tag> &tags = instance.GetTags(); auto nameIter = std::find_if(tags.cbegin(), tags.cend(), [](const Aws::EC2::Model::Tag &tag) { return tag.GetKey() == "Name"; }); if (nameIter != tags.cend()) { name = nameIter->GetValue(); } std::cout << std::setw(48) << name << std::setw(20) << instance.GetInstanceId() << std::setw(25) << instance.GetImageId() << std::setw(15) << typeString << std::setw(15) << instanceStateString << std::setw(15) << monitorString << std::endl; } } if (!outcome.GetResult().GetNextToken().empty()) { request.SetNextToken(outcome.GetResult().GetNextToken()); } else { done = true; } } else { std::cerr << "Failed to describe EC2 instances:" << outcome.GetError().GetMessage() << std::endl; result = 1; break; } } } Aws::ShutdownAPI(options); // Should only be called once. return result; }
Topics

Actions

The following code example shows how to use AllocateAddress.

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::AllocateAddressRequest request; request.SetDomain(Aws::EC2::Model::DomainType::vpc); const Aws::EC2::Model::AllocateAddressOutcome outcome = ec2Client.AllocateAddress(request); if (!outcome.IsSuccess()) { std::cerr << "Failed to allocate Elastic IP address:" << outcome.GetError().GetMessage() << std::endl; return false; } allocationId = outcome.GetResult().GetAllocationId();
  • For API details, see AllocateAddress in Amazon SDK for C++ API Reference.

The following code example shows how to use AssociateAddress.

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::AssociateAddressRequest associate_request; associate_request.SetInstanceId(instanceId); associate_request.SetAllocationId(allocationId); const Aws::EC2::Model::AssociateAddressOutcome associate_outcome = ec2Client.AssociateAddress(associate_request); if (!associate_outcome.IsSuccess()) { std::cerr << "Failed to associate Elastic IP address " << allocationId << " with instance " << instanceId << ":" << associate_outcome.GetError().GetMessage() << std::endl; return false; } std::cout << "Successfully associated Elastic IP address " << allocationId << " with instance " << instanceId << std::endl;

The following code example shows how to use AuthorizeSecurityGroupIngress.

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::IpRange ip_range; ip_range.SetCidrIp("0.0.0.0/0"); Aws::EC2::Model::IpPermission permission1; permission1.SetIpProtocol("tcp"); permission1.SetToPort(80); permission1.SetFromPort(80); permission1.AddIpRanges(ip_range); authorize_request.AddIpPermissions(permission1); Aws::EC2::Model::IpPermission permission2; permission2.SetIpProtocol("tcp"); permission2.SetToPort(22); permission2.SetFromPort(22); permission2.AddIpRanges(ip_range); authorize_request.AddIpPermissions(permission2); const Aws::EC2::Model::AuthorizeSecurityGroupIngressOutcome authorizeOutcome = ec2Client.AuthorizeSecurityGroupIngress(authorizeRequest); if (!authorizeOutcome.IsSuccess()) { std::cerr << "Failed to set ingress policy for security group " << groupName << ":" << authorizeOutcome.GetError().GetMessage() << std::endl; return false; } std::cout << "Successfully added ingress policy to security group " << groupName << std::endl;

The following code example shows how to use CreateKeyPair.

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.

The following code example shows how to use CreateSecurityGroup.

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::CreateSecurityGroupRequest request; request.SetGroupName(groupName); request.SetDescription(description); request.SetVpcId(vpcID); const Aws::EC2::Model::CreateSecurityGroupOutcome outcome = ec2Client.CreateSecurityGroup(request); if (!outcome.IsSuccess()) { std::cerr << "Failed to create security group:" << outcome.GetError().GetMessage() << std::endl; return false; } std::cout << "Successfully created security group named " << groupName << std::endl;

The following code example shows how to use CreateTags.

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::Tag nameTag; nameTag.SetKey("Name"); nameTag.SetValue(instanceName); Aws::EC2::Model::CreateTagsRequest createRequest; createRequest.AddResources(instanceID); createRequest.AddTags(nameTag); Aws::EC2::Model::CreateTagsOutcome createOutcome = ec2Client.CreateTags( createRequest); if (!createOutcome.IsSuccess()) { std::cerr << "Failed to tag ec2 instance " << instanceID << " with name " << instanceName << ":" << createOutcome.GetError().GetMessage() << std::endl; return false; }
  • For API details, see CreateTags in Amazon SDK for C++ API Reference.

The following code example shows how to use DeleteKeyPair.

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::DeleteKeyPairRequest request; request.SetKeyName(keyPairName); const Aws::EC2::Model::DeleteKeyPairOutcome outcome = ec2Client.DeleteKeyPair( request); if (!outcome.IsSuccess()) { std::cerr << "Failed to delete key pair " << keyPairName << ":" << outcome.GetError().GetMessage() << std::endl; } else { std::cout << "Successfully deleted key pair named " << keyPairName << std::endl; }
  • For API details, see DeleteKeyPair in Amazon SDK for C++ API Reference.

The following code example shows how to use DeleteSecurityGroup.

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::DeleteSecurityGroupRequest request; request.SetGroupId(securityGroupID); auto outcome = ec2Client.DeleteSecurityGroup(request); if (!outcome.IsSuccess()) { std::cerr << "Failed to delete security group " << securityGroupID << ":" << outcome.GetError().GetMessage() << std::endl; } else { std::cout << "Successfully deleted security group " << securityGroupID << std::endl; }

The following code example shows how to use DescribeAddresses.

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::DescribeAddressesRequest request; auto outcome = ec2Client.DescribeAddresses(request); if (outcome.IsSuccess()) { std::cout << std::left << std::setw(20) << "InstanceId" << std::setw(15) << "Public IP" << std::setw(10) << "Domain" << std::setw(30) << "Allocation ID" << std::setw(25) << "NIC ID" << std::endl; const auto &addresses = outcome.GetResult().GetAddresses(); for (const auto &address: addresses) { Aws::String domainString = Aws::EC2::Model::DomainTypeMapper::GetNameForDomainType( address.GetDomain()); std::cout << std::left << std::setw(20) << address.GetInstanceId() << std::setw(15) << address.GetPublicIp() << std::setw(10) << domainString << std::setw(30) << address.GetAllocationId() << std::setw(25) << address.GetNetworkInterfaceId() << std::endl; } } else { std::cerr << "Failed to describe Elastic IP addresses:" << outcome.GetError().GetMessage() << std::endl; }

The following code example shows how to use DescribeAvailabilityZones.

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::DescribeAvailabilityZonesRequest describe_request; auto describe_outcome = ec2Client.DescribeAvailabilityZones(describe_request); if (describe_outcome.IsSuccess()) { std::cout << std::left << std::setw(32) << "ZoneName" << std::setw(20) << "State" << std::setw(32) << "Region" << std::endl; const auto &zones = describe_outcome.GetResult().GetAvailabilityZones(); for (const auto &zone: zones) { Aws::String stateString = Aws::EC2::Model::AvailabilityZoneStateMapper::GetNameForAvailabilityZoneState( zone.GetState()); std::cout << std::left << std::setw(32) << zone.GetZoneName() << std::setw(20) << stateString << std::setw(32) << zone.GetRegionName() << std::endl; } } else { std::cerr << "Failed to describe availability zones:" << describe_outcome.GetError().GetMessage() << std::endl; result = false; }

The following code example shows how to use DescribeInstances.

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::DescribeInstancesRequest request; bool header = false; bool done = false; while (!done) { auto outcome = ec2Client.DescribeInstances(request); if (outcome.IsSuccess()) { if (!header) { std::cout << std::left << std::setw(48) << "Name" << std::setw(20) << "ID" << std::setw(25) << "Ami" << std::setw(15) << "Type" << std::setw(15) << "State" << std::setw(15) << "Monitoring" << std::endl; header = true; } const std::vector<Aws::EC2::Model::Reservation> &reservations = outcome.GetResult().GetReservations(); for (const auto &reservation: reservations) { const std::vector<Aws::EC2::Model::Instance> &instances = reservation.GetInstances(); for (const auto &instance: instances) { Aws::String instanceStateString = Aws::EC2::Model::InstanceStateNameMapper::GetNameForInstanceStateName( instance.GetState().GetName()); Aws::String typeString = Aws::EC2::Model::InstanceTypeMapper::GetNameForInstanceType( instance.GetInstanceType()); Aws::String monitorString = Aws::EC2::Model::MonitoringStateMapper::GetNameForMonitoringState( instance.GetMonitoring().GetState()); Aws::String name = "Unknown"; const std::vector<Aws::EC2::Model::Tag> &tags = instance.GetTags(); auto nameIter = std::find_if(tags.cbegin(), tags.cend(), [](const Aws::EC2::Model::Tag &tag) { return tag.GetKey() == "Name"; }); if (nameIter != tags.cend()) { name = nameIter->GetValue(); } std::cout << std::setw(48) << name << std::setw(20) << instance.GetInstanceId() << std::setw(25) << instance.GetImageId() << std::setw(15) << typeString << std::setw(15) << instanceStateString << std::setw(15) << monitorString << std::endl; } } if (!outcome.GetResult().GetNextToken().empty()) { request.SetNextToken(outcome.GetResult().GetNextToken()); } else { done = true; } } else { std::cerr << "Failed to describe EC2 instances:" << outcome.GetError().GetMessage() << std::endl; return false; } }

The following code example shows how to use DescribeKeyPairs.

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::DescribeKeyPairsRequest request; auto outcome = ec2Client.DescribeKeyPairs(request); if (outcome.IsSuccess()) { std::cout << std::left << std::setw(32) << "Name" << std::setw(64) << "Fingerprint" << std::endl; const std::vector<Aws::EC2::Model::KeyPairInfo> &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::cerr << "Failed to describe key pairs:" << outcome.GetError().GetMessage() << std::endl; }

The following code example shows how to use DescribeRegions.

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::DescribeRegionsRequest request; auto outcome = ec2Client.DescribeRegions(request); bool result = true; if (outcome.IsSuccess()) { std::cout << std::left << std::setw(32) << "RegionName" << std::setw(64) << "Endpoint" << std::endl; const auto &regions = outcome.GetResult().GetRegions(); for (const auto &region: regions) { std::cout << std::left << std::setw(32) << region.GetRegionName() << std::setw(64) << region.GetEndpoint() << std::endl; } } else { std::cerr << "Failed to describe regions:" << outcome.GetError().GetMessage() << std::endl; result = false; }
  • For API details, see DescribeRegions in Amazon SDK for C++ API Reference.

The following code example shows how to use DescribeSecurityGroups.

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::DescribeSecurityGroupsRequest request; if (!groupID.empty()) { request.AddGroupIds(groupID); } Aws::String nextToken; do { if (!nextToken.empty()) { request.SetNextToken(nextToken); } auto outcome = ec2Client.DescribeSecurityGroups(request); if (outcome.IsSuccess()) { std::cout << std::left << std::setw(32) << "Name" << std::setw(30) << "GroupId" << std::setw(30) << "VpcId" << std::setw(64) << "Description" << std::endl; const std::vector<Aws::EC2::Model::SecurityGroup> &securityGroups = outcome.GetResult().GetSecurityGroups(); for (const auto &securityGroup: securityGroups) { std::cout << std::left << std::setw(32) << securityGroup.GetGroupName() << std::setw(30) << securityGroup.GetGroupId() << std::setw(30) << securityGroup.GetVpcId() << std::setw(64) << securityGroup.GetDescription() << std::endl; } } else { std::cerr << "Failed to describe security groups:" << outcome.GetError().GetMessage() << std::endl; return false; } nextToken = outcome.GetResult().GetNextToken(); } while (!nextToken.empty());

The following code example shows how to use MonitorInstances.

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::MonitorInstancesRequest request; request.AddInstanceIds(instanceId); request.SetDryRun(true); auto dry_run_outcome = ec2Client.MonitorInstances(request); if (dry_run_outcome.IsSuccess()) { std::cerr << "Failed dry run to enable monitoring on instance. A dry run should trigger an error." << std::endl; return false; } else if (dry_run_outcome.GetError().GetErrorType() != Aws::EC2::EC2Errors::DRY_RUN_OPERATION) { std::cerr << "Failed dry run to enable monitoring on instance " << instanceId << ": " << dry_run_outcome.GetError().GetMessage() << std::endl; return false; } request.SetDryRun(false); auto monitorInstancesOutcome = ec2Client.MonitorInstances(request); if (!monitorInstancesOutcome.IsSuccess()) { std::cerr << "Failed to enable monitoring on instance " << instanceId << ": " << monitorInstancesOutcome.GetError().GetMessage() << std::endl; } else { std::cout << "Successfully enabled monitoring on instance " << instanceId << std::endl; }

The following code example shows how to use RebootInstances.

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::RebootInstancesRequest request; request.AddInstanceIds(instanceId); request.SetDryRun(true); auto dry_run_outcome = ec2Client.RebootInstances(request); if (dry_run_outcome.IsSuccess()) { std::cerr << "Failed dry run to reboot on instance. A dry run should trigger an error." << std::endl; return false; } else if (dry_run_outcome.GetError().GetErrorType() != Aws::EC2::EC2Errors::DRY_RUN_OPERATION) { std::cout << "Failed dry run to reboot instance " << instanceId << ": " << dry_run_outcome.GetError().GetMessage() << std::endl; return false; } request.SetDryRun(false); auto outcome = ec2Client.RebootInstances(request); if (!outcome.IsSuccess()) { std::cout << "Failed to reboot instance " << instanceId << ": " << outcome.GetError().GetMessage() << std::endl; } else { std::cout << "Successfully rebooted instance " << instanceId << std::endl; }
  • For API details, see RebootInstances in Amazon SDK for C++ API Reference.

The following code example shows how to use ReleaseAddress.

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 ec2(clientConfiguration); Aws::EC2::Model::ReleaseAddressRequest request; request.SetAllocationId(allocationID); auto outcome = ec2.ReleaseAddress(request); if (!outcome.IsSuccess()) { std::cerr << "Failed to release Elastic IP address " << allocationID << ":" << outcome.GetError().GetMessage() << std::endl; } else { std::cout << "Successfully released Elastic IP address " << allocationID << std::endl; }
  • For API details, see ReleaseAddress in Amazon SDK for C++ API Reference.

The following code example shows how to use RunInstances.

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::RunInstancesRequest runRequest; runRequest.SetImageId(amiId); runRequest.SetInstanceType(Aws::EC2::Model::InstanceType::t1_micro); runRequest.SetMinCount(1); runRequest.SetMaxCount(1); Aws::EC2::Model::RunInstancesOutcome runOutcome = ec2Client.RunInstances( runRequest); if (!runOutcome.IsSuccess()) { std::cerr << "Failed to launch EC2 instance " << instanceName << " based on ami " << amiId << ":" << runOutcome.GetError().GetMessage() << std::endl; return false; } const Aws::Vector<Aws::EC2::Model::Instance> &instances = runOutcome.GetResult().GetInstances(); if (instances.empty()) { std::cerr << "Failed to launch EC2 instance " << instanceName << " based on ami " << amiId << ":" << runOutcome.GetError().GetMessage() << std::endl; return false; } instanceID = instances[0].GetInstanceId();
  • For API details, see RunInstances in Amazon SDK for C++ API Reference.

The following code example shows how to use StartInstances.

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::StartInstancesRequest start_request; start_request.AddInstanceIds(instanceId); start_request.SetDryRun(true); auto dry_run_outcome = ec2Client.StartInstances(start_request); if (dry_run_outcome.IsSuccess()) { std::cerr << "Failed dry run to start instance. A dry run should trigger an error." << std::endl; return false; } else if (dry_run_outcome.GetError().GetErrorType() != Aws::EC2::EC2Errors::DRY_RUN_OPERATION) { std::cout << "Failed dry run to start instance " << instanceId << ": " << dry_run_outcome.GetError().GetMessage() << std::endl; return false; } start_request.SetDryRun(false); auto start_instancesOutcome = ec2Client.StartInstances(start_request); if (!start_instancesOutcome.IsSuccess()) { std::cout << "Failed to start instance " << instanceId << ": " << start_instancesOutcome.GetError().GetMessage() << std::endl; } else { std::cout << "Successfully started instance " << instanceId << std::endl; }
  • For API details, see StartInstances in Amazon SDK for C++ API Reference.

The following code example shows how to use StopInstances.

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::StopInstancesRequest request; request.AddInstanceIds(instanceId); request.SetDryRun(true); auto dry_run_outcome = ec2Client.StopInstances(request); if (dry_run_outcome.IsSuccess()) { std::cerr << "Failed dry run to stop instance. A dry run should trigger an error." << std::endl; return false; } else if (dry_run_outcome.GetError().GetErrorType() != Aws::EC2::EC2Errors::DRY_RUN_OPERATION) { std::cout << "Failed dry run to stop instance " << instanceId << ": " << dry_run_outcome.GetError().GetMessage() << std::endl; return false; } request.SetDryRun(false); auto outcome = ec2Client.StopInstances(request); if (!outcome.IsSuccess()) { std::cout << "Failed to stop instance " << instanceId << ": " << outcome.GetError().GetMessage() << std::endl; } else { std::cout << "Successfully stopped instance " << instanceId << std::endl; }
  • For API details, see StopInstances in Amazon SDK for C++ API Reference.

The following code example shows how to use TerminateInstances.

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::TerminateInstancesRequest request; request.SetInstanceIds({instanceID}); Aws::EC2::Model::TerminateInstancesOutcome outcome = ec2Client.TerminateInstances(request); if (outcome.IsSuccess()) { std::cout << "Ec2 instance '" << instanceID << "' was terminated." << std::endl; } else { std::cerr << "Failed to terminate ec2 instance " << instanceID << ", " << outcome.GetError().GetMessage() << std::endl; return false; }

The following code example shows how to use UnmonitorInstances.

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::UnmonitorInstancesRequest unrequest; unrequest.AddInstanceIds(instanceId); unrequest.SetDryRun(true); auto undryRunOutcome = ec2Client.UnmonitorInstances(unrequest); if (undryRunOutcome.IsSuccess()) { std::cerr << "Failed dry run to disable monitoring on instance. A dry run should trigger an error." << std::endl; return false; } else if (undryRunOutcome.GetError().GetErrorType() != Aws::EC2::EC2Errors::DRY_RUN_OPERATION) { std::cout << "Failed dry run to disable monitoring on instance " << instanceId << ": " << undryRunOutcome.GetError().GetMessage() << std::endl; return false; } unrequest.SetDryRun(false); auto unmonitorInstancesOutcome = ec2Client.UnmonitorInstances(unrequest); if (!unmonitorInstancesOutcome.IsSuccess()) { std::cout << "Failed to disable monitoring on instance " << instanceId << ": " << unmonitorInstancesOutcome.GetError().GetMessage() << std::endl; } else { std::cout << "Successfully disable monitoring on instance " << instanceId << std::endl; }