Reputation: 52867
I need powershell code to terminate an instance without hardcoding the instance ID.
I tried
aws ec2 terminate-instances --instance-ids 'curl http://169.254.169.254/latest/meta-data/instance-id'
But the instance doesn't terminate. Any ideas?
Upvotes: 2
Views: 835
Reputation: 8152
As mentioned in the comments, I suggest working with AWS Powershell Module.
The following code terminate an instance based on ID and 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
How to create new AccessKey and SecretKey - Managing Access Keys for Your AWS Account.
AWSPowerShell Module installation.
From the docs:
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.
Upvotes: 1
Reputation: 52867
In my case, I was able to set this attribute at instance launch (using some python code in the lambda that launches the instance) InstanceInitiatedShutdownBehavior='terminate'
then in powershell simply
shutdown /s /t 0
If InstanceInitiatedShutdownBehavior='terminate'
is not set, then I believe the default is to stop
(as opposed to terminate
)
Upvotes: 1