使用Vagrant配置机器时,是否可以重新启动机器并从脚本离开的地方继续执行?

25

我正在阅读一个关于Bash的教程,其中说要重启机器,没有直接重启服务的选项,重启机器后还需要运行更多的命令进行配置。那么在云服务部署过程中是否有办法重启服务器并在之后继续完成配置呢?


1
你使用哪种供应服务? - dizballanze
vagrant vbguest插件可以实现这一点,所以应该是可行的。虽然我从未深入了解过它们的实现方式,但它是一个插件,因此可能会有所不同,但您可能会得到一些好的想法。 - Frederic Henri
@dizballanze 目前在 Bash 中... - leeand00
5个回答

30
据我所知,如果尝试重新启动操作系统,你无法拥有一个可以继续上次工作的单个脚本/命令集,例如:

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

在这个例子中,第二个echo调用不会被执行。
您可以将脚本/命令拆分并使用插件,例如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

官方的Vagrant shell provisioner现在本地就有了这个功能。取决于客户端是否实现了重启能力,但在我的测试中,我使用的Linux客户端都可以正常工作。要使用此功能,请将您的shell provisioning分成两个单独的shell脚本。然后在它们之间添加此行:config.vm.provision 'shell', reboot: true。然后您将会在 vagrant up 的安装输出中看到 ==> proxmox: Waiting for machine to reboot...。问题解决了。如果可能的话,应该通过编辑将此内容添加到答案中。但编辑队列已经满了。 - Utkonos
这是该功能的文档:https://developer.hashicorp.com/vagrant/docs/provisioning/shell#reboot - Utkonos
你需要执行vagrant plugin install vagrant-reload来执行#trigger reload步骤。 - Joshit

3
我从未这样做过,但如果我必须这样做,我会将脚本分成两部分,一部分在重启之前包括重启命令,然后另一部分是安装后的脚本。
第一部分还会创建一个锁定文件。
总体脚本将在锁定文件不存在时运行第一个脚本,或者在文件存在时运行第二个脚本。这个总体脚本将被设置为启动项。

你能否给一个基本的例子来展示这个东西会是什么样子? - user5359531

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.

1

0

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