搭StartInstances配 AWS 開發套件或 CLI 使用 - Amazon Elastic Compute Cloud

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

StartInstances配 AWS 開發套件或 CLI 使用

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

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

.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 .NET API 參考StartInstances中的。

Bash
AWS CLI 與 Bash 腳本
注意

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

############################################################################### # function ec2_start_instances # # This function starts one or more Amazon Elastic Compute Cloud (Amazon EC2) instances. # # Parameters: # -i instance_id - The ID(s) of the instance(s) to start (comma-separated). # -h - Display help. # # Returns: # 0 - If successful. # 1 - If it fails. ############################################################################### function ec2_start_instances() { local instance_ids local option OPTARG # Required to use getopts command in a function. # bashsupport disable=BP5008 function usage() { echo "function ec2_start_instances" echo "Starts one or more Amazon Elastic Compute Cloud (Amazon EC2) instances." echo " -i instance_id - The ID(s) of the instance(s) to start (comma-separated)." echo " -h - Display help." echo "" } # Retrieve the calling parameters. while getopts "i:h" option; do case "${option}" in i) instance_ids="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 if [[ -z "$instance_ids" ]]; then errecho "ERROR: You must provide one or more instance IDs with the -i parameter." usage return 1 fi response=$(aws ec2 start-instances \ --instance-ids "${instance_ids}") || { aws_cli_error_log ${?} errecho "ERROR: AWS reports start-instances operation failed with $response." return 1 } 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 命令參考StartInstances中的。

C++
適用於 C++ 的 SDK
注意

還有更多關於 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中的。

CLI
AWS CLI

啟動 Amazon EC2 執行個體

此範例會啟動指定且受 Amazon EBS 支援的執行個體。

命令:

aws ec2 start-instances --instance-ids i-1234567890abcdef0

輸出:

{ "StartingInstances": [ { "InstanceId": "i-1234567890abcdef0", "CurrentState": { "Code": 0, "Name": "pending" }, "PreviousState": { "Code": 80, "Name": "stopped" } } ] }

如需詳細資訊,請參閱《Amazon Elastic Compute Cloud 使用者指南》中的「停止和啟動執行個體」。

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

Java
適用於 Java 2.x 的 SDK
注意

還有更多關於 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.x API 參考StartInstances中的。

JavaScript
適用於 JavaScript (v3) 的開發套件
注意

還有更多關於 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 JavaScript API 參考StartInstances中的。

Kotlin
適用於 Kotlin 的 SDK
注意

還有更多關於 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 的詳細信息,請參閱 AWS SDK StartInstances中的 Kotlin API 參考。

PowerShell
適用的工具 PowerShell

範例 1:此範例會啟動指定的執行個體。

Start-EC2Instance -InstanceId i-12345678

輸出:

CurrentState InstanceId PreviousState ------------ ---------- ------------- Amazon.EC2.Model.InstanceState i-12345678 Amazon.EC2.Model.InstanceState

範例 2:此範例會啟動指定的執行個體。

@("i-12345678", "i-76543210") | Start-EC2Instance

範例 3:此範例會啟動目前已停止的執行個體集。傳回的執行個體物件Get-EC2Instance會傳送至Start-EC2Instance。此範例使用的語法需要 PowerShell 版本 3 或更高版本。

(Get-EC2Instance -Filter @{ Name="instance-state-name"; Values="stopped"}).Instances | Start-EC2Instance

範例 4:在 PowerShell 版本 2 中,您必須使用新物件來建立篩選器參數的篩選器。

$filter = New-Object Amazon.EC2.Model.Filter $filter.Name = "instance-state-name" $filter.Values = "stopped" (Get-EC2Instance -Filter $filter).Instances | Start-EC2Instance
  • 如需 API 詳細資訊,請參閱AWS Tools for PowerShell 指令程StartInstances式參考中的。

Python
適用於 Python (Boto3) 的 SDK
注意

還有更多關於 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 的詳細資訊,請參閱AWS 開發套件StartInstances中的 Python (博托 3) API 參考。

Ruby
適用於 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 # Example usage: 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 Ruby API 參考StartInstances中的。

Rust
適用於 Rust 的 SDK
注意

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

async fn start_instance(client: &Client, id: &str) -> Result<(), Error> { // start_instance has no unique errors to handle. client.start_instances().instance_ids(id).send().await?; println!("Waiting for instance to be running"); let wait_for_running = client .wait_until_instance_running() .instance_ids(id) .wait(Duration::from_secs(60)) .await; match wait_for_running { Ok(_) => println!("Instance is running"), Err(err) => match err { WaiterError::ExceededMaxWait(exceeded) => { println!( "Exceeded max time waiting for instance to start. Exceeded {}s by {}s.", exceeded.max_wait().as_secs(), (exceeded.elapsed() - exceeded.max_wait()).as_secs() ); return Ok(()); } _ => return Err(err.into()), }, } println!("Started instance."); Ok(()) }
  • 如需 API 的詳細資訊,請參閱 AWS SDK StartInstances中的 Rust API 參考資料。

SAP ABAP
適用於 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 詳細資訊,請參閱 AWS SDK StartInstances中的 SAP ABAP API 參考資料。

如需 AWS SDK 開發人員指南和程式碼範例的完整清單,請參閱使用 AWS 開發套件建立 Amazon EC2 資源。此主題也包含有關入門的資訊和舊版 SDK 的詳細資訊。