Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.
Esempi di codice per l'EC2utilizzo di Amazon AWS SDKs
I seguenti esempi di codice mostrano come usare Amazon EC2 con un kit di sviluppo AWS software (SDK).
Le nozioni di base sono esempi di codice che mostrano come eseguire le operazioni essenziali all'interno di un servizio.
Le operazioni sono estratti di codice da programmi più grandi e devono essere eseguite nel contesto. Sebbene le operazioni mostrino come richiamare le singole funzioni del servizio, è possibile visualizzarle contestualizzate negli scenari correlati.
Gli scenari sono esempi di codice che mostrano come eseguire un'attività specifica richiamando più funzioni all'interno dello stesso servizio o combinate con altri Servizi AWS.
Per un elenco completo di guide per AWS SDK sviluppatori ed esempi di codice, consultaCrea EC2 risorse Amazon utilizzando un AWS SDK. Questo argomento include anche informazioni su come iniziare e dettagli sulle SDK versioni precedenti.
Nozioni di base
I seguenti esempi di codice mostrano come iniziare a usare AmazonEC2.
- .NET
-
- AWS SDK for .NET
-
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>Async task.</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>();
try
{
// Retrieve information for up to 10 Amazon EC2 security groups.
var request = new DescribeSecurityGroupsRequest { MaxResults = 10, };
var securityGroups = new List<SecurityGroup>();
var paginatorForSecurityGroups =
ec2Client.Paginators.DescribeSecurityGroups(request);
await foreach (var securityGroup in paginatorForSecurityGroups.SecurityGroups)
{
securityGroups.Add(securityGroup);
}
// Now print the security groups returned by the call to
// DescribeSecurityGroupsAsync.
Console.WriteLine("Welcome to the EC2 Hello Service example. " +
"\nLet's list your Security Groups:");
securityGroups.ForEach(group =>
{
Console.WriteLine(
$"Security group: {group.GroupName} ID: {group.GroupId}");
});
}
catch (AmazonEC2Exception ex)
{
Console.WriteLine($"An Amazon EC2 service error occurred while listing security groups. {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred while listing security groups. {ex.Message}");
}
}
}
- C++
-
- SDKper C++
-
Codice per il CMakeLists file.txtCMake.
# 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})
Codice per il file origine 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) {
(void)argc;
(void)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) {
Aws::EC2::Model::DescribeInstancesOutcome 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;
}
- Java
-
- SDKper Java 2.x
-
/**
* Asynchronously describes the security groups for the specified group ID.
*
* @param groupName the name of the security group to describe
* @return a {@link CompletableFuture} that represents the asynchronous operation
* of describing the security groups. The future will complete with a
* {@link DescribeSecurityGroupsResponse} object that contains the
* security group information.
*/
public CompletableFuture<String> describeSecurityGroupArnByNameAsync(String groupName) {
DescribeSecurityGroupsRequest request = DescribeSecurityGroupsRequest.builder()
.groupNames(groupName)
.build();
DescribeSecurityGroupsPublisher paginator = getAsyncClient().describeSecurityGroupsPaginator(request);
AtomicReference<String> groupIdRef = new AtomicReference<>();
return paginator.subscribe(response -> {
response.securityGroups().stream()
.filter(securityGroup -> securityGroup.groupName().equals(groupName))
.findFirst()
.ifPresent(securityGroup -> groupIdRef.set(securityGroup.groupId()));
}).thenApply(v -> {
String groupId = groupIdRef.get();
if (groupId == null) {
throw new RuntimeException("No security group found with the name: " + groupName);
}
return groupId;
}).exceptionally(ex -> {
logger.info("Failed to describe security group: " + ex.getMessage());
throw new RuntimeException("Failed to describe security group", ex);
});
}
- JavaScript
-
- SDKper JavaScript (v3)
-
import { DescribeSecurityGroupsCommand, EC2Client } from "@aws-sdk/client-ec2";
// Call DescribeSecurityGroups and display the result.
export const main = async () => {
const client = new EC2Client();
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);
}
};
// Call function if run directly.
import { fileURLToPath } from "node:url";
if (process.argv[1] === fileURLToPath(import.meta.url)) {
main();
}
- Kotlin
-
- SDKper Kotlin
-
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}")
}
}
}
- Python
-
- SDKper Python (Boto3)
-
def hello_ec2(ec2_client):
"""
Use the AWS SDK for Python (Boto3) to list the security groups in your account.
This example uses the default settings specified in your shared credentials
and config files.
:param ec2_client: A Boto3 EC2 client. This client provides low-level
access to AWS EC2 services.
"""
print("Hello, Amazon EC2! Let's list up to 10 of your security groups:")
try:
paginator = ec2_client.get_paginator("describe_security_groups")
response_iterator = paginator.paginate(MaxResults=10)
for page in response_iterator:
for sg in page["SecurityGroups"]:
logger.info(f"\t{sg['GroupId']}: {sg['GroupName']}")
except ClientError as err:
logger.error("Failed to list security groups.")
if err.response["Error"]["Code"] == "AccessDeniedException":
logger.error("You do not have permission to list security groups.")
raise
if __name__ == "__main__":
hello_ec2(boto3.client("ec2"))
- Ruby
-
- SDKper Ruby
-
require 'aws-sdk-ec2'
require 'logger'
# EC2Manager is a class responsible for managing EC2 operations
# such as listing all EC2 instances in the current AWS account.
class EC2Manager
def initialize(client)
@client = client
@logger = Logger.new($stdout)
end
# Lists and prints all EC2 instances in the current AWS account.
def list_instances
@logger.info('Listing instances')
instances = fetch_instances
if instances.empty?
@logger.info('You have no instances')
else
print_instances(instances)
end
end
private
# Fetches all EC2 instances using pagination.
#
# @return [Array<Aws::EC2::Types::Instance>] List of EC2 instances.
def fetch_instances
paginator = @client.describe_instances
instances = []
paginator.each_page do |page|
page.reservations.each do |reservation|
reservation.instances.each do |instance|
instances << instance
end
end
end
instances
end
# Prints details of the given EC2 instances.
#
# @param instances [Array<Aws::EC2::Types::Instance>] List of EC2 instances to print.
def print_instances(instances)
instances.each do |instance|
@logger.info("Instance ID: #{instance.instance_id}")
@logger.info("Instance Type: #{instance.instance_type}")
@logger.info("Public IP: #{instance.public_ip_address}")
@logger.info("Public DNS Name: #{instance.public_dns_name}")
@logger.info("\n")
end
end
end
if $PROGRAM_NAME == __FILE__
ec2_client = Aws::EC2::Client.new(region: 'us-west-2')
manager = EC2Manager.new(ec2_client)
manager.list_instances
end
- Rust
-
- SDKper Rust
-
async fn show_security_groups(client: &aws_sdk_ec2::Client, group_ids: Vec<String>) {
let response = client
.describe_security_groups()
.set_group_ids(Some(group_ids))
.send()
.await;
match response {
Ok(output) => {
for group in output.security_groups() {
println!(
"Found Security Group {} ({}), vpc id {} and description {}",
group.group_name().unwrap_or("unknown"),
group.group_id().unwrap_or("id-unknown"),
group.vpc_id().unwrap_or("vpcid-unknown"),
group.description().unwrap_or("(none)")
);
}
}
Err(err) => {
let err = err.into_service_error();
let meta = err.meta();
let message = meta.message().unwrap_or("unknown");
let code = meta.code().unwrap_or("unknown");
eprintln!("Error listing EC2 Security Groups: ({code}) {message}");
}
}
}