Данный BASH скрипт позволяет остановить или запустить все инстансы с определенным тегом.
#!/bin/bash
AWS="$(which aws)"
PROFILE="default"
REGION="eu-west-2"
TAG_KEY="Owner"
TAG_VALUE="Artem"
if [ "$#" == 0 ]
then
echo "This script for start/stop AWS EC Instances by tag"
echo "Usage : $0 [start|stop]"
echo "Example: $0 start"
exit 1
fi
if [ "$1" == "start" ]
then
$AWS --profile $PROFILE --region $REGION ec2 start-instances --instance-ids `$AWS --profile $PROFILE --region $REGION ec2 describe-instances --filters "Name=tag:$TAG_KEY,Values=$TAG_VALUE" --query 'Reservations[].Instances[].InstanceId' --output text`
elif [ "$1" == "stop" ]
then
$AWS --profile $PROFILE --region $REGION ec2 stop-instances --instance-ids `$AWS --profile $PROFILE --region $REGION ec2 describe-instances --filters "Name=tag:$TAG_KEY,Values=$TAG_VALUE" --query 'Reservations[].Instances[].InstanceId' --output text`
else
exec $0
fi
Python3 скрипт, который так же служит для остановки/старта инстансов по тегу, так же фильтрует статус инстансов, чтобы не пробовал стартовать/останавливать инстансы со статусом "terminated"
import boto3
import sys
from botocore.exceptions import ClientError
profile = "default"
region = "eu-west-2"
tagName = "Owner"
tagValue = "Artem"
if sys.argv[1:]:
action = sys.argv[1].upper()
else:
action = "help"
session = boto3.Session(profile_name=profile)
ec2 = session.client('ec2',region_name=region)
custom_filter_start = [{
'Name':'tag:' + tagName,
'Values': [tagValue]},
{
'Name': 'instance-state-name',
'Values': ['stopped']}]
custom_filter_stop = [{
'Name':'tag:' + tagName,
'Values': [tagValue]},
{
'Name': 'instance-state-name',
'Values': ['running', 'pending']}]
def instance_start(instanceId):
# Do a dryrun first to verify permissions
try:
ec2.start_instances(InstanceIds=[instanceId], DryRun=True)
except ClientError as e:
if 'DryRunOperation' not in str(e):
raise
# Dry run succeeded, run start_instances without dryrun
try:
response = ec2.start_instances(InstanceIds=[instanceId], DryRun=False)
print(response)
except ClientError as e:
print(e)
def instance_stop(instanceId):
# Do a dryrun first to verify permissions
try:
ec2.start_instances(InstanceIds=[instanceId], DryRun=True)
except ClientError as e:
if 'DryRunOperation' not in str(e):
raise
# Dry run succeeded, run start_instances without dryrun
try:
response = ec2.stop_instances(InstanceIds=[instanceId], DryRun=False)
print(response)
except ClientError as e:
print(e)
if action == 'START':
response = ec2.describe_instances(Filters=custom_filter_start)
count = len(response['Reservations'])
for x in range(count):
instanceId = response['Reservations'][x]['Instances'][0]['InstanceId']
instance_start(instanceId)
elif action == 'STOP':
response = ec2.describe_instances(Filters=custom_filter_stop)
count = len(response['Reservations'])
for x in range(count):
instanceId = response['Reservations'][x]['Instances'][0]['InstanceId']
instance_stop(instanceId)
else:
print("This script for start/stop AWS EC Instances by tag")
print("Usage : python3 " + sys.argv[0] + " [start|stop]")
print("Example: python3 " + sys.argv[0] + " start")
Может потребоваться установка питон пакета boto3
pip3 install boto3