AWS EC2 Stops Through PowerShell / CMD Tools

I use several "remote" servers in AWS, and we are trying to keep their cost.

Initially, we are looking for a fairly basic command "awsec2 stop all" to run on a schedule from a server that, as we know, will work 24/7.

When verifying that AWS is documented, it seems that we need to use all the current instances, grab the identifier of these and then pass them to the command, and not just state that I want all the instances to shut down,

Is there a better way to collect these identifiers, for example, just the ability to โ€œstop everythingโ€?

Rate the help.

+2
powershell amazon-web-services amazon-ec2
source share
4 answers

AWS CLI provides built-in JSON analysis with the --query option. Alternatively, you can use the --filter option to execute stop commands only to start instances.

aws ec2 describe-instances \ --filter Name=instance-state-name,Values=running \ --query 'Reservations[].Instances[].InstanceId' \ --output text | xargs aws ec2 stop-instances --instance-ids 
+6
source share

This is not tested, but should do the trick with AWS Tools for Powershell :

 @(Get-EC2Instance) | % {$_.RunningInstance} | % {Stop-EC2Instance $_.InstanceId} 

In plain English, the line above receives a collection of instances of an EC2 instance (Amazon.EC2.Model.Reservation), grabs the RunningInstance property for each (a collection of different properties related to the instance), and uses this to capture each InstanceId and stop the instance.

These functions are displayed as follows:

Be sure to check out the help for Stop-EC2Instance ... there are some useful options, such as -Terminate and -Force , that may interest you.

+3
source share

This single line will stop all installations:

 for i in $(aws ec2 describe-instances | jq '.Reservations[].Instances[].InstanceId'); do aws ec2 stop-instances --instance-ids $i; done 

Given that:

.. and yes, the above syntax is for Linux Bash. You can simulate the same for powershell on windows and figure out the powershell method for parsing json.

+2
source share

if anyone wants to do what Peter Moon described through AWS DataPipeline:

 aws ec2 describe-instances --region eu-west-1 --filter Name=instance-state-name,Values=running --query 'Reservations[].Instances[].InstanceId' --output text | xargs aws ec2 stop-instances --region eu-west-1 --instance-ids 

this is basically the same command, but you need to add --region after describe-instances and after stop-instances for it to work. Watch for a / b / c, which is usually included in the name of the region. which seems to cause errors if included here.

0
source share

All Articles