【问题标题】:How to self terminate EC2 from powershell?如何从powershell自行终止EC2?
【发布时间】:2019-10-17 20:32:54
【问题描述】:

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

我试过了

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

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

【问题讨论】:

  • 您是否尝试过使用 AWSPowerShell 模块?
  • @AmitBaranes 我没有。如果你能提出一些建议,我会试试的。基本上,我有一个现有的 powershell 脚本,最后有一行,一旦它完成了它需要做的所有事情,它就会关闭机器。运行问题中的代码给出AWS was not able to validate the provided access credentials
  • 好的,我很快就会发布一段工作代码

标签: amazon-web-services amazon-ec2 aws-sdk


【解决方案1】:

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

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

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.

来自文档:

终止已停止或正在运行的 Amazon EC2 实例,提示输入 在继续之前确认。

请注意,终止的实例在终止后仍然可见 (大约一小时)。 Terminate 操作是幂等的; 如果您多次终止一个实例,则每次调用都会成功。

AWS Tools for PowerShell - Remove-EC2Instance Documtnetion.

【讨论】:

    【解决方案2】:

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

    然后在powershell中简单

    shutdown /s /t 0
    

    如果没有设置InstanceInitiatedShutdownBehavior='terminate',那么我相信默认是stop(而不是terminate)

    【讨论】:

    • 很好的答案,感谢您与我们分享。
    猜你喜欢
    • 2012-05-19
    • 2017-01-20
    • 2020-05-19
    • 1970-01-01
    • 1970-01-01
    • 2010-10-12
    • 1970-01-01
    • 2018-12-14
    • 1970-01-01
    相关资源
    最近更新 更多