Skip to content

Instantly share code, notes, and snippets.

@xunker
Last active April 18, 2024 18:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xunker/f5483b85f74695f3e89e0d541297643c to your computer and use it in GitHub Desktop.
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"
# 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() {
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