RunInstances 搭配 a AWS SDK 或 CLI 使用 - AWS SDK 程式碼範例

文件 AWS SDK AWS 範例 SDK 儲存庫中有更多可用的 GitHub 範例。

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

RunInstances 搭配 a AWS SDK 或 CLI 使用

下列程式碼範例示範如何使用 RunInstances

動作範例是大型程式的程式碼摘錄,必須在內容中執行。您可以在下列程式碼範例的內容中看到此動作:

.NET
AWS SDK for .NET
注意

還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

/// <summary> /// Create and run an EC2 instance. /// </summary> /// <param name="ImageId">The image Id of the image used as a basis for the /// EC2 instance.</param> /// <param name="instanceType">The instance type of the EC2 instance to create.</param> /// <param name="keyName">The name of the key pair to associate with the /// instance.</param> /// <param name="groupId">The Id of the Amazon EC2 security group that will be /// allowed to interact with the new EC2 instance.</param> /// <returns>The instance Id of the new EC2 instance.</returns> public async Task<string> RunInstances(string imageId, string instanceType, string keyName, string groupId) { try { var request = new RunInstancesRequest { ImageId = imageId, InstanceType = instanceType, KeyName = keyName, MinCount = 1, MaxCount = 1, SecurityGroupIds = new List<string> { groupId } }; var response = await _amazonEC2.RunInstancesAsync(request); var instanceId = response.Reservation.Instances[0].InstanceId; Console.Write("Waiting for the instance to start."); await WaitForInstanceState(instanceId, InstanceStateName.Running); return instanceId; } catch (AmazonEC2Exception ec2Exception) { if (ec2Exception.ErrorCode == "InvalidGroupId.NotFound") { _logger.LogError( $"GroupId {groupId} was not found. {ec2Exception.Message}"); } throw; } catch (Exception ex) { _logger.LogError( $"An error occurred while running the instance.: {ex.Message}"); throw; } }
  • 如需 API 詳細資訊,請參閱 RunInstances AWS SDK for .NET 參考中的 API

Bash
AWS CLI 使用 Bash 指令碼
注意

還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

############################################################################### # function ec2_run_instances # # This function launches one or more Amazon Elastic Compute Cloud (Amazon EC2) instances. # # Parameters: # -i image_id - The ID of the Amazon Machine Image (AMI) to use. # -t instance_type - The instance type to use (e.g., t2.micro). # -k key_pair_name - The name of the key pair to use. # -s security_group_id - The ID of the security group to use. # -c count - The number of instances to launch (default: 1). # -h - Display help. # # Returns: # 0 - If successful. # 1 - If it fails. ############################################################################### function ec2_run_instances() { local image_id instance_type key_pair_name security_group_id count response local option OPTARG # Required to use getopts command in a function. # bashsupport disable=BP5008 function usage() { echo "function ec2_run_instances" echo "Launches one or more Amazon Elastic Compute Cloud (Amazon EC2) instances." echo " -i image_id - The ID of the Amazon Machine Image (AMI) to use." echo " -t instance_type - The instance type to use (e.g., t2.micro)." echo " -k key_pair_name - The name of the key pair to use." echo " -s security_group_id - The ID of the security group to use." echo " -c count - The number of instances to launch (default: 1)." echo " -h - Display help." echo "" } # Retrieve the calling parameters. while getopts "i:t:k:s:c:h" option; do case "${option}" in i) image_id="${OPTARG}" ;; t) instance_type="${OPTARG}" ;; k) key_pair_name="${OPTARG}" ;; s) security_group_id="${OPTARG}" ;; c) count="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 if [[ -z "$image_id" ]]; then errecho "ERROR: You must provide an Amazon Machine Image (AMI) ID with the -i parameter." usage return 1 fi if [[ -z "$instance_type" ]]; then errecho "ERROR: You must provide an instance type with the -t parameter." usage return 1 fi if [[ -z "$key_pair_name" ]]; then errecho "ERROR: You must provide a key pair name with the -k parameter." usage return 1 fi if [[ -z "$security_group_id" ]]; then errecho "ERROR: You must provide a security group ID with the -s parameter." usage return 1 fi if [[ -z "$count" ]]; then count=1 fi response=$(aws ec2 run-instances \ --image-id "$image_id" \ --instance-type "$instance_type" \ --key-name "$key_pair_name" \ --security-group-ids "$security_group_id" \ --count "$count" \ --query 'Instances[*].[InstanceId]' \ --output text) || { aws_cli_error_log ${?} errecho "ERROR: AWS reports run-instances operation failed.$response" return 1 } echo "$response" return 0 }

此範例中使用的公用程式函數。

############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################## # function aws_cli_error_log() # # This function is used to log the error messages from the AWS CLI. # # The function expects the following argument: # $1 - The error code returned by the AWS CLI. # # Returns: # 0: - Success. # ############################################################################## function aws_cli_error_log() { local err_code=$1 errecho "Error code : $err_code" if [ "$err_code" == 1 ]; then errecho " One or more S3 transfers failed." elif [ "$err_code" == 2 ]; then errecho " Command line failed to parse." elif [ "$err_code" == 130 ]; then errecho " Process received SIGINT." elif [ "$err_code" == 252 ]; then errecho " Command syntax invalid." elif [ "$err_code" == 253 ]; then errecho " The system environment or configuration was invalid." elif [ "$err_code" == 254 ]; then errecho " The service returned an error." elif [ "$err_code" == 255 ]; then errecho " 255 is a catch-all error." fi return 0 }
  • 如需 API 詳細資訊,請參閱 AWS CLI 命令參考中的 RunInstances

C++
C++ 的 SDK
注意

還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

//! Launch an Amazon Elastic Compute Cloud (Amazon EC2) instance. /*! \param instanceName: A name for the EC2 instance. \param amiId: An Amazon Machine Image (AMI) identifier. \param[out] instanceID: String to return the instance ID. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::EC2::runInstance(const Aws::String &instanceName, const Aws::String &amiId, Aws::String &instanceID, const Aws::Client::ClientConfiguration &clientConfiguration) { 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(); return true; }
  • 如需 API 詳細資訊,請參閱 RunInstances AWS SDK for C++ 參考中的 API

CLI
AWS CLI

範例 1:在預設子網路中啟動執行個體

下列run-instances範例會在目前區域的預設子網路t2.micro中啟動單一 類型的執行個體,並將其與區域預設 VPC 的預設子網路建立關聯。如果您不打算使用 SSH (Linux) 或 RDP (Windows) 連線至執行個體,則金鑰對為選用。

aws ec2 run-instances \ --image-id ami-0abcdef1234567890 \ --instance-type t2.micro \ --key-name MyKeyPair

輸出:

{ "Instances": [ { "AmiLaunchIndex": 0, "ImageId": "ami-0abcdef1234567890", "InstanceId": "i-1231231230abcdef0", "InstanceType": "t2.micro", "KeyName": "MyKeyPair", "LaunchTime": "2018-05-10T08:05:20.000Z", "Monitoring": { "State": "disabled" }, "Placement": { "AvailabilityZone": "us-east-2a", "GroupName": "", "Tenancy": "default" }, "PrivateDnsName": "ip-10-0-0-157.us-east-2.compute.internal", "PrivateIpAddress": "10.0.0.157", "ProductCodes": [], "PublicDnsName": "", "State": { "Code": 0, "Name": "pending" }, "StateTransitionReason": "", "SubnetId": "subnet-04a636d18e83cfacb", "VpcId": "vpc-1234567890abcdef0", "Architecture": "x86_64", "BlockDeviceMappings": [], "ClientToken": "", "EbsOptimized": false, "Hypervisor": "xen", "NetworkInterfaces": [ { "Attachment": { "AttachTime": "2018-05-10T08:05:20.000Z", "AttachmentId": "eni-attach-0e325c07e928a0405", "DeleteOnTermination": true, "DeviceIndex": 0, "Status": "attaching" }, "Description": "", "Groups": [ { "GroupName": "MySecurityGroup", "GroupId": "sg-0598c7d356eba48d7" } ], "Ipv6Addresses": [], "MacAddress": "0a:ab:58:e0:67:e2", "NetworkInterfaceId": "eni-0c0a29997760baee7", "OwnerId": "123456789012", "PrivateDnsName": "ip-10-0-0-157.us-east-2.compute.internal", "PrivateIpAddress": "10.0.0.157", "PrivateIpAddresses": [ { "Primary": true, "PrivateDnsName": "ip-10-0-0-157.us-east-2.compute.internal", "PrivateIpAddress": "10.0.0.157" } ], "SourceDestCheck": true, "Status": "in-use", "SubnetId": "subnet-04a636d18e83cfacb", "VpcId": "vpc-1234567890abcdef0", "InterfaceType": "interface" } ], "RootDeviceName": "/dev/xvda", "RootDeviceType": "ebs", "SecurityGroups": [ { "GroupName": "MySecurityGroup", "GroupId": "sg-0598c7d356eba48d7" } ], "SourceDestCheck": true, "StateReason": { "Code": "pending", "Message": "pending" }, "Tags": [], "VirtualizationType": "hvm", "CpuOptions": { "CoreCount": 1, "ThreadsPerCore": 1 }, "CapacityReservationSpecification": { "CapacityReservationPreference": "open" }, "MetadataOptions": { "State": "pending", "HttpTokens": "optional", "HttpPutResponseHopLimit": 1, "HttpEndpoint": "enabled" } } ], "OwnerId": "123456789012", "ReservationId": "r-02a3f596d91211712" }

範例 2:在非預設的子網路中啟動執行個體,並新增公有 IP 地址

下列 run-instances 範例會針對您要在非預設的子網路中啟動的執行個體請求公有 IP 地址。執行個體已與指定的安全群組建立關聯。

aws ec2 run-instances \ --image-id ami-0abcdef1234567890 \ --instance-type t2.micro \ --subnet-id subnet-08fc749671b2d077c \ --security-group-ids sg-0b0384b66d7d692f9 \ --associate-public-ip-address \ --key-name MyKeyPair

如需 run-instances 的輸出範例,請參閱範例 1。

範例 3:啟動具有額外磁碟區的執行個體

下列 run-instances 範例會使用 mapping.json 中指定的區塊型裝置映射,在啟動時連接額外的磁碟區。區塊型裝置映射可以指定 EBS 磁碟區、執行個體存放區磁碟區,或同時指定 EBS 磁碟區和執行個體存放區磁碟區。

aws ec2 run-instances \ --image-id ami-0abcdef1234567890 \ --instance-type t2.micro \ --subnet-id subnet-08fc749671b2d077c \ --security-group-ids sg-0b0384b66d7d692f9 \ --key-name MyKeyPair \ --block-device-mappings file://mapping.json

mapping.json 的內容。此範例/dev/sdh會新增大小為 100 GiB 的空白 EBS 磁碟區。

[ { "DeviceName": "/dev/sdh", "Ebs": { "VolumeSize": 100 } } ]

mapping.json 的內容。此範例會將 ephemeral1 新增為執行個體儲存體磁碟區。

[ { "DeviceName": "/dev/sdc", "VirtualName": "ephemeral1" } ]

如需 run-instances 的輸出範例,請參閱範例 1。

如需區塊型裝置映射的詳細資訊,請參閱 Amazon EC2 使用者指南中的區塊型裝置映射

範例 4:啟動執行個體並在建立時新增標籤

下列 run-instances 範例會將索引鍵為 webserver、值為 production 的標籤新增至執行個體。此命令也會將索引鍵為 cost-center且值為 的標籤cc123套用至任何已建立的 EBS 磁碟區 (在此情況下為根磁碟區)。

aws ec2 run-instances \ --image-id ami-0abcdef1234567890 \ --instance-type t2.micro \ --count 1 \ --subnet-id subnet-08fc749671b2d077c \ --key-name MyKeyPair \ --security-group-ids sg-0b0384b66d7d692f9 \ --tag-specifications 'ResourceType=instance,Tags=[{Key=webserver,Value=production}]' 'ResourceType=volume,Tags=[{Key=cost-center,Value=cc123}]'

如需 run-instances 的輸出範例,請參閱範例 1。

範例 5:使用使用者資料啟動執行個體

下列 run-instances 範例會將使用者資料傳遞至名為 my_script.txt 的檔案中,且該檔案包含您執行個體的組態指令碼。指令碼會在啟動時執行。

aws ec2 run-instances \ --image-id ami-0abcdef1234567890 \ --instance-type t2.micro \ --count 1 \ --subnet-id subnet-08fc749671b2d077c \ --key-name MyKeyPair \ --security-group-ids sg-0b0384b66d7d692f9 \ --user-data file://my_script.txt

如需 run-instances 的輸出範例,請參閱範例 1。

如需執行個體使用者資料的詳細資訊,請參閱 Amazon EC2 使用者指南中的使用執行個體使用者資料

範例 6:啟動爆量效能執行個體

下列 run-instances 範例會啟動具有 unlimited 積分選項的 t2.micro 執行個體。啟動 T2 執行個體時,如果您未指定 --credit-specification,預設值為 standard 積分選項。啟動 T3 執行個體時,預設值為 unlimited 積分選項。

aws ec2 run-instances \ --image-id ami-0abcdef1234567890 \ --instance-type t2.micro \ --count 1 \ --subnet-id subnet-08fc749671b2d077c \ --key-name MyKeyPair \ --security-group-ids sg-0b0384b66d7d692f9 \ --credit-specification CpuCredits=unlimited

如需 run-instances 的輸出範例,請參閱範例 1。

如需爆量效能執行個體的詳細資訊,請參閱 Amazon EC2 使用者指南中的爆量效能執行個體

  • 如需 API 詳細資訊,請參閱 AWS CLI 命令參考中的 RunInstances

Java
Java 2.x 的 SDK
注意

還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

/** * Runs an EC2 instance asynchronously. * * @param instanceType The instance type to use for the EC2 instance. * @param keyName The name of the key pair to associate with the EC2 instance. * @param groupName The name of the security group to associate with the EC2 instance. * @param amiId The ID of the Amazon Machine Image (AMI) to use for the EC2 instance. * @return A {@link CompletableFuture} that completes with the ID of the started EC2 instance. * @throws RuntimeException If there is an error running the EC2 instance. */ public CompletableFuture<String> runInstanceAsync(String instanceType, String keyName, String groupName, String amiId) { RunInstancesRequest runRequest = RunInstancesRequest.builder() .instanceType(instanceType) .keyName(keyName) .securityGroups(groupName) .maxCount(1) .minCount(1) .imageId(amiId) .build(); CompletableFuture<RunInstancesResponse> responseFuture = getAsyncClient().runInstances(runRequest); return responseFuture.thenCompose(response -> { String instanceIdVal = response.instances().get(0).instanceId(); System.out.println("Going to start an EC2 instance and use a waiter to wait for it to be in running state"); return getAsyncClient().waiter() .waitUntilInstanceExists(r -> r.instanceIds(instanceIdVal)) .thenCompose(waitResponse -> getAsyncClient().waiter() .waitUntilInstanceRunning(r -> r.instanceIds(instanceIdVal)) .thenApply(runningResponse -> instanceIdVal)); }).exceptionally(throwable -> { // Handle any exceptions that occurred during the async call throw new RuntimeException("Failed to run EC2 instance: " + throwable.getMessage(), throwable); }); }
  • 如需 API 詳細資訊,請參閱 RunInstances AWS SDK for Java 2.x 參考中的 API

JavaScript
SDK for JavaScript (v3)
注意

還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

import { EC2Client, RunInstancesCommand } from "@aws-sdk/client-ec2"; /** * Create new EC2 instances. * @param {{ * keyName: string, * securityGroupIds: string[], * imageId: string, * instanceType: import('@aws-sdk/client-ec2')._InstanceType, * minCount?: number, * maxCount?: number }} options */ export const main = async ({ keyName, securityGroupIds, imageId, instanceType, minCount = "1", maxCount = "1", }) => { const client = new EC2Client({}); minCount = Number.parseInt(minCount); maxCount = Number.parseInt(maxCount); const command = new RunInstancesCommand({ // Your key pair name. KeyName: keyName, // Your security group. SecurityGroupIds: securityGroupIds, // An Amazon Machine Image (AMI). There are multiple ways to search for AMIs. For more information, see: // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/finding-an-ami.html ImageId: imageId, // An instance type describing the resources provided to your instance. There are multiple // ways to search for instance types. For more information see: // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-discovery.html InstanceType: instanceType, // Availability Zones have capacity limitations that may impact your ability to launch instances. // The `RunInstances` operation will only succeed if it can allocate at least the `MinCount` of instances. // However, EC2 will attempt to launch up to the `MaxCount` of instances, even if the full request cannot be satisfied. // If you need a specific number of instances, use `MinCount` and `MaxCount` set to the same value. // If you want to launch up to a certain number of instances, use `MaxCount` and let EC2 provision as many as possible. // If you require a minimum number of instances, but do not want to exceed a maximum, use both `MinCount` and `MaxCount`. MinCount: minCount, MaxCount: maxCount, }); try { const { Instances } = await client.send(command); const instanceList = Instances.map( (instance) => `• ${instance.InstanceId}`, ).join("\n"); console.log(`Launched instances:\n${instanceList}`); } catch (caught) { if (caught instanceof Error && caught.name === "ResourceCountExceeded") { console.warn(`${caught.message}`); } else { throw caught; } } };
  • 如需 API 詳細資訊,請參閱 RunInstances AWS SDK for JavaScript 參考中的 API

Kotlin
Kotlin 的 SDK
注意

還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

suspend fun createEC2Instance( name: String, amiId: String, ): String? { val request = RunInstancesRequest { imageId = amiId instanceType = InstanceType.T1Micro maxCount = 1 minCount = 1 } Ec2Client { region = "us-west-2" }.use { ec2 -> val response = ec2.runInstances(request) val instanceId = response.instances?.get(0)?.instanceId val tag = Tag { key = "Name" value = name } val requestTags = CreateTagsRequest { resources = listOf(instanceId.toString()) tags = listOf(tag) } ec2.createTags(requestTags) println("Successfully started EC2 Instance $instanceId based on AMI $amiId") return instanceId } }
  • 如需 API 詳細資訊,請參閱 RunInstances AWS for Kotlin SDK 參考中的 API

PowerShell
for PowerShell 工具

範例 1:此範例會在 AMI-Classic 或預設 EC2 中啟動指定 VPC 的單一執行個體。

New-EC2Instance -ImageId ami-12345678 -MinCount 1 -MaxCount 1 -InstanceType m3.medium -KeyName my-key-pair -SecurityGroup my-security-group

範例 2:此範例會在 AMI 中啟動指定 VPC 的單一執行個體。

New-EC2Instance -ImageId ami-12345678 -MinCount 1 -MaxCount 1 -SubnetId subnet-12345678 -InstanceType t2.micro -KeyName my-key-pair -SecurityGroupId sg-12345678

範例 3:若要新增 EBS 磁碟區或執行個體存放區磁碟區,請定義區塊型裝置映射並將其新增至命令。此範例會新增執行個體存放區磁碟區。

$bdm = New-Object Amazon.EC2.Model.BlockDeviceMapping $bdm.VirtualName = "ephemeral0" $bdm.DeviceName = "/dev/sdf" New-EC2Instance -ImageId ami-12345678 -BlockDeviceMapping $bdm ...

範例 4:若要指定其中一個目前的 Windows AMIs,請使用 AMI 取得其 Get-EC2ImageByName ID。此範例會從目前基本 AMI for Windows Server 2016 啟動執行個體。

$ami = Get-EC2ImageByName WINDOWS_2016_BASE New-EC2Instance -ImageId $ami.ImageId ...

範例 5:在指定的專用主機環境中啟動執行個體。

New-EC2Instance -ImageId ami-1a2b3c4d -InstanceType m4.large -KeyName my-key-pair -SecurityGroupId sg-1a2b3c4d -AvailabilityZone us-west-1a -Tenancy host -HostID h-1a2b3c4d5e6f1a2b3

範例 6:此請求會啟動兩個執行個體,並將具有 Web 伺服器金鑰和生產值的標籤套用至執行個體。請求也會將具有成本中心索引鍵和 cc123 值的標籤套用至建立的磁碟區 (在此情況下,為每個執行個體的根磁碟區)。

$tag1 = @{ Key="webserver"; Value="production" } $tag2 = @{ Key="cost-center"; Value="cc123" } $tagspec1 = new-object Amazon.EC2.Model.TagSpecification $tagspec1.ResourceType = "instance" $tagspec1.Tags.Add($tag1) $tagspec2 = new-object Amazon.EC2.Model.TagSpecification $tagspec2.ResourceType = "volume" $tagspec2.Tags.Add($tag2) New-EC2Instance -ImageId "ami-1a2b3c4d" -KeyName "my-key-pair" -MaxCount 2 -InstanceType "t2.large" -SubnetId "subnet-1a2b3c4d" -TagSpecification $tagspec1,$tagspec2
  • 如需 API 詳細資訊,請參閱 AWS Tools for PowerShell Cmdlet 參考中的 RunInstances

Python
SDK for Python (Boto3)
注意

還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

class EC2InstanceWrapper: """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) instance actions using the client interface.""" def __init__( self, ec2_client: Any, instances: Optional[List[Dict[str, Any]]] = None ) -> None: """ Initializes the EC2InstanceWrapper with an EC2 client and optional instances. :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level access to AWS EC2 services. :param instances: A list of dictionaries representing Boto3 Instance objects. These are high-level objects that wrap instance actions. """ self.ec2_client = ec2_client self.instances = instances or [] @classmethod def from_client(cls) -> "EC2InstanceWrapper": """ Creates an EC2InstanceWrapper instance with a default EC2 client. :return: An instance of EC2InstanceWrapper initialized with the default EC2 client. """ ec2_client = boto3.client("ec2") return cls(ec2_client) def create( self, image_id: str, instance_type: str, key_pair_name: str, security_group_ids: Optional[List[str]] = None, ) -> List[Dict[str, Any]]: """ Creates a new EC2 instance in the default VPC of the current account. The instance starts immediately after it is created. :param image_id: The ID of the Amazon Machine Image (AMI) to use for the instance. :param instance_type: The type of instance to create, such as 't2.micro'. :param key_pair_name: The name of the key pair to use for SSH access. :param security_group_ids: A list of security group IDs to associate with the instance. If not specified, the default security group of the VPC is used. :return: A list of dictionaries representing Boto3 Instance objects representing the newly created instances. """ try: instance_params = { "ImageId": image_id, "InstanceType": instance_type, "KeyName": key_pair_name, } if security_group_ids is not None: instance_params["SecurityGroupIds"] = security_group_ids response = self.ec2_client.run_instances( **instance_params, MinCount=1, MaxCount=1 ) instance = response["Instances"][0] self.instances.append(instance) waiter = self.ec2_client.get_waiter("instance_running") waiter.wait(InstanceIds=[instance["InstanceId"]]) except ClientError as err: params_str = "\n\t".join( f"{key}: {value}" for key, value in instance_params.items() ) logger.error( f"Failed to complete instance creation request.\nRequest details:{params_str}" ) error_code = err.response["Error"]["Code"] if error_code == "InstanceLimitExceeded": logger.error( ( f"Insufficient capacity for instance type '{instance_type}'. " "Terminate unused instances or contact AWS Support for a limit increase." ) ) if error_code == "InsufficientInstanceCapacity": logger.error( ( f"Insufficient capacity for instance type '{instance_type}'. " "Select a different instance type or launch in a different availability zone." ) ) raise return self.instances
  • 如需 API 詳細資訊,請參閱 RunInstances AWS SDK for Python (Boto3) Word 參考中的 API

Rust
Rust 的 SDK
注意

還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

pub async fn create_instance<'a>( &self, image_id: &'a str, instance_type: InstanceType, key_pair: &'a KeyPairInfo, security_groups: Vec<&'a SecurityGroup>, ) -> Result<String, EC2Error> { let run_instances = self .client .run_instances() .image_id(image_id) .instance_type(instance_type) .key_name( key_pair .key_name() .ok_or_else(|| EC2Error::new("Missing key name when launching instance"))?, ) .set_security_group_ids(Some( security_groups .iter() .filter_map(|sg| sg.group_id.clone()) .collect(), )) .min_count(1) .max_count(1) .send() .await?; if run_instances.instances().is_empty() { return Err(EC2Error::new("Failed to create instance")); } let instance_id = run_instances.instances()[0].instance_id().unwrap(); let response = self .client .create_tags() .resources(instance_id) .tags( Tag::builder() .key("Name") .value("From SDK Examples") .build(), ) .send() .await; match response { Ok(_) => tracing::info!("Created {instance_id} and applied tags."), Err(err) => { tracing::info!("Error applying tags to {instance_id}: {err:?}"); return Err(err.into()); } } tracing::info!("Instance is created."); Ok(instance_id.to_string()) }
  • 如需 API 詳細資訊,請參閱 RunInstances AWS for Rust SDK 參考中的 API

SAP ABAP
SDK for SAP ABAP
注意

還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

" Create tags for resource created during instance launch. " DATA lt_tagspecifications TYPE /aws1/cl_ec2tagspecification=>tt_tagspecificationlist. DATA ls_tagspecifications LIKE LINE OF lt_tagspecifications. ls_tagspecifications = NEW /aws1/cl_ec2tagspecification( iv_resourcetype = 'instance' it_tags = VALUE /aws1/cl_ec2tag=>tt_taglist( ( NEW /aws1/cl_ec2tag( iv_key = 'Name' iv_value = iv_tag_value ) ) ) ). APPEND ls_tagspecifications TO lt_tagspecifications. TRY. " Create/launch Amazon Elastic Compute Cloud (Amazon EC2) instance. " oo_result = lo_ec2->runinstances( " oo_result is returned for testing purposes. " iv_imageid = iv_ami_id iv_instancetype = 't2.micro' iv_maxcount = 1 iv_mincount = 1 it_tagspecifications = lt_tagspecifications iv_subnetid = iv_subnet_id ). MESSAGE 'EC2 instance created.' TYPE 'I'. CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception). DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|. MESSAGE lv_error TYPE 'E'. ENDTRY.
  • 如需 API 詳細資訊,請參閱 RunInstances for Word Word 參考中的 Word。 AWS SDK SAP ABAP API