使用 AWS SDK 的 Amazon EC2 程式碼範例
下列程式碼範例示範如何使用 Amazon EC2 搭配 AWS 軟體開發套件 (SDK)。
動作是大型程式的程式碼摘錄,必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數,但您可以在其相關情境和跨服務範例中查看內容中的動作。
Scenarios (案例) 是向您展示如何呼叫相同服務中的多個函數來完成特定任務的程式碼範例。
如需完整的 AWS SDK 開發人員指南和程式碼範例清單,請參閱使用 Amazon EC2 搭配 AWS SDK。此主題也包含入門相關資訊和舊版 SDK 的詳細資訊。
開始使用
下列程式碼範例示範如何開始使用 Amazon EC2。
- .NET
-
- AWS SDK for .NET
-
注意
GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 namespace EC2Actions; public class HelloEc2 { /// <summary> /// HelloEc2 lists the existing security groups for the default users. /// </summary> /// <param name="args">Command line arguments</param> /// <returns>A Task object.</returns> static async Task Main(string[] args) { // Set up dependency injection for Amazon Elastic Compute Cloud (Amazon EC2). using var host = Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder(args) .ConfigureServices((_, services) => services.AddAWSService<IAmazonEC2>() .AddTransient<EC2Wrapper>() ) .Build(); // Now the client is available for injection. var ec2Client = host.Services.GetRequiredService<IAmazonEC2>(); var request = new DescribeSecurityGroupsRequest { MaxResults = 10, }; // Retrieve information about up to 10 Amazon EC2 security groups. var response = await ec2Client.DescribeSecurityGroupsAsync(request); // Now print the security groups returned by the call to // DescribeSecurityGroupsAsync. Console.WriteLine("Security Groups:"); response.SecurityGroups.ForEach(group => { Console.WriteLine($"Security group: {group.GroupName} ID: {group.GroupId}"); }); } }
-
如需 API 詳細資訊,請參閱《AWS SDK for .NET API 參考》中的 DescribeSecurityGroups。
-
- C++
-
- 適用於 C++ 的開發套件
-
注意
GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 CMakeLists.txt CMake 檔案的程式碼。
# 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) # 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})
hello_ec2.cpp 來源檔案的程式碼。
#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; }
-
如需 API 詳細資訊,請參閱《AWS SDK for C++ API 參考》中的 DescribeSecurityGroups。
-
- Java
-
- 適用於 Java 2.x 的開發套件
-
注意
GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 public static void describeEC2SecurityGroups(Ec2Client ec2, String groupId) { try { DescribeSecurityGroupsRequest request = DescribeSecurityGroupsRequest.builder() .groupIds(groupId) .build(); DescribeSecurityGroupsResponse response = ec2.describeSecurityGroups(request); for(SecurityGroup group : response.securityGroups()) { System.out.printf( "Found Security Group with id %s, " + "vpc id %s " + "and description %s", group.groupId(), group.vpcId(), group.description()); } } catch (Ec2Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
-
如需 API 詳細資訊,請參閱《AWS SDK for Java 2.x API 參考》中的 DescribeSecurityGroups。
-
- JavaScript
-
- SDK for JavaScript (v3)
-
注意
GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 import { DescribeSecurityGroupsCommand } from "@aws-sdk/client-ec2"; import { client } from "./libs/client.js"; // Call DescribeSecurityGroups and display the result. export const main = async () => { try { const { SecurityGroups } = await client.send( new DescribeSecurityGroupsCommand({}), ); const securityGroupList = SecurityGroups.slice(0, 9) .map((sg) => ` • ${sg.GroupId}: ${sg.GroupName}`) .join("\n"); console.log( "Hello, Amazon EC2! Let's list up to 10 of your security groups:", ); console.log(securityGroupList); } catch (err) { console.error(err); } };
-
如需 API 詳細資訊,請參閱《AWS SDK for JavaScript API 參考》中的 DescribeSecurityGroups。
-
- Kotlin
-
- 適用於 Kotlin 的開發套件
-
注意
這是預覽版本之服務的發行前版本文件。內容可能變動。
注意
GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 suspend fun describeEC2SecurityGroups(groupId: String) { val request = DescribeSecurityGroupsRequest { groupIds = listOf(groupId) } Ec2Client { region = "us-west-2" }.use { ec2 -> val response = ec2.describeSecurityGroups(request) response.securityGroups?.forEach { group -> println("Found Security Group with id ${group.groupId}, vpc id ${group.vpcId} and description ${group.description}") } } }
-
如需 API 詳細資訊,請參閱《適用於 Kotlin 的 AWS SDK API 參考》中的 DescribeSecurityGroups
。
-
- Python
-
- 適用於 Python (Boto3) 的開發套件
-
注意
GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 import boto3 def hello_ec2(ec2_resource): """ Use the AWS SDK for Python (Boto3) to create an Amazon Elastic Compute Cloud (Amazon EC2) resource and list the security groups in your account. This example uses the default settings specified in your shared credentials and config files. :param ec2_resource: A Boto3 EC2 ServiceResource object. This object is a high-level resource that wraps the low-level EC2 service API. """ print("Hello, Amazon EC2! Let's list up to 10 of your security groups:") for sg in ec2_resource.security_groups.limit(10): print(f"\t{sg.id}: {sg.group_name}") if __name__ == "__main__": hello_ec2(boto3.resource("ec2"))
-
如需 API 詳細資訊,請參閱《適用於 Python (Boto3) 的 AWS SDK API 參考》中的 DescribeSecurityGroups。
-
程式碼範例
- 動作
- 將標籤新增到資源
- 配置彈性 IP 地址
- 將彈性 IP 地址與執行個體建立關聯
- 建立 Amazon Virtual Private Cloud (Amazon VPC)
- 建立啟動範本
- 建立路由表
- 建立安全群組
- 建立安全金鑰對
- 建立子網
- 建立及執行執行個體
- 刪除啟動範本
- 刪除安全群組
- 刪除安全金鑰對
- 刪除快照
- 描述可用區域
- 描述區域
- 描述執行個體狀態
- 描述執行個體
- 描述快照
- 停用詳細監控功能
- 取消彈性 IP 地址與執行個體的關聯
- 啟用監控功能
- 取得有關 Amazon Machine Images 的資料
- 取得有關安全群組的資料
- 取得有關執行個體類型的資料
- 取得與執行個體相關聯的執行個體設定檔的資料
- 取得彈性 IP 地址的詳細資訊
- 獲取預設 VPC
- 獲取 VPC 的預設子網路
- 列出安全金鑰對
- 重新啟動執行個體
- 釋出彈性 IP 地址
- 取代與執行個體相關聯的執行個體設定檔
- 為安全群組設定輸入規則
- 啟動執行個體
- 停止執行個體
- 終止執行個體
- 案例