简体   繁体   中英

AWS EC2 stop all through PowerShell/CMD tools

I utilise a number of 'throwaway' servers in AWS and we're looking at trying to keep the cost of these down.

Initially, we're looking for a fairly basic 'awsec2 stop all' command to be run on a scheduled basis from a server we do know will be running 24/7.

Upon checking against what AWS have documented, it appears that we need to pull in all the currently running instances, grab the ID's of these and then pass them through into the command, rather than simply stating I want all instances to turn off.

Is there a better method collecting these ID's such as simply being able to issue a 'stop all'?

Appreciate the help.

The AWS CLI provides built-in JSON parsing with the --query option. Additionally, you can use the --filter option to execute stop commands on running instances only.

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

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

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

In plain English, the line above gets a collection of EC2 instance objects (Amazon.EC2.Model.Reservation), grabs the RunningInstance property for each (a collection of various properties relating to instance), and uses that to grab the InstanceId of each and stop the instance.

These functions are mapped as follows:

Be sure to check out the help for Stop-EC2Instance ... has some useful parameters like -Terminate and -Force that you may be interested in.

This one-liner will stop all the instnaces:

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

Provided:

  1. You have AWS-CLI instlled ( http://aws.amazon.com/cli/ )
  2. You have jq json parser installed. ( http://stedolan.github.io/jq/ )

..and yeah, above syntax is for Linux Bash shell specific. You can mimic the same for powershell on windows and figure out a powersehll way of parsing json.

if anyone ever wants to do what Peter Moon described via 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

it's basically the same command but you have to add the --region after describe-instances and after stop-instances to make it work. watch out for the a/b/c that's usually included in the region name. that does seems to cause errors if included here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM