2

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?

stevec
  • 41,291
  • 27
  • 223
  • 311
  • Have you tried working with AWSPowerShell module? – Amit Baranes Oct 17 '19 at 12:15
  • @AmitBaranes I haven't. If you can suggest something I'll try it. Basically I have an existing powershell script with one line at the end that shuts down the machine once it's done everything it's required to do. Running the code in the question gives `AWS was not able to validate the provided access credentials` – stevec Oct 17 '19 at 12:16
  • 1
    Sure, I'll post a working piece of code shortly – Amit Baranes Oct 17 '19 at 12:17

2 Answers2

1

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)

stevec
  • 41,291
  • 27
  • 223
  • 311
1

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.

Amit Baranes
  • 7,398
  • 2
  • 31
  • 53