使用" vagrant up"启动流浪汉机器后打印消息

时间:2015-06-13 16:28:55

标签: vagrant vagrantfile

我需要在完成vagrant up命令时显示一条消息。

我尝试过定义一个函数:

def hello
    puts 'hello'
end

然后调用它和文件的结尾:

hello 

但它总是打印在输出的开头而不是结尾。我怎样才能在最后打印一条消息?

6 个答案:

答案 0 :(得分:24)

Vagrant现在内置支持在vagrant up之后显示的消息。只需将其添加到Vagrantfile

即可
config.vm.post_up_message = "This is the start up message!"

然后在您的VM出现后,您将看到绿色的此消息:

==> default: Machine 'default' has a post `vagrant up` message. This is a message
==> default: from the creator of the Vagrantfile, and not from Vagrant itself:
==> default:
==> default:     This is the start up message!

答案 1 :(得分:15)

您还可以使用config.vm.post_up_message的HEREDOC样式变量,如下所示:

$msg = <<MSG
------------------------------------------------------
Local Websphere, accessible at 127.0.0.1

URLS:
 - app under test  - http://localhost:8080/<app url>/
 - ibm console     - http://localhost:9060/ibm/console

------------------------------------------------------
MSG

...
...

Vagrant.configure("2") do |config|
  config.vm.post_up_message = $msg
end

这将产生如下输出:

==> default: Machine 'default' has a post `vagrant up` message. This is a message
==> default: from the creator of the Vagrantfile, and not from Vagrant itself:
==> default:
==> default: ------------------------------------------------------
==> default: Local Websphere, accessible at 127.0.0.1
==> default:
==> default: URLS:
==> default:  - app under test  - http://localhost:8080/<app url>/
==> default:  - ibm console     - http://localhost:9060/ibm/console
==> default:
==> default: ------------------------------------------------------

答案 2 :(得分:9)

Vagrant最后不需要插件来显示消息,只需在所有其他配置程序之后添加一个shell配置程序,并根据需要进行回显。

config.vm.provision "ansible" do |ansible|
  # ... or other existing provisioners

config.vm.provision "shell", privileged: false, inline: <<-EOF
  echo "Vagrant Box provisioned!"
  echo "Local server address is http://#{$hostname}"
EOF

有了这个,vagrant up应该以这样的结尾:

==> default: Running provisioner: shell...
    default: Running: inline script
==> default: Vagrant Box provisioned!
==> default: Local server address is http://vagrant.dev

有必要添加privileged: false(如Vagrant Issue 1673中所述)来抑制Ubuntu的stdin: is not a tty错误。

答案 3 :(得分:6)

一旦我开始学习Ruby,我就找到了理想的解决方案:)

BEGIN 声明在程序运行之前调用的代码。

#!/usr/bin/ruby
puts "This is main Ruby Program"
BEGIN {
    puts "Initializing Ruby Program"
}

它会产生这个:

Initializing Ruby Program
This is main Ruby Program

它在Vagrantfile中完美运行。

答案 4 :(得分:5)

试试vagrant-triggers plugin

$ vagrant plugin install vagrant-triggers

然后添加:

config.trigger.after :up do
  puts 'hello'
end

Vagrantfile

答案 5 :(得分:1)

来自@slm的heredoc解决方案非常可爱,但你也可以将heredoc 放在 Ruby中:

config.vm.post_up_message = <<-HEREDOC
  This is line 1
  This is line 2
  THis is line 3
HEREDOC

实际上有一些略有不同的Ruby heredoc样式:https://infinum.co/the-capsized-eight/multiline-strings-ruby-2-3-0-the-squiggly-heredoc