DigitalOcean Vagrantfile

I was a bit besotted with being able to develop ansible code using an on-premise Vsphere cluster as a substrate. As I was developing a single-machine ELK stack for testing, I needed something a bit more beefy than virtualbox on my poor overworked laptop, and of course vagrant provides a quick and easy way to spin up a machine from scratch and apply your ansible code to it.

So much for my $DAYJOB, but for my freelance projects and other stuff, I’d quite like the ability to do the same thing on a public cloud provider. DigitalOcean, despite a few problems, is probably the cheapest/easiest API-driven public cloud at the moment., so I found the DigitalOcean Vagrant Provider.

This provider takes a Vagrantfile similar to that of the Vsphere one, however it needs to contain a secret which you probably don’t want to include in your next git commit, so I wrote the following which will execute a shell command to grab this value from the environment:

Vagrant.configure('2') do |config|

    droplet_name = `basename $PWD`.chomp

  config.vm.define "#{droplet_name}" do |config|
      config.vm.provider :digital_ocean do |provider, override|
        override.ssh.private_key_path = '~/.ssh/id_rsa.digitalocean' = 'digital_ocean'
        override.vm.box_url = ""
        provider.token = `echo $DO_API_TOKEN`
        provider.image = 'centos-6-5-x64'
        provider.region = 'lon1'
        provider.size = '512mb'

As you can also see, line 3 dynamically names the droplet with the basename of the current working directory. I have a modifed .bashrc which will provide the DIgitalOcean API token as an environment variable $DO_API_TOKEN. This is used at line 10 as the value for provider.token.

It’s also necessary to provide a separate, unused keypair at the location in override.ssh.private_key_path.

ssh-keygen -b 4096 -f id_rsa.digitalocean

Now a vagrant up will bring up a droplet with the given parameters for you to do with as you will. I intend to use the ansible provisioner to test out some things, which might make a good topic for future posts.

If you don’t want to keep the droplet around, a vagrant destroy will, surprise surprise, destroy the droplet and stop it costing you money, and/or potentially hanging around being a security risk..

I’d previously cobbled something together using Terraform + Ansible, but this is a lot cleaner and easier :)


Now read this

Run ad-hoc ansible commands against your vagrant box

OK, 4 years down the line, here’s my next pearl of wisdom. I’m not going to make statements about keeping this blog updated, because, as you can see, they generally fail :) I’m working with vagrant boxes running on a VMware vsphere... Continue →