AWSDoc AWS SDK サンプルリポジトリには、その他の SDK GitHub サンプルがあります
翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。
AWS SDK を使用して Amazon EC2 インスタンスを起動
以下のコード例は、Amazon EC2 インスタンスを起動する方法を示しています。
アクション例は、より大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。次のコード例で、このアクションのコンテキストを確認できます。
- .NET
-
- AWS SDK for .NET
-
注記
にはまだまだあります。 GitHub用例一覧を検索し、AWS コード例リポジトリ
での設定と実行の方法を確認してください。 /// <summary> /// Start an EC2 instance. /// </summary> /// <param name="ec2InstanceId">The instance Id of the Amazon EC2 instance /// to start.</param> /// <returns>Async task.</returns> public async Task StartInstances(string ec2InstanceId) { var request = new StartInstancesRequest { InstanceIds = new List<string> { ec2InstanceId }, }; var response = await _amazonEC2.StartInstancesAsync(request); if (response.StartingInstances.Count > 0) { var instances = response.StartingInstances; instances.ForEach(i => { Console.WriteLine($"Successfully started the EC2 instance with instance ID: {i.InstanceId}."); }); } }
-
API の詳細については、AWS SDK for .NETAPI StartInstancesリファレンスのを参照してください。
-
- C++
-
- SDK for C++
-
注記
にはまだまだあります GitHub。用例一覧を検索し、AWS コード例リポジトリ
での設定と実行の方法を確認してください。 Aws::EC2::EC2Client ec2Client(clientConfiguration); Aws::EC2::Model::StartInstancesRequest start_request; start_request.AddInstanceIds(instanceId); start_request.SetDryRun(true); auto dry_run_outcome = ec2Client.StartInstances(start_request); if (dry_run_outcome.IsSuccess()) { std::cerr << "Failed dry run to start instance. A dry run should trigger an error." << std::endl; return false; } else if (dry_run_outcome.GetError().GetErrorType() != Aws::EC2::EC2Errors::DRY_RUN_OPERATION) { std::cout << "Failed dry run to start instance " << instanceId << ": " << dry_run_outcome.GetError().GetMessage() << std::endl; return false; } start_request.SetDryRun(false); auto start_instancesOutcome = ec2Client.StartInstances(start_request); if (!start_instancesOutcome.IsSuccess()) { std::cout << "Failed to start instance " << instanceId << ": " << start_instancesOutcome.GetError().GetMessage() << std::endl; } else { std::cout << "Successfully started instance " << instanceId << std::endl; }
-
API の詳細については、AWS SDK for C++API StartInstancesリファレンスのを参照してください。
-
- Java
-
- SDK for Java 2.x
-
注記
にはまだまだあります GitHub。用例一覧を検索し、AWS コード例リポジトリ
での設定と実行の方法を確認してください。 public static void startInstance(Ec2Client ec2, String instanceId) { Ec2Waiter ec2Waiter = Ec2Waiter.builder() .overrideConfiguration(b -> b.maxAttempts(100)) .client(ec2) .build(); StartInstancesRequest request = StartInstancesRequest.builder() .instanceIds(instanceId) .build(); System.out.println("Use an Ec2Waiter to wait for the instance to run. This will take a few minutes."); ec2.startInstances(request); DescribeInstancesRequest instanceRequest = DescribeInstancesRequest.builder() .instanceIds(instanceId) .build(); WaiterResponse<DescribeInstancesResponse> waiterResponse = ec2Waiter.waitUntilInstanceRunning(instanceRequest); waiterResponse.matched().response().ifPresent(System.out::println); System.out.println("Successfully started instance "+instanceId); }
-
API の詳細については、AWS SDK for Java 2.xAPI StartInstancesリファレンスのを参照してください。
-
- JavaScript
-
- JavaScript (v3) 用の SDK
-
注記
にはまだまだあります。 GitHub用例一覧を検索し、AWS コード例リポジトリ
での設定と実行の方法を確認してください。 import { StartInstancesCommand } from "@aws-sdk/client-ec2"; import { client } from "../libs/client.js"; export const main = async () => { const command = new StartInstancesCommand({ // Use DescribeInstancesCommand to find InstanceIds InstanceIds: ["INSTANCE_ID"], }); try { const { StartingInstances } = await client.send(command); const instanceIdList = StartingInstances.map( (instance) => ` • ${instance.InstanceId}`, ); console.log("Starting instances:"); console.log(instanceIdList.join("\n")); } catch (err) { console.error(err); } };
-
API の詳細については、AWS SDK for JavaScriptAPI StartInstancesリファレンスのを参照してください。
-
- Kotlin
-
- SDK for Kotlin
-
注記
これはプレビューリリースの機能に関するプレリリースドキュメントです。このドキュメントは変更される可能性があります。
注記
にはまだまだあります GitHub。用例一覧を検索し、AWS コード例リポジトリ
での設定と実行の方法を確認してください。 suspend fun startInstanceSc(instanceId: String) { val request = StartInstancesRequest { instanceIds = listOf(instanceId) } Ec2Client { region = "us-west-2" }.use { ec2 -> ec2.startInstances(request) println("Waiting until instance $instanceId starts. This will take a few minutes.") ec2.waitUntilInstanceRunning { // suspend call instanceIds = listOf(instanceId) } println("Successfully started instance $instanceId") } }
-
API の詳細については、「AWSSDK for Kotlin API リファレンス」のを参照してくださいStartInstances
。
-
- 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 start(self): """ Starts an instance and waits for it to be in a running state. :return: The response to the start request. """ if self.instance is None: logger.info("No instance to start.") return try: response = self.instance.start() self.instance.wait_until_running() except ClientError as err: logger.error( "Couldn't start instance %s. Here's why: %s: %s", self.instance.id, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return response
-
API の詳細については、『AWSSDK for Python (Boto3) API リファレンス』のを参照してくださいStartInstances。
-
- Ruby
-
- SDK for Ruby
-
注記
にはまだまだあります。 GitHub用例一覧を検索し、AWS コード例リポジトリ
での設定と実行の方法を確認してください。 require "aws-sdk-ec2" # Attempts to start an Amazon Elastic Compute Cloud (Amazon EC2) instance. # # Prerequisites: # # - The Amazon EC2 instance. # # @param ec2_client [Aws::EC2::Client] An initialized EC2 client. # @param instance_id [String] The ID of the instance. # @return [Boolean] true if the instance was started; otherwise, false. # @example # exit 1 unless instance_started?( # Aws::EC2::Client.new(region: 'us-west-2'), # 'i-123abc' # ) def instance_started?(ec2_client, instance_id) response = ec2_client.describe_instance_status(instance_ids: [instance_id]) if response.instance_statuses.count.positive? state = response.instance_statuses[0].instance_state.name case state when "pending" puts "Error starting instance: the instance is pending. Try again later." return false when "running" puts "The instance is already running." return true when "terminated" puts "Error starting instance: " \ "the instance is terminated, so you cannot start it." return false end end ec2_client.start_instances(instance_ids: [instance_id]) ec2_client.wait_until(:instance_running, instance_ids: [instance_id]) puts "Instance started." return true rescue StandardError => e puts "Error starting instance: #{e.message}" return false end # Full example call: def run_me instance_id = "" region = "" # Print usage information and then stop. if ARGV[0] == "--help" || ARGV[0] == "-h" puts "Usage: ruby ec2-ruby-example-start-instance-i-123abc.rb " \ "INSTANCE_ID REGION " # Replace us-west-2 with the AWS Region you're using for Amazon EC2. puts "Example: ruby ec2-ruby-example-start-instance-i-123abc.rb " \ "i-123abc us-west-2" exit 1 # If no values are specified at the command prompt, use these default values. # Replace us-west-2 with the AWS Region you're using for Amazon EC2. elsif ARGV.count.zero? instance_id = "i-123abc" region = "us-west-2" # Otherwise, use the values as specified at the command prompt. else instance_id = ARGV[0] region = ARGV[1] end ec2_client = Aws::EC2::Client.new(region: region) puts "Attempting to start instance '#{instance_id}' " \ "(this might take a few minutes)..." unless instance_started?(ec2_client, instance_id) puts "Could not start instance." end end run_me if $PROGRAM_NAME == __FILE__
-
API の詳細については、AWS SDK for RubyAPI StartInstancesリファレンスのを参照してください。
-
- Rust
-
- SDK for Rust
-
注記
これはプレビューリリースの SDK に関するドキュメントです。SDK は変更される場合があり、本稼働環境では使用しないでください。
注記
にはまだまだあります GitHub。用例一覧を検索し、AWS コード例リポジトリ
での設定と実行の方法を確認してください。 async fn start_instance(client: &Client, id: &str) -> Result<(), Error> { client.start_instances().instance_ids(id).send().await?; println!("Started instance."); Ok(()) }
-
API の詳細については、「AWSSDK for Rust API リファレンス」のを参照してくださいStartInstances
。
-
- SAP ABAP
-
- SDK for SAP ABAP
-
注記
にはまだまだあります GitHub。用例一覧を検索し、AWS コード例リポジトリ
での設定と実行の方法を確認してください。 DATA lt_instance_ids TYPE /aws1/cl_ec2instidstringlist_w=>tt_instanceidstringlist. APPEND NEW /aws1/cl_ec2instidstringlist_w( iv_value = iv_instance_id ) TO lt_instance_ids. "Perform dry run" TRY. " DryRun is set to true. This checks for the required permissions to start the instance without actually making the request. " lo_ec2->startinstances( it_instanceids = lt_instance_ids iv_dryrun = abap_true ). CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception). " If the error code returned is `DryRunOperation`, then you have the required permissions to start this instance. " IF lo_exception->av_err_code = 'DryRunOperation'. MESSAGE 'Dry run to start instance completed.' TYPE 'I'. " DryRun is set to false to start instance. " oo_result = lo_ec2->startinstances( " oo_result is returned for testing purposes. " it_instanceids = lt_instance_ids iv_dryrun = abap_false ). MESSAGE 'Successfully started the EC2 instance.' TYPE 'I'. " If the error code returned is `UnauthorizedOperation`, then you don't have the required permissions to start this instance. " ELSEIF lo_exception->av_err_code = 'UnauthorizedOperation'. MESSAGE 'Dry run to start instance failed. User does not have permissions to start the instance.' TYPE 'E'. ELSE. DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|. MESSAGE lv_error TYPE 'E'. ENDIF. ENDTRY.
-
API の詳細については、AWSSDK for SAP ABAP API リファレンスのを参照してくださいStartInstances。
-