Archives

Categories

Category: Vagrant

Following on from my post on Customising Vagrant behaviour another handy thing you can do with your Vagrantfile and some simple Ruby is install your plugin dependencies automatically.

Say you are distributing a Vagrant config to your team. You might require them to have vagrant-omnibus and vagrant-aws installed so that they can provision servers on AWS with Chef. Ordinarily you would need to provide them with instructions on installing these plugins, but wouldn’t it be great if they could just:

1

2

3

git clone[project]

cd[project]

vagrant up

With a bit of Ruby you can install these plugins automatically for them and all they have to do is simply run
vagrant up and all systems are go.

Add the following to the top of your Vagrantfile changing the first line to have the plugins you require:

Now everytime Vagrant is run it will quickly check that all of the plugins you require are installed. If a plugin is missing it will be installed and then Vagrant will be re-run with the same arguments you originally provided.

Vagrant is a great piece of software and an integral part of my development toolbox.

One thing that a lot of people don’t realise about Vagrant is that the Vagrantfile which you use to store your configuration in is just Ruby code. This means you can quickly and easily customise the behaviour of Vagrant.

Here are a few quick examples to get you going, place the following snippets in your Vagrant file and then execute a Vagrant command like
vagrant up to see their output.

Output the folder path of your Vagrantfile

1

2

vagrantPath=File.dirname(__FILE__)

puts vagrantPath

Output the Vagrant command (up, halt, destroy etc.)

1

puts ARGV[0]

Output all of the Vagrant command line arguments

1

2

3

ARGV.eachdo|a|

putsa

end

Output the chosen Vagrant provider

1

2

3

4

5

6

7

provider=''

ARGV.eachdo|a|

ifa.include?('--provider=')

provider=a[11,a.length]

end

end

puts provider

Output the username running Vagrant

1

puts ENV['USER']

As you can see adding these snippets to your Vagrantfile is easy and allows powerful custom logic. You could provision certain resources based on the user running Vagrant or stop people from being able to run commands like
vagrant halt, it is very flexible.