Skip to content

Instantly share code, notes, and snippets.

@aljp
Last active August 27, 2018 06:15
Show Gist options
  • Save aljp/0cab85f2a451145e5d46c40bafa19ef6 to your computer and use it in GitHub Desktop.
Save aljp/0cab85f2a451145e5d46c40bafa19ef6 to your computer and use it in GitHub Desktop.
A bash script to start a local python shell connected to remote resources through ssh tunnels
#!/usr/bin/env bash
# THE SHELL ACTIVATOR
# Provide an "environment" name as the first argument to this script and it will open a python shell to the environment's web tier.
if [ -z $1 ]; then
echo "First argument must be the environment"
exit 1
fi
ENV_FILE=$1
# Developers have a folder of .env files for various environments.
if [ ! -f ".environments/${ENV_FILE}.env" ]; then
echo "Invalid environment - Cannot find the environment file"
exit 1
fi
export $(cat .environments/${ENV_FILE}.env)
source $(pipenv --venv)/bin/activate
# The "get_ssh_tunnels" command below returns an SSH command that creates tunnels to resources in a private subnet. These tunnels go through our SSH bastion instance.
# This includes:
# - Postgres Database
# - Redis Database(s)
# The actual SSH Command is run in the background.
# Example: ssh -N -L 5433:postgres.example.com:5432 -L 6479:redis1.example.com:6379 -L 6579:redis2.example.com:6379 user@ssh-bastion.example.com -i ~/.ssh/example.pem
$(python bin/deploy.py -q get_ssh_tunnels -e ${ENV_FILE} -t web) &
SSH_PROCESS_ID=$!
echo "SSH Process ID: ${SSH_PROCESS_ID}"
# This will kill the SSH process when you exit the python shell
function cleanup {
echo "Killing SSH Process ${SSH_PROCESS_ID}"
kill ${SSH_PROCESS_ID}
}
trap cleanup EXIT
# Start Django Shell
python manage.py shell_plus
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment