Skip to content

Instantly share code, notes, and snippets.

@jespada
Last active September 13, 2018 11:28
Show Gist options
  • Save jespada/e7bed01bf6e11fd37d08c718bbd5f658 to your computer and use it in GitHub Desktop.
Save jespada/e7bed01bf6e11fd37d08c718bbd5f658 to your computer and use it in GitHub Desktop.
ec2 instance launched in last X days
#!/bin/bash
# to list instances launched in in the last 15 days run like:
# ./aws-ec2-launched-in-last.sh 15
# https://stackoverflow.com/questions/18858120/finding-all-amazon-aws-instances-that-do-not-have-a-certain-tag
OLDER=$1
if date -v-"$OLDER"d > /dev/null 2>&1; then
# BSD systems (Mac OS X)
DATE=$(date -v-"$OLDER"d +%Y-%m-%d)
else
# GNU systems (Linux)
DATE=date --date="-$OLDER days" +%Y-%m-%d
fi
##aws ec2 describe-instances --query 'Reservations[].Instances[?LaunchTime>='2018-08-01'][].{id: InstanceId, type: InstanceType, launched: LaunchTime}'
# aws ec2 describe-instances --filters "Name=tag:Name,Values=*" --output json --query 'Reservations[*].Instances[*].[PrivateIpAddress,InstanceId,Tags[?Key=='Name'].Value]'
# aws ec2 describe-instances --filters "Name=tag:Name,Values=*" --query "Reservations[].Instances[?LaunchTime>='2018-09-12'].[PrivateIpAddress,InstanceId,Tags[?Key=='Name'].Value][]"
## aws ec2 describe-instances --query "Reservations[].Instances[?LaunchTime>='2018-09-12'][].{id: InstanceId, type: InstanceType, launched: LaunchTime, tags: Tags}"
# instance-state-name - The state of the instance (pending | running
# | shutting-down | terminated | stopping | stopped ).
echo "STOPPED INSTSNCES LAUNCHED IN LAST $OLDER DAYS"
echo " ID -- InstanType -- Launch time -- Tags"
aws ec2 describe-instances --filter Name=instance-state-name,Values=stopped --query "Reservations[].Instances[?LaunchTime>=\`$DATE\`][].{id: InstanceId, type: InstanceType, launched: LaunchTime, tags: Tags}" |jq -r '.[]| "\(.id) -- \(.type) -- \(.launched) -- \(.tags)"'
echo ""
echo "RUNNING INSTANCES LAUNCHED IN LAST $OLDER DAYS"
echo " ID -- InstanType -- Launch time -- Tags"
aws ec2 describe-instances --filter Name=instance-state-name,Values=running --query "Reservations[].Instances[?LaunchTime>=\`$DATE\`][].{id: InstanceId, type: InstanceType, launched: LaunchTime, tags: Tags}" |jq -r '.[]| "\(.id) -- \(.type) -- \(.launched) -- \(.tags)"'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment