-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstop_ec2_instances.sh
More file actions
75 lines (62 loc) · 2.6 KB
/
stop_ec2_instances.sh
File metadata and controls
75 lines (62 loc) · 2.6 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
75
#!/usr/bin/env bash
# stop_javier_instances.sh
# Purpose: Stop every running EC2 instance whose Name tag contains "javier" (any case)
# across the specified regions. Print friendly names before stopping and a summary after.
# Compatibility: Works with macOS default bash 3.2. Do not source this file.
set -euo pipefail
AWS_PROFILE=dev
if ! aws sts get-caller-identity --profile "$AWS_PROFILE" >/dev/null 2>&1; then
echo "SSO session expired or not logged in. Logging in..."
aws sso login --profile sso-main
fi
# Regions to scan. Add or remove regions as needed.
regions=(eu-west-1 eu-north-1 us-east-1)
# EC2 tag filters are case sensitive. Include common case variants explicitly.
NAME_FILTERS='*javier*,*Javier*,*JAVIER*'
for r in "${regions[@]}"; do
echo "### $r"
# Query only instances that are running and whose Name matches the filters.
# Return a tab-separated list with two columns: InstanceId and Name tag value.
pairs="$(aws ec2 describe-instances \
--profile "$AWS_PROFILE" \
--region "$r" \
--filters "Name=tag:Name,Values=${NAME_FILTERS}" "Name=instance-state-name,Values=running" \
--query 'Reservations[].Instances[].[InstanceId, Tags[?Key==`Name`]|[0].Value]' \
--output text || true)"
# If the query returned an empty string or whitespace only, there is nothing to stop.
if [[ -z "${pairs// }" ]]; then
echo "Nothing to stop in $r."
continue
fi
# Build an array of instance IDs and a human friendly string "Name (ID)".
ids=()
pretty=""
while IFS=$'\t' read -r id name; do
# Skip lines without an instance ID.
[[ -z "${id:-}" ]] && continue
ids+=("$id")
pretty+="${name:-unknown} (${id}) "
done <<< "$pairs"
# Print the exact set of instances that will be stopped.
echo "Stopping: $pretty"
# Call stop-instances with the full array of IDs.
# Use "${ids[@]}" to expand all array elements. Do not use $ids.
aws ec2 stop-instances --profile "$AWS_PROFILE" --region "$r" --instance-ids "${ids[@]}" >/dev/null
# Wait until all targeted instances reach the stopped state.
aws ec2 wait instance-stopped --profile "$AWS_PROFILE" --region "$r" --instance-ids "${ids[@]}"
# Print a summary table for the instances that were stopped in this region.
aws ec2 describe-instances \
--profile "$AWS_PROFILE" \
--region "$r" \
--instance-ids "${ids[@]}" \
--query 'Reservations[].Instances[].{
AZ:Placement.AvailabilityZone,
Id:InstanceId,
Name: Tags[?Key==`Name`]|[0].Value,
PrivateIP:PrivateIpAddress,
PublicIP:PublicIpAddress,
State:State.Name,
Type:InstanceType
}' \
--output table
done