AWS SDK を使用して Amazon EC2 インスタンスを作成 - AWS SDK コードサンプル

Doc AWS SDK Examples リポジトリには、他にも SDK の例があります。 AWS GitHub

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

AWS SDK を使用して Amazon EC2 インスタンスを作成

次のコード例は、Amazon EC2 インスタンスを作成、実行する方法を示しています。

アクション例は、より大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。次のコード例で、このアクションのコンテキストを確認できます。

.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 の詳細については、「 API リファレンスRunInstances」の「」を参照してください。 AWS SDK for .NET

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 の詳細については、「 API リファレンスRunInstances」の「」を参照してください。 AWS SDK for C++

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 の内容。この例では、サイズが 100 GiB である空の 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 の例では、キー 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 の詳細については、「 コマンドリファレンスRunInstances」の「」を参照してください。 AWS CLI

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(); RunInstancesResponse response = ec2.runInstances(runRequest); String instanceId = response.instances().get(0).instanceId(); Tag tag = Tag.builder() .key("Name") .value(name) .build(); CreateTagsRequest tagRequest = CreateTagsRequest.builder() .resources(instanceId) .tags(tag) .build(); try { ec2.createTags(tagRequest); System.out.printf("Successfully started EC2 Instance %s based on AMI %s", instanceId, amiId); return instanceId; } catch (Ec2Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } }
  • API の詳細については、「 API リファレンスRunInstances」の「」を参照してください。 AWS SDK for Java 2.x

JavaScript
SDK for JavaScript (v3)
注記

については、こちらを参照してください 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 の詳細については、「 API リファレンスRunInstances」の「」を参照してください。 AWS SDK for JavaScript

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 の詳細については、RunInstancesAWS「 SDK for Kotlin API リファレンス」の「」を参照してください。

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 の詳細については、RunInstancesAWS「 SDK for Python (Boto3) API リファレンス」の「」を参照してください。

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 の詳細については、RunInstancesAWS「 SDK for SAP ABAP API リファレンス」の「」を参照してください。