Last active
May 28, 2024 19:03
-
-
Save xunker/f5483b85f74695f3e89e0d541297643c to your computer and use it in GitHub Desktop.
Get IP address of EC2 Instance via the "Name" Tag, using "aws cli"
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
# Uses `aws cli` to get list of *running* EC2 instances, queried by the "Value" | |
# of the Tag "Name". | |
# In the case of Beanstalk EC2 instances, that "Name" is usually the same as the | |
# name of the Beanstalk cluster. | |
# | |
# To install, either copy this function to your .bashrc/.bash_profile/.zprofile, | |
# or save the file in your home directory and add `source .ec2instances.bash` to | |
# one of the files above or whatever file is correct for your shell. | |
# | |
# Usage: | |
# ec2instances [name] | |
# - `name` is a string, and can include wildcard characters. | |
# If using wildcards, be sure to escape them or wrap name in quotes. | |
# | |
# Returns a JSON array of objects containing the instance ID, names, and IPs. | |
# | |
# Example: | |
# $ ec2instances someserver\* | |
# | |
# [ | |
# { | |
# "InstanceId": "i-0afed43727f4132e8", | |
# "PrivateIpAddress": "172.16.84.121", | |
# "PublicIpAddress": null, # this server doesn't have one | |
# "Name": "someserver-1" | |
# } | |
# ] | |
# | |
ec2instances() { | |
if [ -z "$1" ]; then | |
echo "usage: ec2instances <instance-name>" | |
echo "" | |
echo "<instance-name> can use '*' as wildcard character, but will need to either" | |
echo "be escaped (ex: server\\*) or wrapped in quotes (ex: \"server*\")." | |
return -1 | |
fi | |
aws ec2 describe-instances \ | |
--filters "Name=tag:Name,Values=$1" \ | |
--query " | |
Reservations[*].Instances[?State.Name=='running'].[ | |
{ | |
"InstanceId": InstanceId, | |
"PrivateIpAddress": PrivateIpAddress, | |
"PublicIpAddress": PublicIpAddress, | |
"Name": Tags[?Key=='Name'].Value | [0] | |
} | |
][0] | |
" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment