Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Vagrant command with a plugin

I'm trying to add a couple of custom commands to a Vagrantfile so I can use vagrant <cmd> instead of cluttering the project folder with a ton of extra scripts.

Is there a way to do this without uploading a gem? Specifically, it'd be ideal if once the project is checked out from git the commands work out of the box.

like image 635
agoebel Avatar asked Jun 02 '26 07:06

agoebel


2 Answers

For anyone coming to this in 2016 or later, vagrant now supports:

vagrant YOUR-COMMAND

See "PLUGIN DEVELOPMENT: COMMANDS" for details:

Within the context of a plugin definition . . . Commands are defined with the command method, which takes as an argument the name of the command, in this case "foo." This means the command will be invokable via vagrant foo.

command "foo" do
  require_relative "command"
  Command
end
like image 198
coroin Avatar answered Jun 05 '26 02:06

coroin


I did some digging and discovered this thread. I really like agoebel's solution, but hijacking the Vagrantfile seems a little hacky and still doesn't introduce custom commands. I see this approach is being appropriate for checking plugin dependences, or some additional check before standard commands are run:

REQUIRED_PLUGINS = %w(vagrant-ohai vagrant-vbguest)
restart_required = REQUIRED_PLUGINS.any? do |plugin|
  system "vagrant plugin install #{plugin}" unless Vagrant.has_plugin?(plugin)
end

But you can also create a file in the same directory as your Vargrantfile called .vagrantplugins which a plugin definition like so:

class MyCommand < Vagrant.plugin(2, :command)
  def self.synopsis
    "Says Hello"
  end

  def execute
    puts "Hello"
    0
  end
end

class MyPlugin < Vagrant.plugin(2)
  name "My Plugin"

  command "mycommand" do
    MyCommand
  end
end

Effectively allowing you to write custom commands. Vagrant removed the functionality that allowed definition of custom commands inline in new 2.x.x version of the API.

This is a great compromise. If you vagrant list-commands, you should see:

mycommand       Says Hello

Hope this helps!

like image 34
James Taylor Avatar answered Jun 05 '26 03:06

James Taylor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!