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
246 views
in Technique[技术] by (71.8m points)

linux - Start and stop EC2 and then enable/check services on instance using bash

I need to stop start multiple EC2 instances and run few command after they start, using bash on the same manage server without needing to ssh.

I know how to start and stop EC2 instances, for 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 IDs by running:

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 instances?
  2. How can I grab a specific EC2 instance and run a command to check a service enabled after the instance started?

May be I need to run if condition to compare the id or tag name with the EC2 instance needed then run the shell command?

I know the logic but please help me with the script details.


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

1 Answer

0 votes
by (71.8m points)

You can start/stop multiple instances by specifying their IDs:

aws ec2 start-instances --instance-ids i-1a1234 i-1a1235 i-1a1236

If you want to run a script on an instance every time it starts, you can put the script in:

/var/lib/cloud/scripts/per-boot/

This will use cloud-init to automatically run the script, which can then do whatever checking/processing you wish.

When your program on the instance has finished its processing, it can stop its own instance with:

sudo shutdown now -h

For more details, see: Auto-Stop EC2 instances when they finish a task - DEV Community

Alternatively, you cold use AWS Systems Manager Run Command to run a script on the instance. This is a great way to run jobs on instances that are already running. The command can even be executed on multiple instances simultaneously.


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

...