Vagrant dhcp:获取IP地址

时间:2014-04-23 08:58:49

标签: vagrant vagrantfile

美好的一天!
我想使用dhcp增加几个节点。但我也希望得到这个节点的ip-addresses并将它们写入文件。 Vagrant docs说:“可以通过使用vagrant ssh将SSH连接到机器并使用适当的命令行工具查找IP来确定IP地址,例如ifconfig”。

所以我为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

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

1 个答案:

答案 0 :(得分: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