aaron dodd dot com

Query AWS EC2 nodes launched older than a certain date

28 Feb 2018 - Aaron Dodd

The AWS CLI allows for querying and filtering results, but I was having issues with creating a script to give me a list of running nodes launched more than 10 minutes ago.

Below is an example of how to do this.

#!/bin/bash

# Example how to query AWS for nodes that have been online older than a certain date
# Example below returns just the "Name" tag value (intent is for looping through for other actions)
# Example below also filters by "state=running" to excluded stopped or pending instances
# To get newer than a certain date, just alter ?LaunchTime<=${ec2_older_than_date} for the <= to be >=

query_older_than_minutes=10

# sed line conforms date output to AWS's datetime format
ec2_older_than_date=$(date --date='-10 minutes' --utc "+%FT%T.%N" | sed -r 's/[[:digit:]]{6}$/Z/')

# add backticks to variable for inclusion in AWS call
ec2_older_than_date="\`${ec2_older_than_date}\`"

aws_servers=$(aws ec2 describe-instances --filters "Name=tag:APPGROUP,Values=myfunapp" "Name=instance-state-name,Values=running" --query "Reservations[].Instances[?LaunchTime<=${ec2_older_than_date}].[Tags[?Key==\`Name\`].Value]" --output text)

Gist

The “aws_servers” could then be looped (for server in ${aws_servers}; do …)