如何从 powershell 自行终止 EC2?

How to self terminate EC2 from powershell?

我需要 powershell 代码来终止实例,而无需对实例 ID 进行硬编码。

我试过了

aws ec2 terminate-instances --instance-ids 'curl http://169.254.169.254/latest/meta-data/instance-id'

但实例并未终止。有任何想法吗?

就我而言,我能够在实例启动时设置此属性(在启动实例的 lambda 中使用一些 python 代码)InstanceInitiatedShutdownBehavior='terminate'

然后在 powershell 中简单地

shutdown /s /t 0

如果未设置 InstanceInitiatedShutdownBehavior='terminate',那么我认为默认值为 stop(与 terminate 相对)

如评论中所述,我建议使用 AWS Powershell 模块。

以下代码根据 ID 和区域终止实例。

Install-Module AWSPowerShell
Import-Module AWSPowerShell
#Set AWS Credential        
Set-AWSCredential -AccessKey "AccessKey" -SecretKey "SecretKey"     
#Remove EC2 Insatnace
Remove-EC2Instance -InstanceId "InstanceId" -Region "Region"  -Force

如何创建新的 AccessKey 和 SecretKey - Managing Access Keys for Your AWS Account.

AWSPowerShell Module installation.

来自文档:

Terminates a stopped or running Amazon EC2 instance, prompting for confirmation before proceeding.

Note that terminated instances will remain visible after termination (for approximately one hour). The Terminate operation is idempotent; if you terminate an instance more than once, each call will succeed.

AWS Tools for PowerShell - Remove-EC2Instance Documtnetion.