有没有像“预先vagrant up”这样的钩子?

17

我正在尝试使用vagrant自动化我的开发环境。我需要与其他开发者共享vagrant设置,因此在正常的vagrant up过程开始之前,我们需要确保满足一些边界条件。

vagrant中是否有任何钩子(例如git中的预提交或其他预*脚本)?提供脚本太晚了。

我的当前设置如下:

Vagrantfile
vagrant-templates/
vagrant-templates/apache.conf
vagrant-templates/...
sub-project1/
sub-project2/

我需要确保子项目{1..n}存在,如果不存在,应该显示错误消息。

我更喜欢类似于Bash的解决方案,但我对其他解决方案持开放态度。


我写了一个shell脚本来引导vagrant项目。你可以在这里查看它: https://github.com/marcovanest/strappy也许这是你问题的解决方案,否则你可以扫描代码寻找答案。 - cocheese
@cocheese 谢谢。你的脚本在 vagrant 之外。这没关系,但我正在寻找一个内部脚本。如果没有,我会仔细研究那个解决方案。 - Nepomuk Pajonk
5个回答

25

你可以尝试使用我编写的这个Vagrant插件:

https://github.com/emyl/vagrant-triggers

安装完成后,你可以在Vagrantfile文件中添加如下内容:

config.trigger.before :up, :execute => "..."

1
这个答案应该被接受为正确的。我已经很长时间在寻找这样的插件了。谢谢@Emyl! - warantesbr
谢谢,这正是我在寻找的。 - Justin
可以确认,非常性感。 - dave

11

一种选择是将逻辑直接放入Vagrantfile中,然后在项目中的所有vagrant命令上执行。例如,像这样:

def ensure_sub_project(name)
  if !File.exists?(File.expand_path("../#{name}", __FILE__))
    # you could raise or do other ruby magic, or shell out (for a bash script)
    system('clone-the-project.sh', name)
  end
end

ensure_sub_project('some-project')
ensure_sub_project('other-project')

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

6

您可以编写自己的Vagrant插件,并在机器启动时使用action_hook,类似于以下内容:

require 'vagrant-YOURPLUGINNAME/YOURACTIONCLASS'

module VagrantPlugins
  module YOURPLUGINNAME
    class Plugin < Vagrant.plugin('2')
      name 'YOURPLUGINNAME'
      description <<-DESC
          Some description of your plugin
      DESC

      config(:YOURPLUGINNAME) do
        require_relative 'config'
        Config
      end

      action_hook(:YOURPLUGINNAME, :machine_action_up) do |hook|
        hook.prepend(YOURACTIONCLASS.METHOD)
      end
    end
  end
end

4

还有一个要看的插件是vagrant-host-shell,它只在提供盒子时运行。只需在Vagrantfile中在其他provisoner之前添加它:

config.vm.provision :host_shell do |shell|
  shell.inline = './clone-projects.sh'
  shell.abort_on_nonzero = true
end

2

除了tmatilai的回答,你还可以添加以下内容:

case ARGV[0]
when "provision", "up"
  system "./prepare.sh"
else
  # do nothing
end

将以下内容添加到你的Vagrantfile中,以便仅在特定命令上运行它。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接