4

I know how to use vagrant-hostsupdater to add entries into the host's /etc/hosts file that point to the VM, but I'm actually trying to find a dynamic way to go the OTHER direction. On my machine, I have MySQL installed with a large db. I don't want to put this inside the VM, I need the VM to be able to access it.

I can easily set it up manually. After vagrant up, I can ssh into the VM and edit the /etc/hosts there and make an entry like hostmachine.local and point to my IP address at the time. However, as I move from home to work my host machine will change so I constantly have to update that entry.

Is there a way within an .erb file or somehow to make a vagrant up take the IP of the host machine and make such an entry in a VM hosts file?

4

3 回答 3

2

这是一种方法。由于Vagrantfile是 Ruby 脚本,我们可以使用一些逻辑来查找本地主机名和 IP 地址。然后我们在一个简单的配置脚本中使用它们,将它们添加到来宾/etc/hosts文件中。

示例Vargrantfile

# -*- mode: ruby -*-
# vi: set ft=ruby :

# test setting the host IP address into the guest /etc/hosts

# determine host IP address - may need some other magic here
# (ref: http://stackoverflow.com/questions/5029427/ruby-get-local-ip-nix)
require 'socket'
def my_first_private_ipv4
  Socket.ip_address_list.detect{|intf| intf.ipv4_private?}
end
ip = my_first_private_ipv4.ip_address()

# determine host name - may need some other magic here
hostname = `hostname`

script = <<SCRIPT
echo "#{ip} #{hostname}" | tee -a /etc/hosts
SCRIPT

VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
  config.vm.box = "hashicorp/precise64"
  config.vm.hostname = "iptest"
  config.vm.provision :shell, :inline => script
  config.vm.provider "virtualbox" do |vb|
  #   vb.gui = true
     vb.name = "iptest"
     vb.customize ["modifyvm", :id, "--memory", "1000"]
  end
end

注意:如果您提供多次(不破坏 VM),echo | tee -a添加到的命令将继续追加。/etc/hosts如果遇到这种情况,您可能需要一个更好的解决方案。

于 2014-10-09T20:58:49.063 回答
1

另一种可能的解决方案是使用vagrant-hosts 插件。可以像 BrianC 在他的回答中显示的那样找到主机 IP。

流浪文件:

# -*- mode: ruby -*-
# vi: set ft=ruby :

require 'socket'

def my_first_private_ipv4
  Socket.ip_address_list.detect{|intf| intf.ipv4_private?}
end
host_ip = my_first_private_ipv4.ip_address()

Vagrant.configure(2) do |config|
    config.vm.define "web", primary: true do |a|
        a.vm.box = "ubuntu/trusty64"
        a.vm.hostname = "web.local"

        a.vm.provider "virtualbox" do |vb|
          vb.memory = 2048
          vb.cpus = 1
        end

        a.vm.provision :hosts do |provisioner|
            provisioner.add_host host_ip, ['host.machine']
        end
    end
end

Provisioner 将向 VM 的/etc/hosts文件添加一行,将主机的 IP 地址映射到host.machine. 多次运行 Provisioner 不会导致/etc/hosts.

于 2015-11-26T13:45:54.070 回答
0

考虑到我的情况,我实际上找到了一个更简单的解决方案,在 Mac 上运行 VM,并且我的 local.db.yml 文件不是源代码的一部分。实际上,我没有使用名称/IP,而是能够转到 Mac 的系统偏好设置并找到我的计算机的本地网络名称,即 Kris-White-Mac.local

这解决了 VM 内部和外部的问题,因此通过使用该名称而不是 localhost 或 127.0.0.1,即使我的 IP 发生更改,它也可以工作。

于 2014-10-11T15:40:41.293 回答