[Vagrant & VirtualBox] Vagrant: vagrant-hostsupdater で /etc/hosts を書き換える

vagrant-hostsupdater を利用すると、vagrant 実行時に /etc/hosts を書き換えてくれます。

[markdown]
> * [cogitatio/vagrant-hostsupdater](https://github.com/cogitatio/vagrant-hostsupdater)

## インストール

“`prettyprinted
% vagrant plugin install vagrant-hostsupdater
“`

## つかいかた

Vagrantfile に設定を加えます。

“`ruby:Vagrantfile
#
# Vagrant::Hostsupdater
#
config.vm.network :private_network, ip: “192.168.33.10”
config.vm.hostname = “www.yahoo.com”
config.hostsupdater.aliases = [“www.yahoo.co.jp”, “www.sample.com”]
“`

いつもどりに `vagrant up`

“`prettyprinted
% vagrant up
Bringing machine ‘default’ up with ‘virtualbox’ provider…
:
==> default: Checking for host entries
==> default: adding to (/etc/hosts) : 192.168.33.10 www.yahoo.com # VAGRANT: 357923c65f4312d443b6ee87f1885dbd (default) / f5f95a0d-a022-4d77-9239-9137fd229574
==> default: adding to (/etc/hosts) : 192.168.33.10 www.yahoo.co.jp # VAGRANT: 357923c65f4312d443b6ee87f1885dbd (default) / f5f95a0d-a022-4d77-9239-9137fd229574
==> default: adding to (/etc/hosts) : 192.168.33.10 www.sample.com # VAGRANT: 357923c65f4312d443b6ee87f1885dbd (default) / f5f95a0d-a022-4d77-9239-9137fd229574
Password:
==> default: Setting hostname…
:
“`

/etc/hosts を確認してみる。

“`:/etc/hosts
##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting. Do not change this entry.
##
127.0.0.1 localhost
255.255.255.255 broadcasthost
::1 localhost
fe80::1%lo0 localhost
192.168.33.10 www.yahoo.com # VAGRANT: 357923c65f4312d443b6ee87f1885dbd (default) / f5f95a0d-a022-4d77-9239-9137fd229574
192.168.33.10 www.yahoo.co.jp # VAGRANT: 357923c65f4312d443b6ee87f1885dbd (default) / f5f95a0d-a022-4d77-9239-9137fd229574
192.168.33.10 www.sample.com # VAGRANT: 357923c65f4312d443b6ee87f1885dbd (default) / f5f95a0d-a022-4d77-9239-9137fd229574
“`

/etc/hosts を使ってドメインの名前解決をしてくれるので、この例では某ポータルサイトの URI をたたくと仮想マシンのドキュメントルートが表示されるようになります。

> * [ITmedia エンタープライズ : Linux Tips「システム設定ファイルを知ろう~/etc/hosts~」](http://www.itmedia.co.jp/help/tips/linux/l0351.html)

`vagrant halt` で終了すると、/etc/hosts も元に戻りました。

“`:/etc/hosts
##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting. Do not change this entry.
##
127.0.0.1 localhost
255.255.255.255 broadcasthost
::1 localhost
fe80::1%lo0 localhost
“`

## 補遺

> * [VagrantでゲストOSを起動した際に、ホストOSのhostsファイルにゲストOSのホスト名・IPを追加・削除してくれるVagrantプラグイン「Vagrant::Hostsupdater」 | misty-magic.h](http://mistymagich.wordpress.com/2013/09/02/vagrant%E3%81%A7%E3%82%B2%E3%82%B9%E3%83%88os%E3%82%92%E8%B5%B7%E5%8B%95%E3%81%97%E3%81%9F%E9%9A%9B%E3%81%AB%E3%80%81%E3%83%9B%E3%82%B9%E3%83%88os%E3%81%AEhosts%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB/)
> * [Vagrantのプラグイン、何入れてたっけ…。 – Qiita](http://qiita.com/akiko-pusu/items/9b45b6b70878669e2e11)
[/markdown]