Created
April 18, 2023 18:38
-
-
Save jailbirt/fad9df779f14bc2d8246d498a642c0cf to your computer and use it in GitHub Desktop.
StopStartEc2InstanceByName.sh
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Get the name tag from command line argument | |
if [ $# -eq 0 ] | |
then | |
echo "Please provide a name tag for EC2 instances" | |
exit 1 | |
fi | |
name=$1 | |
# Get the instance IDs for instances with the given name tag | |
instance_ids=$(aws ec2 describe-instances --filters "Name=tag:Name,Values=$name" --query "Reservations[].Instances[].InstanceId" --output text) | |
# Check if there are any instances with the given name tag | |
if [ -z "$instance_ids" ] | |
then | |
echo "No instances found with the name tag $name" | |
exit 1 | |
fi | |
# Stop and start the instances to restart them | |
aws ec2 stop-instances --instance-ids $instance_ids | |
aws ec2 wait instance-stopped --instance-ids $instance_ids | |
aws ec2 start-instances --instance-ids $instance_ids | |
aws ec2 wait instance-running --instance-ids $instance_ids | |
echo "Instances with the name tag $name have been restarted" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment