与 AWS SDK或TerminateInstances一起使用 CLI - AWS SDK代码示例

AWS 文档 AWS SDK示例 GitHub 存储库中还有更多SDK示例

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

与 AWS SDK或TerminateInstances一起使用 CLI

以下代码示例演示如何使用 TerminateInstances

操作示例是大型程序的代码摘录,必须在上下文中运行。在以下代码示例中,您可以查看此操作的上下文:

.NET
AWS SDK for .NET
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

/// <summary> /// Terminate an EC2 instance. /// </summary> /// <param name="ec2InstanceId">The instance Id of the EC2 instance /// to terminate.</param> /// <returns>Async task.</returns> public async Task<List<InstanceStateChange>> TerminateInstances(string ec2InstanceId) { var request = new TerminateInstancesRequest { InstanceIds = new List<string> { ec2InstanceId } }; var response = await _amazonEC2.TerminateInstancesAsync(request); return response.TerminatingInstances; }
  • 有关API详细信息,请参阅 “AWS SDK for .NET API参考 TerminateInstances” 中的。

Bash
AWS CLI 使用 Bash 脚本
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

############################################################################### # function ec2_terminate_instances # # This function terminates one or more Amazon Elastic Compute Cloud (Amazon EC2) # instances using the AWS CLI. # # Parameters: # -i instance_ids - A space-separated list of instance IDs. # -h - Display help. # # Returns: # 0 - If successful. # 1 - If it fails. ############################################################################### function ec2_terminate_instances() { local instance_ids response local option OPTARG # Required to use getopts command in a function. # bashsupport disable=BP5008 function usage() { echo "function ec2_terminate_instances" echo "Terminates one or more Amazon Elastic Compute Cloud (Amazon EC2) instances." echo " -i instance_ids - A space-separated list of instance IDs." 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 # Check if instance ID is provided if [[ -z "${instance_ids}" ]]; then echo "Error: Missing required instance IDs parameter." usage return 1 fi # shellcheck disable=SC2086 response=$(aws ec2 terminate-instances \ "--instance-ids" $instance_ids \ --query 'TerminatingInstances[*].[InstanceId,CurrentState.Name]' \ --output text) || { aws_cli_error_log ${?} errecho "ERROR: AWS reports terminate-instances operation failed.$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 }
C++
SDK对于 C++
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

//! Terminate an Amazon Elastic Compute Cloud (Amazon EC2) instance. /*! \param instanceID: An EC2 instance ID. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::EC2::terminateInstances(const Aws::String &instanceID, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::EC2::EC2Client ec2Client(clientConfiguration); Aws::EC2::Model::TerminateInstancesRequest request; request.SetInstanceIds({instanceID}); Aws::EC2::Model::TerminateInstancesOutcome outcome = ec2Client.TerminateInstances(request); if (outcome.IsSuccess()) { std::cout << "Ec2 instance '" << instanceID << "' was terminated." << std::endl; } else { std::cerr << "Failed to terminate ec2 instance " << instanceID << ", " << outcome.GetError().GetMessage() << std::endl; return false; } return outcome.IsSuccess(); }
  • 有关API详细信息,请参阅 “AWS SDK for C++ API参考 TerminateInstances” 中的。

CLI
AWS CLI

终止 Amazon EC2 实例

本示例将终止指定的实例。

命令:

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

输出:

{ "TerminatingInstances": [ { "InstanceId": "i-1234567890abcdef0", "CurrentState": { "Code": 32, "Name": "shutting-down" }, "PreviousState": { "Code": 16, "Name": "running" } } ] }

有关更多信息,请参阅AWS 命令行界面用户指南中的使用 Amazon EC2 实例。

Java
SDK适用于 Java 2.x
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

/** * Terminates an EC2 instance asynchronously and waits for it to reach the terminated state. * * @param instanceId the ID of the EC2 instance to terminate * @return a {@link CompletableFuture} that completes when the instance has been terminated * @throws RuntimeException if there is no response from the AWS SDK or if there is a failure during the termination process */ public CompletableFuture<Object> terminateEC2Async(String instanceId) { TerminateInstancesRequest terminateRequest = TerminateInstancesRequest.builder() .instanceIds(instanceId) .build(); CompletableFuture<TerminateInstancesResponse> responseFuture = getAsyncClient().terminateInstances(terminateRequest); return responseFuture.thenCompose(terminateResponse -> { if (terminateResponse == null) { throw new RuntimeException("No response received for terminating instance " + instanceId); } System.out.println("Going to terminate an EC2 instance and use a waiter to wait for it to be in terminated state"); return getAsyncClient().waiter() .waitUntilInstanceTerminated(r -> r.instanceIds(instanceId)) .thenApply(waiterResponse -> null); }).exceptionally(throwable -> { // Handle any exceptions that occurred during the async call throw new RuntimeException("Failed to terminate EC2 instance: " + throwable.getMessage(), throwable); }); }
  • 有关API详细信息,请参阅 “AWS SDK for Java 2.x API参考 TerminateInstances” 中的。

JavaScript
SDK对于 JavaScript (v3)
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

import { EC2Client, TerminateInstancesCommand } from "@aws-sdk/client-ec2"; import { fileURLToPath } from "url"; import { parseArgs } from "util"; /** * Terminate one or more EC2 instances. * @param {{ instanceIds: string[] }} options */ export const main = async ({ instanceIds }) => { const client = new EC2Client({}); const command = new TerminateInstancesCommand({ InstanceIds: instanceIds, }); try { const { TerminatingInstances } = await client.send(command); const instanceList = TerminatingInstances.map( (instance) => ` • ${instance.InstanceId}`, ); console.log("Terminating instances:"); console.log(instanceList.join("\n")); } catch (caught) { if ( caught instanceof Error && caught.name === "InvalidInstanceID.NotFound" ) { console.warn(`${caught.message}`); } else { throw caught; } } ``; };
  • 有关API详细信息,请参阅 “AWS SDK for JavaScript API参考 TerminateInstances” 中的。

Kotlin
SDK对于 Kotlin 来说
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

suspend fun terminateEC2(instanceID: String) { val request = TerminateInstancesRequest { instanceIds = listOf(instanceID) } Ec2Client { region = "us-west-2" }.use { ec2 -> val response = ec2.terminateInstances(request) response.terminatingInstances?.forEach { instance -> println("The ID of the terminated instance is ${instance.instanceId}") } } }
PowerShell
用于 PowerShell

示例 1:此示例终止指定的实例(该实例可能正在运行或处于 “已停止” 状态)。在继续操作之前,cmdlet 将提示您进行确认;使用-Force 开关取消该提示。

Remove-EC2Instance -InstanceId i-12345678

输出:

CurrentState InstanceId PreviousState ------------ ---------- ------------- Amazon.EC2.Model.InstanceState i-12345678 Amazon.EC2.Model.InstanceState
  • 有关API详细信息,请参阅 AWS Tools for PowerShell Cmdlet 参考TerminateInstances中的。

Python
SDK适用于 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 terminate(self): """ Terminates an instance and waits for it to be in a terminated state. """ if self.instance is None: logger.info("No instance to terminate.") return instance_id = self.instance.id try: self.instance.terminate() self.instance.wait_until_terminated() self.instance = None except ClientError as err: logging.error( "Couldn't terminate instance %s. Here's why: %s: %s", instance_id, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise
  • 有关API详细信息,请参阅TerminateInstances中的 AWS SDKPython (Boto3) API 参考。

Ruby
SDK对于 Ruby
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 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 terminated; otherwise, false. # @example # exit 1 unless instance_terminated?( # Aws::EC2::Client.new(region: 'us-west-2'), # 'i-123abc' # ) def instance_terminated?(ec2_client, instance_id) response = ec2_client.describe_instance_status(instance_ids: [instance_id]) if response.instance_statuses.count.positive? && response.instance_statuses[0].instance_state.name == "terminated" puts "The instance is already terminated." return true end ec2_client.terminate_instances(instance_ids: [instance_id]) ec2_client.wait_until(:instance_terminated, instance_ids: [instance_id]) puts "Instance terminated." return true rescue StandardError => e puts "Error terminating 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-terminate-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-terminate-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 terminate instance '#{instance_id}' " \ "(this might take a few minutes)..." unless instance_terminated?(ec2_client, instance_id) puts "Could not terminate instance." end end run_me if $PROGRAM_NAME == __FILE__
  • 有关API详细信息,请参阅 “AWS SDK for Ruby API参考 TerminateInstances” 中的。

Rust
SDK对于 Rust
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

pub async fn delete_instance(&self, instance_id: &str) -> Result<(), EC2Error> { tracing::info!("Deleting instance with id {instance_id}"); self.stop_instance(instance_id).await?; self.client .terminate_instances() .instance_ids(instance_id) .send() .await?; self.wait_for_instance_terminated(instance_id).await?; tracing::info!("Terminated instance with id {instance_id}"); Ok(()) }

使用 W API aiters 等待实例进入已终止状态。使用 Waiters API 需要在 rust 文件中使用 “使用 aws_sdk_ec2:: client:: Waiters”。

async fn wait_for_instance_terminated(&self, instance_id: &str) -> Result<(), EC2Error> { self.client .wait_until_instance_terminated() .instance_ids(instance_id) .wait(Duration::from_secs(60)) .await .map_err(|err| match err { WaiterError::ExceededMaxWait(exceeded) => EC2Error(format!( "Exceeded max time ({}s) waiting for instance to terminate.", exceeded.max_wait().as_secs(), )), _ => EC2Error::from(err), })?; Ok(()) }