AWS Doc SDK ExamplesWord
기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.
an AWS SDK 또는 CLITerminateInstances
와 함께 사용
다음 코드 예제는 TerminateInstances
의 사용 방법을 보여 줍니다.
작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
- .NET
-
- AWS SDK for .NET
-
참고
더 많은 on 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) { try { var request = new TerminateInstancesRequest { InstanceIds = new List<string> { ec2InstanceId } }; var response = await _amazonEC2.TerminateInstancesAsync(request); Console.Write("Waiting for the instance to terminate."); await WaitForInstanceState(ec2InstanceId, InstanceStateName.Terminated); Console.WriteLine($"\nThe instance {ec2InstanceId} has been terminated."); return response.TerminatingInstances; } catch (AmazonEC2Exception ec2Exception) { if (ec2Exception.ErrorCode == "InvalidInstanceId") { _logger.LogError( $"InstanceId is invalid, unable to terminate. {ec2Exception.Message}"); } throw; } catch (Exception ex) { _logger.LogError( $"An error occurred while terminating the instance.: {ex.Message}"); throw; } } /// <summary> /// Wait until an EC2 instance is in a specified state. /// </summary> /// <param name="instanceId">The instance Id.</param> /// <param name="stateName">The state to wait for.</param> /// <returns>A Boolean value indicating the success of the action.</returns> public async Task<bool> WaitForInstanceState(string instanceId, InstanceStateName stateName) { var request = new DescribeInstancesRequest { InstanceIds = new List<string> { instanceId } }; // Wait until the instance is in the specified state. var hasState = false; do { // Wait 5 seconds. Thread.Sleep(5000); // Check for the desired state. var response = await _amazonEC2.DescribeInstancesAsync(request); var instance = response.Reservations[0].Instances[0]; hasState = instance.State.Name == stateName; Console.Write(". "); } while (!hasState); return hasState; }
-
API 세부 정보는 TerminateInstances AWS SDK for .NET 참조의 API를 참조하세요.
-
- Bash
-
- AWS CLI Bash 스크립트 사용
-
참고
더 많은 on 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 }
-
API 세부 정보는 AWS CLI 명령 참조의 TerminateInstances를 참조하세요.
-
- C++
-
- C++ SDK
-
참고
더 많은 on 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 세부 정보는 TerminateInstances AWS SDK for C++ 참조의 API를 참조하세요.
-
- 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 인스턴스 사용을 참조하세요.
-
API 세부 정보는 AWS CLI 명령 참조의 TerminateInstances
를 참조하세요.
-
- Java
-
- Java 2.x용 SDK
-
참고
더 많은 on 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 세부 정보는 TerminateInstances AWS SDK for Java 2.x 참조의 API를 참조하세요.
-
- JavaScript
-
- SDK for JavaScript (v3)
-
참고
더 많은 on GitHub가 있습니다. AWS 코드 예시 리포지토리
에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요. import { EC2Client, TerminateInstancesCommand } from "@aws-sdk/client-ec2"; import { fileURLToPath } from "node:url"; import { parseArgs } from "node: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 세부 정보는 TerminateInstances AWS SDK for JavaScript 참조의 API를 참조하세요.
-
- Kotlin
-
- Kotlin용 SDK
-
참고
더 많은 on 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}") } } }
-
API 세부 정보는 Word for Kotlin TerminateInstances
참조의 Word를 참조하세요. AWS SDK API
-
- PowerShell
-
- for PowerShell 도구
-
예제 1:이 예제는 지정된 인스턴스를 종료합니다(인스턴스가 실행 중이거나 '중지됨' 상태일 수 있음). 계속하기 전에 cmdlet에 확인 메시지가 표시됩니다. -강제 스위치를 사용하여 프롬프트를 숨깁니다.
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
-
- Python용 SDK(Boto3)
-
참고
더 많은 on GitHub가 있습니다. AWS 코드 예시 리포지토리
에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요. class EC2InstanceWrapper: """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) instance actions using the client interface.""" def __init__( self, ec2_client: Any, instances: Optional[List[Dict[str, Any]]] = None ) -> None: """ Initializes the EC2InstanceWrapper with an EC2 client and optional instances. :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level access to AWS EC2 services. :param instances: A list of dictionaries representing Boto3 Instance objects. These are high-level objects that wrap instance actions. """ self.ec2_client = ec2_client self.instances = instances or [] @classmethod def from_client(cls) -> "EC2InstanceWrapper": """ Creates an EC2InstanceWrapper instance with a default EC2 client. :return: An instance of EC2InstanceWrapper initialized with the default EC2 client. """ ec2_client = boto3.client("ec2") return cls(ec2_client) def terminate(self) -> None: """ Terminates instances and waits for them to reach the terminated state. """ if not self.instances: logger.info("No instances to terminate.") return instance_ids = [instance["InstanceId"] for instance in self.instances] try: self.ec2_client.terminate_instances(InstanceIds=instance_ids) waiter = self.ec2_client.get_waiter("instance_terminated") waiter.wait(InstanceIds=instance_ids) self.instances.clear() for instance_id in instance_ids: print(f"• Instance ID: {instance_id}\n" f"• Action: Terminated") except ClientError as err: logger.error( f"Failed instance termination details:\n\t{str(self.instances)}" ) error_code = err.response["Error"]["Code"] if error_code == "InvalidInstanceID.NotFound": logger.error( "One or more instance IDs do not exist. " "Please verify the instance IDs and try again." ) raise
-
API 세부 정보는 Word for Python(Boto3) TerminateInstances 참조의 Word를 참조하세요. AWS SDK API
-
- Ruby
-
- Ruby용 SDK
-
참고
더 많은 on 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.' true rescue StandardError => e puts "Error terminating instance: #{e.message}" 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)...' return if instance_terminated?(ec2_client, instance_id) puts 'Could not terminate instance.' end run_me if $PROGRAM_NAME == __FILE__
-
API 세부 정보는 TerminateInstances AWS SDK for Ruby 참조의 API를 참조하세요.
-
- Rust
-
- Rust용 SDK
-
참고
더 많은 on 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(()) }
웨이터 API를 사용하여 인스턴스가 종료될 때까지 기다립니다. 웨이터 API를 사용하려면 rust 파일에 'use 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(()) }
-
API 세부 정보는 Word for Rust TerminateInstances
참조의 Word를 참조하세요. AWS SDK API
-