-
Notifications
You must be signed in to change notification settings - Fork 3
Script: get_instances
Use this script to get a list of running AWS Linux EC2 instances and transform this list into environment variables with ssh connection information.
The script has a bash function fn_hosts
that executes the script job. This function accepts 3 parameters. Only the first and second parameters are required. The third has a default value: default
which is the default awscli profile.
fn_hosts <region> <aws_ssh_keys_directory> <awscli_profile>
For each instance that you wish to be found by this script, you need to add fours tags:
- ssh_user: the user used to connect in the instance (ubuntu)
- ssh_port: the ssh port (22)
- ssh_key: the ssh key (my_key.pem)
- Name: put a name in you instance without spaces
Download your keys into a directory in your station and save the path in your mind. Let's assume that you choose ~/.aws_keys/
Create an alias into .bashrc or .profile:
. /opt/galintools/bin/get_instances
alias ec2hostssa-east-1="rm -f /tmp/defaulthosts_sa-east-1.tmp ; fn_hosts sa-east-1 ~/.aws_keys/ ; source /tmp/defaulthosts_sa-east-1.tmp ; rm -f /tmp/defaulthosts_sa-east-1.tmp"
The above example will:
- Source the script
- Make sure to remove the temporary file created by script
- Call the function fn_hosts with two parameters: the region to search for instances and the ssh keys directory. The function will search for instances on the
default
profile - Source the temporary file created to set the environment vars
- Remove the temporary file created by script
Now you can access your instances by doing this:
eval $instancename_region_instanceid
NOTE 1: The script will create the temporary file with a name that is formed by the profile + hosts_ + region + .tmp
. For example: if you have only one profile in your ~/.aws/credentials, then it will assumes default as the profile name. So, fn_hosts function will create /tmp/defaulthosts_.tmp
NOTE 2: if you named your instances with a minus sign ( - ) it will be converted to underscore ( _ ) to be possible to source the environment variable.
NOTE 3: The variable name will be lower case even if the instance name is upper case
NOTE 4: The variable will be constructed with the following pattern: instancename_region_instanceid