forked from HariSekhon/DevOps-Bash-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
aws_ec2_terminate_instance_by_name.sh
executable file
·65 lines (50 loc) · 1.8 KB
/
aws_ec2_terminate_instance_by_name.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
63
64
65
#!/usr/bin/env bash
# vim:ts=4:sts=4:sw=4:et
#
# Author: Hari Sekhon
# Date: 2024-08-27 11:28:25 +0200 (Tue, 27 Aug 2024)
#
# https///github.com/HariSekhon/DevOps-Bash-tools
#
# License: see accompanying Hari Sekhon LICENSE file
#
# If you're using my code you're welcome to connect with me on LinkedIn and optionally send me feedback to help steer this or other code I publish
#
# https://www.linkedin.com/in/HariSekhon
#
set -euo pipefail
[ -n "${DEBUG:-}" ] && set -x
srcdir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck disable=SC1090,SC1091
. "$srcdir/lib/aws.sh"
# shellcheck disable=SC2034,SC2154
usage_description="
Terminate an AWS EC2 instance by name
Investigate instance names quickly using adjacent script aws_ec2_instances.sh
$usage_aws_cli_required
"
# used by usage() in lib/utils.sh
# shellcheck disable=SC2034
usage_args="<instance_name>"
help_usage "$@"
num_args 1 "$@"
instance_name="$1"
instance_id="$(VERBOSE=1 "$srcdir/aws_ec2_instance_name_to_id.sh" "$instance_name")"
if ! is_instance_id "$instance_id"; then
die "Invalid Instance ID returned, failed regex validation: $instance_id"
fi
echo
timestamp "Checking instance state"
instance_state="$(
aws ec2 describe-instances --instance-ids "$instance_id" --query 'Reservations[*].Instances[*].State.Name' --output text
)"
if [ "$instance_state" = "terminated" ]; then
timestamp "Instance '$instance_name' with id '$instance_id' is already terminated"
exit 0
elif [ "$instance_state" != "running" ]; then
die "Instance state '$instance_state' was not expected - is not 'terminated' or 'running' - aborting for safety"
fi
echo >&2
read -r -p "Do you want to terminate instance '$instance_name' with id '$instance_id'? (y/N) " answer
check_yes "$answer"
aws ec2 terminate-instances --instance-ids "$instance_id"