Jonathan Altman

Dotcom Thousandaire

January 11, 2013

I am doing a bunch of work in VMs managed with Vagrant+chef, and I have several different VMs configured for different projects/roles so that I can do dev work on a VM that has just the set of things on it that a QA or production box will have.  To make it easier, I put together some bash functions and a tab completion setup in my .bash_profile to make it easier to work with vagrant and multiple VMs.  I will describe what I wanted to accomplish and how I did it.

Rationale

What I wanted was to be able to have multiple VMs and have it be easy to run a command against any of them without having to cd (change directory) to the correct directory for a server and then do what I needed. The idea is that the following commands should behave as follows:

  • vag server_a up: bring server_a up via vagrant up in server_a's directory
  • vag server\name_ vagrant\command_ ...: in general, run the vagrant command vagrant\command_ for the server server\name_
  • firevm server\name_: this is the one special command addition I made. I find it useful when I'm doing work on a server to bring it up from a suspended state, ssh into it, do my thing, then suspend the server when I log out of the ssh session. firevm is the name of the command I wanted to do that
  • Tab completion should work on the vag AND firevm command, so that if I tab-complete where server\name_ should be I should see a list of the servers available. For vag I also want it so that if I tab-complete on vagrant\command_ I get auto-complete against the list of vagrant subcommands

How I Did It

Where the Vagrant-powered VMs have to live

To make the scripting easy, I decided that all the Vagrant setups would live in one directory.

Setting Up the .bash_profile file

I put the following code in my ~/.bash_profile file (also available in this gist): 

The vag function

The vag function takes care of the vag server\name_ vagrant\sub-command ..._.

Implementing tab completion

The \vagrant_servers()_ function and the complete -F ... command that follows it handles the tab completion. For the first argument to the commands it completes for, it shows the list of servers (directory names) in the common directory that your vagrant servers live in. If you are using the vag command, it will provide tab completion on the second argument with the list of vagrant sub-commands available. The list of subcommands was scraped out of the invocation of the vagrant command line with no arguments earlier in the script where VAGRANT_SUBCMDS is defined. No other arguments past those supported get any tab completion.

The firevm special command

Finally, the firevm shell function takes care of the special handling to resume the vm, ssh into it, and then suspend it.