AWS SDK 또는 RunInstances CLI와 함께 사용 - Amazon Elastic Compute Cloud

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

AWS SDK 또는 RunInstances CLI와 함께 사용

다음 코드 예제는 RunInstances의 사용 방법을 보여줍니다.

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.

.NET
AWS SDK for .NET
참고

더 많은 정보가 있습니다 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) { 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); return response.Reservation.Instances[0].InstanceId; }
  • API 세부 정보는 AWS SDK for .NET API RunInstances참조를 참조하십시오.

Bash
AWS CLI Bash 스크립트 사용
참고

더 많은 정보가 있습니다. 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++
SDK for C++
참고

자세한 내용은 에서 확인할 수 GitHub 있습니다. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

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();
  • API 세부 정보는 AWS SDK for C++ API RunInstances참조를 참조하십시오.

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의 콘텐츠. 이 예제에서는 크기가 100GiB인 빈 EBS 볼륨(/dev/sdh)을 추가합니다.

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

mapping.json의 콘텐츠. 이 예제에서는 ephemeral1을 인스턴스 스토어 볼륨으로 추가합니다.

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

run-instances 출력 예제는 예제 1을 참조하세요.

블록 디바이스 매핑에 대한 자세한 내용은 Amazon EC2 사용 설명서에서 블록 디바이스 매핑을 참조하세요.

예제 4: 인스턴스를 시작하고 생성 시 태그를 추가하는 방법

다음 run-instances 예제에서는 키가 production이고 값이 webserver인 태그를 인스턴스에 추가합니다. 이 명령은 또 생성되는 EBS 볼륨(이 경우에는 루트 볼륨)에 키가 cost-center이고 값이 cc123인 태그를 적용합니다.

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
SDK for Java 2.x
참고

