Skip to content

Instantly share code, notes, and snippets.

@bonclay7
Created February 5, 2018 10:44
Show Gist options
  • Select an option

  • Save bonclay7/6c23a1019678585d704d5a0796232009 to your computer and use it in GitHub Desktop.

Select an option

Save bonclay7/6c23a1019678585d704d5a0796232009 to your computer and use it in GitHub Desktop.
Useful functions to list your instances and eventually ssh to it
# Get a formatted list of instances from an instance name (or a part of it)
function instances_ips(){
local instance_name=$1
[ -z ${instance_name} ] && { echo "Missing instance name"; return 1; }
aws ec2 describe-instances \
--filters Name=tag:Name,Values=${instance_name} \
--query 'Reservations[*].Instances[*].{ID:InstanceId, Name:Tags[?Key==`Name`].Value, PrivateIP:PrivateIpAddress, PublicIp:PublicIpAddress, State:State.Name}' \
--output json \
--region us-west-1 | jq -r ".[] | .[] | {Id: .ID, Name: .Name[0], PrivateIP: .PrivateIP, PublicIp: .PublicIp, State: .State}"
}
# From an instance-id, get some details about an EC2 instance
function instance_details(){
local instance_id=$1
[ -z ${instance_id} ] && { echo "Missing instance id"; return 1; }
aws ec2 describe-instances \
--filters Name=instance-id,Values=${instance_id} \
--query 'Reservations[*].Instances[*].{ID:InstanceId, Name:Tags[?Key==`Name`].Value, PrivateIP:PrivateIpAddress, PublicIp:PublicIpAddress, State:State.Name}' \
--output json \
--region us-west-1 | jq -r ".[] | .[] | {Id: .ID, Name: .Name[0], PrivateIP: .PrivateIP, PublicIp: .PublicIp, State: .State} | to_entries |map(\"\(.key)=\(.value|tostring)\")|.[] "
}
# From an instance id, Use instance_details function to get it's public ip and then ssh to it
# For this to work automatically, you'll neeed to setup your ssh config properly
function ssh_instance_id(){
local instance_id=$1
[ -z ${instance_id} ] && { echo "Missing instance id"; return 1; }
ssh $(instance_details ${instance_id} | awk -F'=' '/PublicIp/ {print $2}')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment