Developer Guide

Terminating an Amazon EC2 Instance

When you no longer need one or more of your Amazon EC2 instances, you can terminate them.

To terminate an EC2 instance

public static void TerminateInstance( AmazonEC2Client ec2Client, string instanceId) { var request = new TerminateInstancesRequest(); request.InstanceIds = new List<string>() { instanceId }; try { var response = ec2Client.TerminateInstances(request); foreach (InstanceStateChange item in response.TerminatingInstances) { Console.WriteLine("Terminated instance: " + item.InstanceId); Console.WriteLine("Instance state: " + item.CurrentState.Name); } } catch(AmazonEC2Exception ex) { // Check the ErrorCode to see if the instance does not exist. if ("InvalidInstanceID.NotFound" == ex.ErrorCode) { Console.WriteLine("Instance {0} does not exist.", instanceId); } else { // The exception was thrown for another reason, so re-throw the exception. throw; } } }
  1. Create and initialize a TerminateInstancesRequest object.

  2. Set the TerminateInstancesRequest.InstanceIds property to a list of one or more instance IDs for the instances to terminate.

  3. Pass the request object to the TerminateInstances method. If the specified instance doesn't exist, an AmazonEC2Exception is thrown.

  4. You can use the TerminateInstancesResponse object to list the terminated instances, as follows.