Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.
Utilizzo StopInstances
con un AWS SDK o una CLI
I seguenti esempi di codice mostrano come utilizzareStopInstances
.
Gli esempi di operazioni sono estratti di codice da programmi più grandi e devono essere eseguiti nel contesto. È possibile visualizzare questa operazione nel contesto nel seguente esempio di codice:
- .NET
-
- AWS SDK for .NET
-
Nota
C'è altro su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS
. /// <summary> /// Stop an EC2 instance. /// </summary> /// <param name="ec2InstanceId">The instance Id of the EC2 instance to /// stop.</param> /// <returns>Async task.</returns> public async Task StopInstances(string ec2InstanceId) { // In addition to the list of instance Ids, the // request can also include the following properties: // Force When true, forces the instances to // stop but you must check the integrity // of the file system. Not recommended on // Windows instances. // Hibernate When true, hibernates the instance if the // instance was enabled for hibernation when // it was launched. var request = new StopInstancesRequest { InstanceIds = new List<string> { ec2InstanceId }, }; var response = await _amazonEC2.StopInstancesAsync(request); if (response.StoppingInstances.Count > 0) { var instances = response.StoppingInstances; instances.ForEach(i => { Console.WriteLine($"Successfully stopped the EC2 Instance " + $"with InstanceID: {i.InstanceId}."); }); } }
-
Per i dettagli sull'API, consulta la StopInstancessezione AWS SDK for .NET API Reference.
-
- Bash
-
- AWS CLI con lo script Bash
-
Nota
C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS
. ############################################################################### # function ec2_stop_instances # # This function stops one or more Amazon Elastic Compute Cloud (Amazon EC2) instances. # # Parameters: # -i instance_id - The ID(s) of the instance(s) to stop (comma-separated). # -h - Display help. # # Returns: # 0 - If successful. # 1 - If it fails. ############################################################################### function ec2_stop_instances() { local instance_ids local option OPTARG # Required to use getopts command in a function. # bashsupport disable=BP5008 function usage() { echo "function ec2_stop_instances" echo "Stops one or more Amazon Elastic Compute Cloud (Amazon EC2) instances." echo " -i instance_id - The ID(s) of the instance(s) to stop (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 stop-instances \ --instance-ids "${instance_ids}") || { aws_cli_error_log ${?} errecho "ERROR: AWS reports stop-instances operation failed with $response." return 1 } return 0 }
Le funzioni di utilità utilizzate in questo esempio.
############################################################################### # 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 }
-
Per i dettagli sull'API, consulta StopInstances AWS CLICommand Reference.
-
- C++
-
- SDK per C++
-
Nota
C'è altro su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS
. Aws::EC2::EC2Client ec2Client(clientConfiguration); Aws::EC2::Model::StopInstancesRequest request; request.AddInstanceIds(instanceId); request.SetDryRun(true); auto dry_run_outcome = ec2Client.StopInstances(request); if (dry_run_outcome.IsSuccess()) { std::cerr << "Failed dry run to stop 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 stop instance " << instanceId << ": " << dry_run_outcome.GetError().GetMessage() << std::endl; return false; } request.SetDryRun(false); auto outcome = ec2Client.StopInstances(request); if (!outcome.IsSuccess()) { std::cout << "Failed to stop instance " << instanceId << ": " << outcome.GetError().GetMessage() << std::endl; } else { std::cout << "Successfully stopped instance " << instanceId << std::endl; }
-
Per i dettagli sull'API, consulta la StopInstancessezione AWS SDK for C++ API Reference.
-
- CLI
-
- AWS CLI
-
Esempio 1: per interrompere un'istanza Amazon EC2
Nell'esempio di
stop-instances
seguente viene interrotta l'istanza supportata da Amazon EBS specificata.aws ec2 stop-instances \ --instance-ids i-1234567890abcdef0
Output:
{ "StoppingInstances": [ { "InstanceId": "i-1234567890abcdef0", "CurrentState": { "Code": 64, "Name": "stopping" }, "PreviousState": { "Code": 16, "Name": "running" } } ] }
Per ulteriori informazioni, consulta Arrestare e avviare un'istanza nella Guida per l'utente di Amazon Elastic Compute Cloud.
Esempio 2: per ibernare un'istanza Amazon EC2
Nell'esempio di
stop-instances
seguente viene ibernata un'istanza supportata da Amazon EBS se tale istanza è abilitata per l'ibernazione e soddisfa i prerequisiti di ibernazione. Dopo l'ibernazione dell'istanza, questa viene arrestata.aws ec2 stop-instances \ --instance-ids i-1234567890abcdef0 \ --hibernate
Output:
{ "StoppingInstances": [ { "CurrentState": { "Code": 64, "Name": "stopping" }, "InstanceId": "i-1234567890abcdef0", "PreviousState": { "Code": 16, "Name": "running" } } ] }
Per ulteriori informazioni, consulta Ibernazione di un'istanza Linux on demand nella Guida per l'utente di Amazon Elastic Cloud Compute.
-
Per i dettagli sull'API, consulta StopInstances AWS CLI
Command Reference.
-
- Java
-
- SDK per Java 2.x
-
Nota
C'è altro su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS
. public static void stopInstance(Ec2Client ec2, String instanceId) { Ec2Waiter ec2Waiter = Ec2Waiter.builder() .overrideConfiguration(b -> b.maxAttempts(100)) .client(ec2) .build(); StopInstancesRequest request = StopInstancesRequest.builder() .instanceIds(instanceId) .build(); System.out.println("Use an Ec2Waiter to wait for the instance to stop. This will take a few minutes."); ec2.stopInstances(request); DescribeInstancesRequest instanceRequest = DescribeInstancesRequest.builder() .instanceIds(instanceId) .build(); WaiterResponse<DescribeInstancesResponse> waiterResponse = ec2Waiter.waitUntilInstanceStopped(instanceRequest); waiterResponse.matched().response().ifPresent(System.out::println); System.out.println("Successfully stopped instance " + instanceId); }
-
Per i dettagli sull'API, consulta la StopInstancessezione AWS SDK for Java 2.x API Reference.
-
- JavaScript
-
- SDK per JavaScript (v3)
-
Nota
C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS
. import { StopInstancesCommand } from "@aws-sdk/client-ec2"; import { client } from "../libs/client.js"; export const main = async () => { const command = new StopInstancesCommand({ // Use DescribeInstancesCommand to find InstanceIds InstanceIds: ["INSTANCE_ID"], }); try { const { StoppingInstances } = await client.send(command); const instanceIdList = StoppingInstances.map( (instance) => ` • ${instance.InstanceId}`, ); console.log("Stopping instances:"); console.log(instanceIdList.join("\n")); } catch (err) { console.error(err); } };
-
Per i dettagli sull'API, consulta la StopInstancessezione AWS SDK for JavaScript API Reference.
-
- Kotlin
-
- SDK per Kotlin
-
Nota
C'è di più su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS
. suspend fun stopInstanceSc(instanceId: String) { val request = StopInstancesRequest { instanceIds = listOf(instanceId) } Ec2Client { region = "us-west-2" }.use { ec2 -> ec2.stopInstances(request) println("Waiting until instance $instanceId stops. This will take a few minutes.") ec2.waitUntilInstanceStopped { // suspend call instanceIds = listOf(instanceId) } println("Successfully stopped instance $instanceId") } }
-
Per i dettagli sull'API, StopInstances
consulta AWS SDK for Kotlin API reference.
-
- PowerShell
-
- Strumenti per PowerShell
-
Esempio 1: questo esempio interrompe l'istanza specificata.
Stop-EC2Instance -InstanceId i-12345678
Output:
CurrentState InstanceId PreviousState ------------ ---------- ------------- Amazon.EC2.Model.InstanceState i-12345678 Amazon.EC2.Model.InstanceState
-
Per i dettagli sull'API, vedere StopInstancesin AWS Tools for PowerShell Cmdlet Reference.
-
- Python
-
- SDK per Python (Boto3)
-
Nota
C'è altro su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice 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 stop(self): """ Stops an instance and waits for it to be in a stopped state. :return: The response to the stop request. """ if self.instance is None: logger.info("No instance to stop.") return try: response = self.instance.stop() self.instance.wait_until_stopped() except ClientError as err: logger.error( "Couldn't stop instance %s. Here's why: %s: %s", self.instance.id, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return response
-
Per i dettagli sull'API, consulta StopInstances AWSSDK for Python (Boto3) API Reference.
-
- Ruby
-
- SDK per Ruby
-
Nota
C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS
. require "aws-sdk-ec2" # 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 stopped; otherwise, false. # @example # exit 1 unless instance_stopped?( # Aws::EC2::Client.new(region: 'us-west-2'), # 'i-123abc' # ) def instance_stopped?(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 "stopping" puts "The instance is already stopping." return true when "stopped" puts "The instance is already stopped." return true when "terminated" puts "Error stopping instance: " \ "the instance is terminated, so you cannot stop it." return false end end ec2_client.stop_instances(instance_ids: [instance_id]) ec2_client.wait_until(:instance_stopped, instance_ids: [instance_id]) puts "Instance stopped." return true rescue StandardError => e puts "Error stopping 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-stop-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 stop instance '#{instance_id}' " \ "(this might take a few minutes)..." unless instance_stopped?(ec2_client, instance_id) puts "Could not stop instance." end end run_me if $PROGRAM_NAME == __FILE__
-
Per i dettagli sull'API, consulta la StopInstancessezione AWS SDK for Ruby API Reference.
-
- Rust
-
- SDK per Rust
-
Nota
C'è di più su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS
. async fn stop_instance(client: &Client, id: &str) -> Result<(), Error> { client.stop_instances().instance_ids(id).send().await?; println!("Stopping instance..."); let wait = client .wait_until_instance_stopped() .instance_ids(id) .wait(Duration::from_secs(60)) .await; match wait { Ok(_) => { println!("Stopped instance."); } Err(err) => match err { WaiterError::ExceededMaxWait(exceeded) => { println!( "Exceeded max time waiting for instance to stop. Exceeded {}s by {}s", exceeded.max_wait().as_secs(), (exceeded.elapsed() - exceeded.max_wait()).as_secs() ) } _ => return Err(err.into()), }, }; Ok(()) }
-
Per i dettagli sulle API, consulta la StopInstances
guida di riferimento all'API AWS SDK for Rust.
-
- SAP ABAP
-
- SDK per SAP ABAP
-
Nota
C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice 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 stop the instance without actually making the request. " lo_ec2->stopinstances( 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 stop this instance. " IF lo_exception->av_err_code = 'DryRunOperation'. MESSAGE 'Dry run to stop instance completed.' TYPE 'I'. " DryRun is set to false to stop instance. " oo_result = lo_ec2->stopinstances( " oo_result is returned for testing purposes. " it_instanceids = lt_instance_ids iv_dryrun = abap_false ). MESSAGE 'Successfully stopped the EC2 instance.' TYPE 'I'. " If the error code returned is `UnauthorizedOperation`, then you don't have the required permissions to stop this instance. " ELSEIF lo_exception->av_err_code = 'UnauthorizedOperation'. MESSAGE 'Dry run to stop instance failed. User does not have permissions to stop 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.
-
Per i dettagli sulle API, StopInstancesconsulta AWS SDK for SAP ABAP API reference.
-
Per un elenco completo delle guide per sviluppatori AWS SDK e degli esempi di codice, consulta. Crea risorse Amazon EC2 utilizzando un SDK AWS Questo argomento include anche informazioni su come iniziare e dettagli sulle versioni precedenti dell'SDK.