是否可以在使用Vagrant配置计算机时重新启动计算机,并在脚本停止的情况下启动?

时间:2016-01-20 21:31:50

标签: bash vagrant vagrant-provision

我正在阅读bash中的一个教程,他们说要重启机器,没有选择直接重启服务,这是重启机器的问题,然后还有更多的命令仍然需要配置时运行。

那么有没有办法在配置中重新启动一个盒子,然后在你之后离开的地方继续?

4 个答案:

答案 0 :(得分:15)

据我所知,如果尝试重新启动操作系统,则无法使用单个脚本/命令集进行停止,例如:

  config.vm.provision "shell", inline: <<-SHELL
    echo $(date) > ~/rebootexample
    reboot
    echo $(date) >> ~/rebootexample
  SHELL

在此示例中,不会执行第二次回应调用。

您可以拆分脚本/命令并使用vagrant reload等插件。

Vagrantfile的示例片段,以突出显示其可能的用途:

  # execute code before reload
  config.vm.provision "shell", inline: <<-SHELL
     echo $(date) > ~/rebootexample
  SHELL

  # trigger reload
  config.vm.provision :reload

  # execute code after reload
  config.vm.provision "shell", inline: <<-SHELL
     echo $(date) >> ~/rebootexample
  SHELL

答案 1 :(得分:3)

我从来没有这样做过,但如果必须的话,我会将脚本分成两部分,一部分在重新启动之前包含restart命令,然后另一部分安装后。

第一个也会创建一个锁文件。

如果锁定文件不存在,则整个脚本将运行第一个脚本;如果文件存在,则运行第二个脚本。这个整体脚本将被设置为启动。

答案 2 :(得分:1)

您可以采用的一个技巧是发送重启信号并将其余的配置工作保存为要在启动时运行的脚本:

config.vm.provision "shell", inline: <<-SHELL
  echo "Do your thing... DONE"
cat <<-RCLOCAL | sed -s 's_^      __' > /etc/rc.local
      #!/bin/bash
      echo "This will be run once on next boot and then it's destroyed and never run again"
      rm /etc/rc.local
RCLOCAL
  chmod o+x /etc/rc.local
  shutdown -r now #restart
SHELL

这已经过测试,可以在debian 9上运行,所以你可能需要启用服务或找到另一种方法来让你的代码在下次启动时运行,如果你正在运行别的东西。

不幸的是你不能简单地做:

config.vm.provision "shell", inline: "shutdown -r now"
config.vm.provision "shell", inline: "echo 'hello world'"

results in ==>
The SSH connection was unexpectedly closed by the remote end. This
usually indicates that SSH within the guest machine was unable to
properly start up. Please boot the VM in GUI mode to check whether
it is booting properly.

答案 3 :(得分:0)

Vagrant具有用于配置的重启选项,但是,重启来宾功能目前不支持Linux。

您可以在https://github.com/secret104278/vagrant_reboot_linux/tree/master处检查我的插件,我已经实现了Linux重新启动的功能。

相关问题