本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
終止 Amazon EC2執行個體
當您不再需要一或多個 Amazon EC2執行個體時,您可以終止它們。
此範例示範如何使用 AWS SDK for .NET 來終止EC2執行個體。它需要執行個體 ID 作為輸入。
NuGet 套件:
程式設計元素:
-
命名空間 Amazon。EC2
-
命名空間 Amazon.EC2.模型
using System; using System.Threading.Tasks; using System.Collections.Generic; using Amazon.EC2; using Amazon.EC2.Model; namespace EC2TerminateInstance { class Program { static async Task Main(string[] args) { if((args.Length == 1) && (args[0].StartsWith("i-"))) { // Terminate the instance var ec2Client = new AmazonEC2Client(); await TerminateInstance(ec2Client, args[0]); } else { Console.WriteLine("\nCommand-line argument missing or incorrect."); Console.WriteLine("\nUsage: EC2TerminateInstance instance-ID"); Console.WriteLine(" instance-ID - The EC2 instance you want to terminate."); return; } } // // Method to terminate an EC2 instance private static async Task TerminateInstance(IAmazonEC2 ec2Client, string instanceID) { var request = new TerminateInstancesRequest{ InstanceIds = new List<string>() { instanceID }}; TerminateInstancesResponse response = await ec2Client.TerminateInstancesAsync(new TerminateInstancesRequest{ InstanceIds = new List<string>() { instanceID } }); foreach (InstanceStateChange item in response.TerminatingInstances) { Console.WriteLine("Terminated instance: " + item.InstanceId); Console.WriteLine("Instance state: " + item.CurrentState.Name); } } } }
在您執行範例之後,最好登入 Amazon EC2主控台