Skip to content

Instantly share code, notes, and snippets.

@juanje
Created April 12, 2012 07:46
Show Gist options
  • Save juanje/2365480 to your computer and use it in GitHub Desktop.
Save juanje/2365480 to your computer and use it in GitHub Desktop.
Example of Rake tasks for dealing with Vagrant
#NOTA: this is actually rake/helper.rb but gists can't named files as directories
require 'vagrant'
class VM
def initialize(opts=nil)
opts ||= {ui_class: Vagrant::UI::Colored}
@env = Vagrant::Environment.new(opts)
@vm = @env.primary_vm
end
def project_path
@vm.config.vm.shared_folders['v-project'][:guestpath]
end
def check_if_alive
raise "Must run `vagrant up`" if !@vm.created?
raise "Must be running!" if @vm.state != :running
end
def cli(command=nil)
@env.cli(command) if command
end
def sudo(command=nil)
check_if_alive
@vm.channel.sudo(command) if command
end
def execute(command=nil, cwd=nil)
check_if_alive
cwd ||= project_path
command = "cd #{cwd}; #{command}"
# Some code borrowed from Vagrant::Command::SSH.ssh_execute
exit_status = 0
exit_status = @vm.channel.execute(command, :error_check => false) do |type, data|
channel = type == :stdout ? :out : :error
case type
when :stdout
color = :green
when :stderr
color = :red
else
color = :clear
end
# Print the SSH output as it comes in, but don't prefix it and don't
# force a new line so that the output is properly preserved
@vm.ui.info(data.to_s,
:prefix => false,
:new_line => false,
:channel => channel,
:color => color)
end
# Exit with the exit status we got from executing the command
exit exit_status
end
end
load 'rake/helper.rb'
desc "Set up the VM"
task :up do
vm = VM.new
vm.cli('up')
end
desc "Shutdown the VM"
task :graceful_down do
vm = VM.new
vm.sudo('halt')
end
desc "Start sinatra app"
task :start_sinatra do
vm = VM.new
status = vm.execute('rackup -D')
raise "It didn't start" if status > 0
end
desc "Run tests at the sinatra app"
task :tests do
vm = VM.new
vm.execute('rake features')
end
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant::Config.run do |config|
config.vm.box = "base"
config.vm.box_url = "http://files.vagrantup.com/lucid32.box"
config.vm.share_folder "v-project", "/var/www/hi-sinatra", "hi-sinatra"
config.vm.network :hostonly, "192.168.33.10"
end
@quantumJLBass
Copy link

I followed this, and have been getting and odd error I just can't seem to get around. Google is failing me again. I have the latest vagrant (1.3.3) on windows 7 and I can rake, but I get this error

CLI outputt

any ideas on corrections to get this going?

@stevepereira
Copy link

how does "require 'vagrant'" work with Vagrant 1.1+? are you guys using the gem install of vagrant?

@juanxhos
Copy link

wich gem vagrant did you install ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment