Skip to content

Instantly share code, notes, and snippets.

@micklove
Last active July 11, 2018 08:35
Show Gist options
  • Save micklove/7ecfd0f0efc9fe1f63e0107ef856d33f to your computer and use it in GitHub Desktop.
Save micklove/7ecfd0f0efc9fe1f63e0107ef856d33f to your computer and use it in GitHub Desktop.
Filter ec2 instances by state 'running' and Tag Name / Value
# Add this to your ~/.aws/cli/alias file
#
# rit == (R)unning (I)nstances by (T)ag
# (Name and Value)
#
# Allows users to filter their AWS instances, which are running, by Tag Name / Value and see a summarised view.
#
# Pre-requisite - Expects one tag to be 'Name'
#
# e.g. With 1 Tag Match the Instance tagged with "branch" of "develop"
#
# >aws rit branch develop
#
# With 2 Tags Match the Instance tagged with "branch" of "develop" AND "component" of "api"
# >aws rit branch develop component api
#
# Currently limited to 2 tags - future enhancement (suggestions appreciated :)
#
rit =
! g() {
local EXTRA_TAG_FILTER=""
[[ $# -eq 4 ]] && EXTRA_TAG_FILTER="Name=tag:${3},Values=*${4}*"
aws ec2 describe-instances \
--filter "Name=tag:${1},Values=*${2}*" ${EXTRA_TAG_FILTER} "Name=instance-state-name,Values=running" \
--query 'Reservations[].Instances[].{Tags: Tags, State: State.Name, ID: InstanceId,PrivateIpAddress: PrivateIpAddress, LaunchTime: LaunchTime, Name: Tags[?Key==`Name`].Value| [0],Type: InstanceType, Platform: Platform || `Linux`}' \
# jq equivalent of the jmespath match
# | select((.Tags[]|select(.Key=="Name")|.Value) | match("REGEXHERE") )
}; g
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment