Created
November 15, 2022 20:31
-
-
Save daveadams/a862075bab5e613c04bda0815faa96f1 to your computer and use it in GitHub Desktop.
List running EC2 instances with a given tag older than a certain number of hours
This file contains hidden or 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
# too-old.sh | |
# Author: David Adams | |
# License: Public Domain | |
# | |
# Provides a bash function for listing EC2 instances with a given tag value older than a | |
# certain number of hours. This script is not particularly robust to unexpected error | |
# conditions. This is just a quick example. | |
# | |
# PREREQUISITES | |
# | |
# You must have the AWS CLI installed and in your path as `aws` and you must have jq 1.6+ | |
# installed and in your path as `jq`. This function also assumes you have appropriate AWS | |
# credentials configured with access to run ec2:DescribeInstances. Finally, you should also | |
# have your AWS region configured either via your AWS CLI config or by setting the AWS_REGION | |
# environment variable. | |
# | |
# USAGE | |
# | |
# Load this file into your shell by running `source too-old.sh`. | |
# | |
# To list all instances with tag Role=worker launched more than 72 hours ago, run: | |
# | |
# $ list-old-instances Role worker 72 | |
# i-010102930184dab | |
# [... etc ...] | |
# | |
# If no instances are found a message will be written to stderr: | |
# | |
# $ list-old-instances Role none 100000 | |
# No instances found with tag 'Role'='none' running longer than 100000 hours. | |
# | |
list-old-instances() { | |
if (( # < 3 )); then | |
echo "USAGE: list-old-instances <tag-name> <tag-value> <hours>" >&2 | |
return 1 | |
fi | |
local tagname=$1 | |
local tagvalue=$2 | |
local hours=$3 | |
local result=$( | |
aws ec2 describe-instances \ | |
--output json \ | |
--filters \ | |
Name=tag:"$tagname",Values="$tagvalue" \ | |
Name=instance-state-name,Values=running \ | |
| jq -r --argjson hours "$hours" ' | |
.Reservations[].Instances[] | |
|select((.LaunchTime|sub("\\+00:00$";"Z")|fromdate) < (now - ($hours*60*60))) | |
|.InstanceId | |
' | |
) | |
if [[ -z $result ]]; then | |
echo "No instances found with tag '$tagname'='$tagvalue' running longer than $hours hours." >&2 | |
else | |
echo "$result" | |
fi | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment