我想在虚拟机暂停或关闭之前触发操作。
我看到了可以使用的操作挂钩,但它们都是在操作完成后https://www.vagrantup.com/docs/plugins/action-hooks.html。有什么线索吗?
我想在虚拟机暂停或关闭之前触发操作。
我看到了可以使用的操作挂钩,但它们都是在操作完成后https://www.vagrantup.com/docs/plugins/action-hooks.html。有什么线索吗?
Vagrant.configure("2") do |config|
# Your existing Vagrant configuration
...
# run some script before the guest is halted
config.trigger.before :halt do
info "Dumping the database before destroying the VM..."
run_remote "bash /vagrant/cleanup.sh"
end
# run some script before the guest is suspended
config.trigger.before :suspend do
info "Dumping the database before destroying the VM..."
run_remote "bash /vagrant/cleanup.sh"
end
# clean up files on the host after the guest is destroyed
config.trigger.after :destroy do
run "rm -Rf tmp/*"
end
# start apache on the guest after the guest starts
config.trigger.after :up do
run_remote "service apache2 start"
end
end
我认为您也可以尝试在客户机上使用udev事件。当第一次执行vagrant up
(或稍后执行vagrant provision
)时,可以通过配置来完成此操作。例如,我正在使用代码在nfs挂载目录后重新启动php5-fpm。
如果您的操作系统支持systemd,我认为您也可以在客户机上使用systemd。
https://github.com/lqbweb/vagrant_hook
这是一个基本且简单的 Vagrant 插件,它演示了如何附加到特定的 Vagrant 链式操作。
我不知道如何在插件中使用config.trigger
而不是Vagrantfile。
然而,我发现docs完全错误,"after"是不正确的!
实际上,你只需要使用prepend
:
require_relative "action"
action_hook(:goodhosts, :machine_action_halt) do |hook|
hook.prepend(Action)
end
以下是整合版触发器的工作原理:
注意:钩子/中间件是嵌套的,而不是顺序执行的。prepend
,即在调用下一个中间件之前和之后都有操作。def call(env)
before
@app.call(env)
after
虽然触发器的集成版本使用prepend
表示“之前”,使用append
表示“之后”,并采用“线性中间件”,即仅在调用下一个中间件之前执行操作,就好像钩子是顺序执行的。
def call(env)
operation
@app.call(env)
由于提供者的 halt
和 suspend
操作也是中间件(例如可以以 hyperv 为例),因此前置钩子肯定可以在停止或暂停操作生效之前进行操作。