Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
683 views
in Technique[技术] by (71.8m points)

disable service before stopping one of the aws ec2 using bash script

I need to stop start multiple ec2 and run few command before and after ,using bash on the same manage server so no need to ssh. I know how to start and stop ec2, example:

start instance:

#! /bin/bash
aws ec2 start-instances --instance-ids i-1a1234

stop instance:

#! /bin/bash
aws ec2 stop-instances --instance-ids i-1a1234

I figured how to list all ec2 id by running :i.e.:

aws ec2 describe-instances --filters "Name=tag:Name,Values=Test: Instance 1" --query 'Reservations[].Instances[].[InstanceId] --output text

My questions are:

  1. how can I stop/start multiple ec2.

  2. how can I grab a specific ec2 and run a command to disable service before stopping and enable it after ec2 started.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Just like:

aws ec2 describe-instances --filters "Name=tag:Name,Values=Test: Instance 1" --query 'Reservations[].Instances[].[InstanceId] --output text

lists the instances on aws. The following will show the public DNS names of the instances

aws ec2 describe-instances --filters "Name=tag:Name,Values=Test: Instance 1" --query 'Reservations[].Instances[].[PublicDnsName] --output text

If the instances are running with no public access, the following can be run for a list of private IP addresses:

aws ec2 describe-instances --filters "Name=tag:Name,Values=Test: Instance 1" --query 'Reservations[].Instances[].[PrivateIpAddress] --output text

The aws commands can then be used in a loop to process each entry:

for var in $(aws ec2 describe-instances --filters "Name=tag:Name,Values=Test: Instance 1" --query 'Reservations[].Instances[].[PrivateIpAddress] --output text)
do
     ssh -i somekey.pem "ec2-user@$var" ......... # Loop through each IP address and run ssh
done
for var in $(aws ec2 describe-instances --filters "Name=tag:Name,Values=Test: Instance 1" --query 'Reservations[].Instances[].[InstanceId] --output text)
do
     aws ec2 stop-instances --instance-ids "$var" # Loop through each instance id and stop.
done

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...