zowのプログラムな日々

日々のプログラミングとか

Mac(Yosemite)でVagrant環境を構築する

rbenvやpyenvなどで言語バージョンを変更することは出来ても、その他の環境(DB等)が変えられないと意味無いので開発環境として仮想環境を構築する。

仮想環境と言えば昔はVMwareVirtualBox等で作っていたけども、開発環境としてもっとお手軽に利用できるVagrantを導入する

VirtualBoxのインストール

以下からOSX用バイナリをDLしてインストールする。

https://www.virtualbox.org/wiki/Downloads

今回は4.3.20をインストールした。インストール方法は迷うところが無いので割愛。

起動するとこんな感じ。

f:id:zow3:20150115221836p:plain

Vagrantのインストール

以下からOSX用バイナリをDLしてインストールする。

https://www.vagrantup.com/downloads.html

これも迷うところが無いのでインストール方法は割愛。

インストールされたバージョンは1.7.2

$ vagrant -v
Vagrant 1.7.2
$

Boxの追加

インストール自体は上記だけ。

あとは仮想環境のベースとなるOS部分を用意する。

仕事で使うのであれば自分で作るべきだと思うけど、仕事じゃないし、既に用意されている物がたくさんあるのでそれを活用する。

以下でBoxを探す

http://www.vagrantbox.es/

今回はUbuntu14.04LTS Serverのイメージを使う。「Ubuntu 14.04 (based on amd64 server iso file) 」というのがあるので、それを利用する。

以下コマンドでBoxを追加する。

vagrant box add Box名(任意の名前) 取得元URL

実際に実行したのが以下。イメージをDLしてるので結構時間がかかる。

$ vagrant box add ubuntu-14.04-server https://github.com/kraksoft/vagrant-box-ubuntu/releases/download/14.04/ubuntu-14.04-amd64.box
==> box: Adding box 'ubuntu-14.04-server' (v0) for provider: 
    box: Downloading: https://github.com/kraksoft/vagrant-box-ubuntu/releases/download/14.04/ubuntu-14.04-amd64.box
==> box: Successfully added box 'ubuntu-14.04-server' (v0) for 'virtualbox'!
$ 

DLが終わったらBoxが追加されているのを確認する。

$ vagrant box list
ubuntu-14.04-server (virtualbox, 0)
$

仮想環境を作る

DLしたイメージを元に仮想環境を作成する。

まず、作業場所のディレクトリを作成する

$ mkdir -p ~/dev/vagrant/ubuntu-14.04-server

作成したディレクトリで「vagrant init」する。

コマンドは以下の形。

vagrant init Box名

$ cd ~/dev/vagrant/ubuntu-14.04-server
$ vagrant init ubuntu-14.04-server
A `Vagrantfile` has been placed in this directory. You are now
ready to `vagrant up` your first virtual environment! Please read
the comments in the Vagrantfile as well as documentation on
`vagrantup.com` for more information on using Vagrant.
$ ls -l
total 8
-rw-r--r--  1 zow  staff  3031  1 15 22:57 Vagrantfile
$

vagrant init」が成功すると、ディレクトリ内に「Vagrantfile」が出来上がる。

このファイルはrubyで書かれていて、ここで各種設定をすることでカスタマイズ出来る。

だが、弄るのは置いといて、まずは作成した仮想環境を立ち上げてみる。

$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'ubuntu-14.04-server'...
==> default: Matching MAC address for NAT networking...
==> default: Setting the name of the VM: ubuntu-1404-server_default_1421330751978_99630
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
==> default: Forwarding ports...
    default: 22 => 2222 (adapter 1)
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2222
    default: SSH username: vagrant
    default: SSH auth method: private key
    default: Warning: Connection timeout. Retrying...
    default: 
    default: Vagrant insecure key detected. Vagrant will automatically replace
    default: this with a newly generated keypair for better security.
    default: 
    default: Inserting generated public key within guest...
    default: Removing insecure key from the guest if its present...
    default: Key inserted! Disconnecting and reconnecting using new SSH key...
==> default: Machine booted and ready!
==> default: Checking for guest additions in VM...
    default: No guest additions were detected on the base box for this VM! Guest
    default: additions are required for forwarded ports, shared folders, host only
    default: networking, and more. If SSH fails on this machine, please install
    default: the guest additions and repackage the box to continue.
    default: 
    default: This is not an error message; everything may continue to work properly,
    default: in which case you may ignore this message.
==> default: Mounting shared folders...
    default: /vagrant => /Users/zow/dev/vagrant/ubuntu-14.04-server
Failed to mount folders in Linux guest. This is usually because
the "vboxsf" file system is not available. Please verify that
the guest additions are properly installed in the guest and
can work properly. The command attempted was:

mount -t vboxsf -o uid=`id -u vagrant`,gid=`getent group vagrant | cut -d: -f3` vagrant /vagrant
mount -t vboxsf -o uid=`id -u vagrant`,gid=`id -g vagrant` vagrant /vagrant

The error output from the last command was:

stdin: is not a tty
mount: unknown filesystem type 'vboxsf'
$

※エラーが出ているがこれは後で解説。

起動するとVirtualBoxの画面にそれが反映される。

f:id:zow3:20150115230700p:plain

ステータスを見るとこんな感じ

$ vagrant status
Current machine states:

default                   running (virtualbox)

The VM is running. To stop this VM, you can run `vagrant halt` to
shut it down forcefully, or you can run `vagrant suspend` to simply
suspend the virtual machine. In either case, to restart it again,
simply run `vagrant up`.
$

起動していればコンソールに接続することが出来る。

以下コマンドで仮想環境に接続する。

$ vagrant ssh
Welcome to Ubuntu 14.04 LTS (GNU/Linux 3.13.0-24-generic x86_64)

 * Documentation:  https://help.ubuntu.com/
Last login: Thu Jan 15 14:22:42 2015 from 10.0.2.2
vagrant@vagrant-ubuntu-trusty:~$ 

これで仮想環境内に開発環境等をお好みで作成することができる。

※エラーについて

とりあえず起動はしている。だがエラーが出ている。

内容はHost側とGuest側の共有ディレクトリがマウントできないというエラー。

これはイメージを作った人次第ではあるんだけど、作った人がうまく設定していないとこんな事も起きる。

自分でイメージを作る人の為にもこの部分についてちょっと解説しておきたいと思う。

落としたイメージがちゃんと設定されていてマウントもされてる人は読み飛ばして構わない。

Vagrantの共有ディレクトリのマウントが失敗する場合

エラーメッセージでググるといろいろ出てくる。

vagrantでmountエラーの解決方法 - Qiita

上記のやり方で解決出来る人はそのまま実行すれば良い。

だが、今回のイメージの場合は解決出来ない。

vagrant@vagrant-ubuntu-trusty:~$ ls  /etc/init.d/
apparmor           grub-common  ondemand  README      sendsigs  umountfs
console-setup      halt         pppd-dns  reboot      single    umountnfs.sh
cron               irqbalance   procps    resolvconf  skeleton  umountroot
dbus               killprocs    rc        rpcbind     ssh       urandom
dns-clean          kmod         rc.local  rsync       sudo
friendly-recovery  networking   rcS       rsyslog     udev
vagrant@vagrant-ubuntu-trusty:~$ 

そもそも共有ディレクトリを使うために必要な「vboxadd」が存在しない。

この場合どうすれば良いのかについて説明する。

この「vboxadd」なんだけれども、VirtualBoxで提供されているサービスで、イメージを作った際、ゲストOS側にインストールしておく必要がある。

これがインストールされてない場合は、以下サイトからバージョンに合わせて個別でDLしてインストールしてやればいい

http://download.virtualbox.org/virtualbox/

今回は4.3.20をインストールしているので4.3.20からDLするが、恐らくバージョン依存は無いはずなので、他のバージョンの物を使っても大丈夫だと思う。

DLするのは「VBoxGuestAdditions_4.3.20.iso」だが、ローカルで落としても共有ディレクトリが無いので、ゲストOSからwget で落としてやる

