Simple script we use to connect to Beanstalk host

The title of this post is self explanatory and it explains perfectly what we want to share today with you: a basic script we have in our home directory and we use it each time we want to ssh on a host from a Beanstalk environment.

The script is:

#!/bin/sh

RANDOM=$$$(date +%s)
PEM_FILE=${*: -1}
hosts=""

if [ $# -lt 2 ];
then
echo "You must provide environment name and pem file."
exit 1
elif [ $# -eq 2 ];
then
hosts=`aws ec2 describe-instances --filters "Name=tag:elasticbeanstalk:environment-name,Values='$1'" | grep PublicDnsName | xargs | tr ", " "\n" | grep ec2 | uniq`
else
hosts=`aws ec2 describe-instances --filters "Name=tag:elasticbeanstalk:environment-name,Values='$1'" --profile $2 | grep PublicDnsName | xargs | tr ", " "\n" | grep ec2 | uniq`
fi

array=(`echo $hosts | sed 's/  /\n/g'`)
total=${#array[@]}
if [ $total -eq 0 ];
then
echo "No host found."
exit 1
else
echo "Found $total hosts."
host_to_connect=${array[$RANDOM % ${#array[@]}]}
echo "Connecting to $host_to_connect host ..."
ssh -i "$PEM_FILE" ec2-user@$host_to_connect
fi

Save it in a file – let’s say it’s named connect.sh, make sure that file has the right permissions (chmod 755 connect.sh) and then there are 2 things left before running it:

At this moment, you are ready to go. Usually, we access this script with 3 parameters:

./connect.sh beanstalk_environment_name aws_profile path_to_pem_file

If you provide only 2 parameters, the script will consider credentials for default profile, but the environment name and the path to the pem file are mandatory.

Of course, this script could be easily modified to cover other use cases, but for us it’s perfect as it is. Also, we know it is far from being something we could boast, but as we said, it does its job.

Feel free to add a comment below with your opinion!

4 thoughts on “Simple script we use to connect to Beanstalk host

  1. If there are multiple ec2 running behind elastic beanstalk.. which instance will it connect to?

    1. From what we know, eb cli doesn’t give you control to ec2 instances. you can only do actions related to beanstalk, but not related to hosts where you app runs

Comments are closed.