자세한 내용은 에서 확인할 수 GitHub 있습니다. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.ec2.Ec2Client; import software.amazon.awssdk.services.ec2.model.InstanceType; import software.amazon.awssdk.services.ec2.model.RunInstancesRequest; import software.amazon.awssdk.services.ec2.model.RunInstancesResponse; import software.amazon.awssdk.services.ec2.model.Tag; import software.amazon.awssdk.services.ec2.model.CreateTagsRequest; import software.amazon.awssdk.services.ec2.model.Ec2Exception; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html * * This code example requires an AMI value. You can learn more about this value * by reading this documentation topic: * * https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/AMIs.html */ public class CreateInstance { public static void main(String[] args) { final String usage = """ Usage: <name> <amiId> Where: name - An instance name value that you can obtain from the AWS Console (for example, ami-xxxxxx5c8b987b1a0).\s amiId - An Amazon Machine Image (AMI) value that you can obtain from the AWS Console (for example, i-xxxxxx2734106d0ab).\s """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String name = args[0]; String amiId = args[1]; Region region = Region.US_EAST_1; Ec2Client ec2 = Ec2Client.builder() .region(region) .build(); String instanceId = createEC2Instance(ec2, name, amiId); System.out.println("The Amazon EC2 Instance ID is " + instanceId); ec2.close(); } public static String createEC2Instance(Ec2Client ec2, String name, String amiId) { RunInstancesRequest runRequest = RunInstancesRequest.builder() .imageId(amiId) .instanceType(InstanceType.T1_MICRO) .maxCount(1) .minCount(1) .build(); // Use a waiter to wait until the instance is running. System.out.println("Going to start an EC2 instance using a waiter"); RunInstancesResponse response = ec2.runInstances(runRequest); String instanceIdVal = response.instances().get(0).instanceId(); ec2.waiter().waitUntilInstanceRunning(r -> r.instanceIds(instanceIdVal)); Tag tag = Tag.builder() .key("Name") .value(name) .build(); CreateTagsRequest tagRequest = CreateTagsRequest.builder() .resources(instanceIdVal) .tags(tag) .build(); try { ec2.createTags(tagRequest); System.out.printf("Successfully started EC2 Instance %s based on AMI %s", instanceIdVal, amiId); return instanceIdVal; } catch (Ec2Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } }
  • API 세부 정보는 AWS SDK for Java 2.x API RunInstances참조를 참조하십시오.

JavaScript
JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

import { RunInstancesCommand } from "@aws-sdk/client-ec2"; import { client } from "../libs/client.js"; // Create a new EC2 instance. export const main = async () => { const command = new RunInstancesCommand({ // Your key pair name. KeyName: "KEY_PAIR_NAME", // Your security group. SecurityGroupIds: ["SECURITY_GROUP_ID"], // An x86_64 compatible image. ImageId: "ami-0001a0d1a04bfcc30", // An x86_64 compatible free-tier instance type. InstanceType: "t1.micro", // Ensure only 1 instance launches. MinCount: 1, MaxCount: 1, }); try { const response = await client.send(command); console.log(response); } catch (err) { console.error(err); } };
  • API 세부 정보는 AWS SDK for JavaScript API RunInstances참조를 참조하십시오.

Kotlin
SDK for Kotlin
참고

자세한 내용은 다음과 같습니다 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 세부 정보는 Kotlin API용AWS SDK 레퍼런스를 참조하세요 RunInstances.

PowerShell
다음을 위한 도구 PowerShell

예 1: 이 예제는 EC2-Classic 또는 기본 VPC에서 지정된 AMI의 단일 인스턴스를 시작합니다.

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

예 2: 이 예제는 VPC에서 지정된 AMI의 단일 인스턴스를 시작합니다.

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 AMI 중 하나를 지정하려면 를 사용하여 Get-EC2ImageByName AMI ID를 가져오십시오. 이 예제는 윈도우 서버 2016의 현재 기본 AMI에서 인스턴스를 시작합니다.

$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: 이 요청은 두 개의 인스턴스를 시작하고 웹 서버 키와 프로덕션 값이 포함된 태그를 인스턴스에 적용합니다. 또한 요청은 cost-center 키와 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 세부 정보는 Cmdlet 참조를 참조하십시오 RunInstances.AWS Tools for PowerShell

Python
SDK for Python(Boto3)
참고

자세한 내용은 다음과 같습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

class InstanceWrapper: """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) instance actions.""" def __init__(self, ec2_resource, instance=None): """ :param ec2_resource: A Boto3 Amazon EC2 resource. This high-level resource is used to create additional high-level objects that wrap low-level Amazon EC2 service actions. :param instance: A Boto3 Instance object. This is a high-level object that wraps instance actions. """ self.ec2_resource = ec2_resource self.instance = instance @classmethod def from_resource(cls): ec2_resource = boto3.resource("ec2") return cls(ec2_resource) def create(self, image, instance_type, key_pair, security_groups=None): """ Creates a new EC2 instance. The instance starts immediately after it is created. The instance is created in the default VPC of the current account. :param image: A Boto3 Image object that represents an Amazon Machine Image (AMI) that defines attributes of the instance that is created. The AMI defines things like the kind of operating system and the type of storage used by the instance. :param instance_type: The type of instance to create, such as 't2.micro'. The instance type defines things like the number of CPUs and the amount of memory. :param key_pair: A Boto3 KeyPair or KeyPairInfo object that represents the key pair that is used to secure connections to the instance. :param security_groups: A list of Boto3 SecurityGroup objects that represents the security groups that are used to grant access to the instance. When no security groups are specified, the default security group of the VPC is used. :return: A Boto3 Instance object that represents the newly created instance. """ try: instance_params = { "ImageId": image.id, "InstanceType": instance_type, "KeyName": key_pair.name, } if security_groups is not None: instance_params["SecurityGroupIds"] = [sg.id for sg in security_groups] self.instance = self.ec2_resource.create_instances( **instance_params, MinCount=1, MaxCount=1 )[0] self.instance.wait_until_running() except ClientError as err: logging.error( "Couldn't create instance with image %s, instance type %s, and key %s. " "Here's why: %s: %s", image.id, instance_type, key_pair.name, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return self.instance
  • API에 대한 자세한 내용은 파이썬용AWS SDK (Boto3) API 레퍼런스를 참조하십시오 RunInstances.

SAP ABAP
SDK for SAP ABAP
참고

자세한 내용은 다음과 같습니다. 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 세부 정보는 SAP용AWS SDK ABAP API 참조를 참조하십시오 RunInstances.

AWS SDK 개발자 가이드 및 코드 예제의 전체 목록은 을 참조하십시오. SDK를 사용하여 Amazon EC2 리소스 생성 AWS 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.