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.
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
commandmethod, which takes as an argument the name of the command, in this case "foo." This means the command will be invokable viavagrant foo.
command "foo" do
require_relative "command"
Command
end
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With