1

再会!
我想使用 dhcp 增加几个节点。但我也想获取这个节点的 IP 地址并将它们写入文件。Vagrant 文档说“可以通过使用 vagrant ssh SSH 进入机器并使用适当的命令行工具(例如 ifconfig)来查找 IP 地址来确定 IP 地址”。

所以我为master创建了一个简单的bash脚本

`vagrant ssh master -c 'ifconfig | grep -oP "inet addr:\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}" | grep -oP "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}" | tail -n 2 | head -n 1'`

以及其他节点的相同脚本。

我想把这个脚本放到 Vagrantfile 中。我应该使用什么插件?我尝试https://github.com/emyl/vagrant-triggers

config.trigger.after :up do
   ipAddr = `vagrant ssh master -c 'ifconfig | grep -oP "inet addr:\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}" | grep -oP "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}" | tail -n 2 | head -n 1'`
   puts "master ipAddr #{ipAddr}"
   ipAddr = `vagrant ssh slave01 -c 'ifconfig | grep -oP "inet addr:\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}" | grep -oP "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}" | tail -n 2 | head -n 1'`
   puts "slave01 ipAddr #{ipAddr}"
end

但它会在其中一个节点启动时触发,而不是同时启动。

4

1 回答 1

2

我修改了您使用vagrant-triggers插件进行多框设置的方法。这对我有用:

# Vagrantfile
Vagrant.configure(2) do |config|
  config.vm.box = "ubuntu/trusty64"
  config.vm.network :private_network, type: "dhcp"
  config.vm.define "test-web"
  config.vm.define "test-db"
  config.vm.define "test-dual"
  config.trigger.after :up, :stdout => false, :stderr => false do
    get_ip_address = %Q(vagrant ssh #{@machine.name} -c 'ifconfig | grep -oP "inet addr:\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}" | grep -oP "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}" | tail -n 2 | head -n 1')
    @logger.debug "Running `#{get_ip_address}`"
    output = `#{get_ip_address}`
    @logger.debug "Output received:\n----\n#{output}\n----"
    puts "==> #{@machine.name}: Available on DHCP IP address #{output.strip}"
    @logger.debug "Finished running :after trigger"
  end  
end

# Console:
$ vagrant up test-web
Bringing machine 'test-web' up with 'virtualbox' provider...
==> test-web: Checking if box 'ubuntu/trusty64' is up to date...
==> test-web: Resuming suspended VM...
==> test-web: Booting VM...
==> test-web: Waiting for machine to boot. This may take a few minutes...
    test-web: SSH address: 127.0.0.1:2222
    test-web: SSH username: vagrant
    test-web: SSH auth method: private key
    test-web: Warning: Connection refused. Retrying...
==> test-web: Machine booted and ready!
==> test-web: Running triggers after up...
Connection to 127.0.0.1 closed.
==> test-web: Available on DHCP IP address 172.28.128.3
于 2015-03-03T15:24:36.583 回答