SSH to an EC2 Instance via Alfred

This may a task limited to me, but in case it’s not, here’s my goal:

  1. I have a collection of identical Amazon EC2 instances, all sharing the same “name” tag for identification; together they make up a Drupal server farm for a single site.
  2. I want to SSH to one of the instances – it doesn’t matter which one – so that I can execute some drush commands.

Heretofore my procedure has been cumbersome, involving logging in to the EC2 dashboard on the web, filtering my long list of instances by name, copying the external DNS name from one of the instance to the clipboard, and then pasting this, as part of an SSH command, to the terminal.

What I’ve done to streamline this, using Alfred and the AWS CLI, is this:

I set up an Alfred workflow, with the trigger keyword d7:

Alfred App Workflow Setup

The workflow triggers a Terminal command:

ssh -t -p 22 -i 'keypair.pem' \
ec2-user@`aws ec2 describe-instances --profile clientname --filters "Name=tag:Name,Values=name-filter"  \
--output text \
--query 'Reservations[*].Instances[*].PublicDnsName' | tail -n 1` \
"sudo su - apache"

Where, in my case, the components of the above are:

  • keypair.pem is the name of the EC2 keypair I used with SSH to login to the instance
  • ec2-user is the username I want to use to SSH to the instance
  • clientname is an AWS CLI profile name that provides credentials
  • name-filter is the name that the pool of instances I want to select from share in common

This command has the effect of using the AWS CLI to look up the external DNS names of all of the instances in this pool, grabbing the last one, and then SSHing to that instances and su’ing to the apache user.

So now I just trigger Alfred (Control + Space) and type d7 and press ENTER. Presto.

Alfred Workflow

All of this presupposes that you’ve already set up the AWS CLI and ensured it’s working for you.


Add new comment