-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheck_create_instances.sh
63 lines (51 loc) · 1.66 KB
/
check_create_instances.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#! /bin/bash
# Author: Jorge Marcos Martos
queue_url=$(aws sqs list-queues --query QueueUrls[0])
queue_url="${queue_url%\"}"
queue_url="${queue_url#\"}"
ami_id="ami-02d1f8db964df5386"
function check_messages () {
queue_check=$(aws sqs get-queue-attributes --queue-url $queue_url \
--attribute-names ApproximateNumberOfMessages)
number_messages=$(echo $queue_check | jq -r '.Attributes.ApproximateNumberOfMessages')
}
function launch_instance () {
aws ec2 run-instances --image-id $ami_id --count 1 --instance-type t2.micro
}
function destroy_instance () {
instance_id=$(aws ec2 describe-instances \
--filters "Name=instance-state-name,Values=running" \
| jq -r ".Reservations[0] | .Instances[] | .InstanceId")
aws ec2 terminate-instances --instance-ids $instance_id
}
function check_instances () {
running_instances=$(aws ec2 describe-instances \
--filters "Name=instance-state-name,Values=running" \
--query "Reservations[*].Instances[*].InstanceId" --output text | wc -l)
}
main () {
while [ "$number_messages" != 0 ]
check_messages
check_instances
let threshold="($number_messages + 9) / 10 - $running_instances"
echo "Workload is $threshold"
do
if [ $running_instances -lt 5 ] && [ $threshold -gt 0 ]
then
echo 'Launching an instance...'
launch_instance
elif [ $running_instances -eq 0 ] && [ $threshold -le 0 ]
then
echo 'There are no instances yet or the process has been completed'
elif [ $running_instances -eq 5 ] && [ $threshold -gt 0 ]
then
echo 'Maximum number reached, cannot create any more instances...'
else
echo 'Destroying an instance...'
destroy_instance
fi
echo 'Next check in 15s'
sleep 15
done
}
main