vagrant@vagrant-ubuntu-trusty:~$ cd /tmp
vagrant@vagrant-ubuntu-trusty:/tmp$ wget http://download.virtualbox.org/virtualbox/4.3.20/VBoxGuestAdditions_4.3.20.iso
vagrant@vagrant-ubuntu-trusty:/tmp$ ls -l
total 56976
-rw-rw-r-- 1 vagrant vagrant 58343424 Nov 21 14:01 VBoxGuestAdditions_4.3.20.iso
vagrant@vagrant-ubuntu-trusty:/tmp$ 

ダウンロードしたイメージをマウントする

vagrant@vagrant-ubuntu-trusty:/tmp$ sudo mount -t iso9660 /tmp/VBoxGuestAdditions_4.3.20.iso /mnt
mount: block device /tmp/VBoxGuestAdditions_4.3.20.iso is write-protected, mounting read-only
vagrant@vagrant-ubuntu-trusty:/tmp$

/mntにマウントされたので、そこにある「VBoxLinuxAdditions.run」を実行してやる

vagrant@vagrant-ubuntu-trusty:/tmp$ cd /mnt/
vagrant@vagrant-ubuntu-trusty:/mnt$ ll
total 50814
dr-xr-xr-x  6 root root     2048 Nov 21 14:01 ./
drwxr-xr-x 23 root root     4096 Jan 15 14:06 ../
dr-xr-xr-x  2 root root     2048 Nov 21 14:01 32Bit/
dr-xr-xr-x  2 root root     2048 Nov 21 14:01 64Bit/
-r-xr-xr-x  1 root root      647 Sep 12 12:10 AUTORUN.INF*
-r-xr-xr-x  1 root root     6966 Nov 21 14:57 autorun.sh*
dr-xr-xr-x  2 root root     2048 Nov 21 14:01 cert/
dr-xr-xr-x  2 root root     2048 Nov 21 14:01 OS2/
-r-xr-xr-x  1 root root     5523 Nov 21 14:57 runasroot.sh*
-r-xr-xr-x  1 root root  7146957 Nov 21 14:58 VBoxLinuxAdditions.run*
-r-xr-xr-x  1 root root 16434176 Nov 21 14:59 VBoxSolarisAdditions.pkg*
-r-xr-xr-x  1 root root 17356976 Nov 21 15:00 VBoxWindowsAdditions-amd64.exe*
-r-xr-xr-x  1 root root   312384 Nov 21 14:56 VBoxWindowsAdditions.exe*
-r-xr-xr-x  1 root root 10754048 Nov 21 14:57 VBoxWindowsAdditions-x86.exe*
vagrant@vagrant-ubuntu-trusty:/mnt$ sudo ./VBoxLinuxAdditions.run 
Verifying archive integrity... All good.
Uncompressing VirtualBox 4.3.20 Guest Additions for Linux............
VirtualBox Guest Additions installer
Copying additional installer modules ...
Installing additional modules ...
Removing existing VirtualBox non-DKMS kernel modules ...done.
Building the VirtualBox Guest Additions kernel modules
The headers for the current running kernel were not found. If the following
module compilation fails then this could be the reason.

Building the main Guest Additions module ...done.
Building the shared folder support module ...done.
Building the OpenGL support module ...done.
Doing non-kernel setup of the Guest Additions ...done.
Starting the VirtualBox Guest Additions ...done.
Installing the Window System drivers
Could not find the X.Org or XFree86 Window System, skipping.
vagrant@vagrant-ubuntu-trusty:/mnt$ 

ビルドが終わると「vboxadd」が追加されている

vagrant@vagrant-ubuntu-trusty:/mnt$ ls /etc/init.d/
apparmor           irqbalance  rc.local    sendsigs      umountroot
console-setup      killprocs   rcS         single        urandom
cron               kmod        README      skeleton      vboxadd
dbus               networking  reboot      ssh           vboxadd-service
dns-clean          ondemand    resolvconf  sudo          vboxadd-x11
friendly-recovery  pppd-dns    rpcbind     udev
grub-common        procps      rsync       umountfs
halt               rc          rsyslog     umountnfs.sh
vagrant@vagrant-ubuntu-trusty:/mnt$ 

あとはマウントしたisoイメージをアンマウントしてからリブート

vagrant@vagrant-ubuntu-trusty:/$ sudo umount /mnt 
vagrant@vagrant-ubuntu-trusty:/$ df
Filesystem     1K-blocks    Used Available Use% Mounted on
/dev/sda1       40636768 1276360  37273140   4% /
none                   4       0         4   0% /sys/fs/cgroup
udev              240116       4    240112   1% /dev
tmpfs              50184     344     49840   1% /run
none                5120       0      5120   0% /run/lock
none              250916       0    250916   0% /run/shm
none              102400       0    102400   0% /run/user
vagrant@vagrant-ubuntu-trusty:/$ sync;sync;sync;sudo reboot

ゲストOS側は以上。

あとはホスト側でゲストOSを再起動してやる

$ vagrant halt
==> default: Attempting graceful shutdown of VM...
$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Clearing any previously set forwarded ports...
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
==> default: Forwarding ports...
    default: 22 => 2222 (adapter 1)
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2222
    default: SSH username: vagrant
    default: SSH auth method: private key
    default: Warning: Connection timeout. Retrying...
==> default: Machine booted and ready!
==> default: Checking for guest additions in VM...
==> default: Mounting shared folders...
    default: /vagrant => /Users/zow/dev/vagrant/ubuntu-14.04-server
$

正常に起動したら共有ディレクトリが正常に使えるかを確認する。

ホスト側の共有ディレクトリは「Vagrantfile」が置かれているディレクトリになる。

ゲスト側の共有ディレクトリは「/vagrant」になる。

ホスト側で任意のファイルを作成する。

$ ls -l
total 8
-rw-r--r--  1 zow  staff  3031  1 15 22:57 Vagrantfile
$ touch aaa.txt
$ ls
Vagrantfile aaa.txt
$ 

次にゲスト側で作成したファイルを確認する。

$ vagrant ssh
Welcome to Ubuntu 14.04 LTS (GNU/Linux 3.13.0-24-generic x86_64)

 * Documentation:  https://help.ubuntu.com/
Last login: Thu Jan 15 15:12:56 2015 from 10.0.2.2
vagrant@vagrant-ubuntu-trusty:~$ ls -l /vagrant/
total 4
-rw-r--r-- 1 vagrant vagrant    0 Jan 15 15:12 aaa.txt
-rw-r--r-- 1 vagrant vagrant 3031 Jan 15 13:57 Vagrantfile
vagrant@vagrant-ubuntu-trusty:~$ 

作成したファイルがこちらでも参照できるのが確認できた。

修正したゲストOSをBoxにする

せっかく直したので、これをBoxとして利用する。

ホストOS側で以下を実行

$ vagrant package
==> default: Attempting graceful shutdown of VM...
==> default: Clearing any previously set forwarded ports...
==> default: Exporting VM...
==> default: Compressing package to: /Users/zow/dev/vagrant/ubuntu-14.04-server/package.box
$ ls 
Vagrantfile aaa.txt     package.box
$

パッケージが出来た。これをbox addしてやればboxとして使えるようになる。

$ vagrant box add ubuntu-14.04-server-rebuild package.box 
==> box: Adding box 'ubuntu-14.04-server-rebuild' (v0) for provider: 
    box: Downloading: file:///Users/zow/dev/vagrant/ubuntu-14.04-server/package.box
==> box: Successfully added box 'ubuntu-14.04-server-rebuild' (v0) for 'virtualbox'!
$ vagrant box list
ubuntu-14.04-server         (virtualbox, 0)
ubuntu-14.04-server-rebuild (virtualbox, 0)
$

あとはこの「ubuntu-14.04-server-rebuild」を使えば共有ディレクトリ設定を毎回やる必要はなくなる。