Vagrant

2014/11/09更新

対応バージョン: 1.4.3

仮想マシン作成時に以下のメッセージが出て共有ディレクトリのマウントに失敗する。

% vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
[default] Importing base box 'centos70_64'...
[default] Matching MAC address for NAT networking...
[default] Setting the name of the VM...
[default] Clearing any previously set forwarded ports...
[default] Clearing any previously set network interfaces...
[default] Preparing network interfaces based on configuration...
[default] Forwarding ports...
[default] -- 22 => 2222 (adapter 1)
[default] Booting VM...
[default] Waiting for machine to boot. This may take a few minutes...
[default] Machine booted and ready!
[default] Mounting shared folders...
[default] -- /vagrant
Failed to mount folders in Linux guest. This is usually beacuse
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

これはVirtualBox Guest Additionsのカーネルモジュールが正しくビルドされていないのが原因なので以下のように同モジュールをビルドし直して仮想マシンを再起動すればよい。

% vagrant ssh -c "sudo /etc/init.d/vboxadd setup"
Removing existing VirtualBox non-DKMS kernel modules     [  OK  ]
Building the VirtualBox Guest Additions kernel modules
Building the main Guest Additions module                 [  OK  ]
Building the shared folder support module                [  OK  ]
Building the OpenGL support module                       [  OK  ]
Doing non-kernel setup of the Guest Additions            [  OK  ]
Starting the VirtualBox Guest Additions                  [  OK  ]
Connection to 127.0.0.1 closed.

% vagrant reload

% vagrant ssh -c "LANG=C df -h /vagrant"
Filesystem      Size  Used Avail Use% Mounted on
none            455G  103G  353G  23% /vagrant

2010/10/11更新

対応バージョン: 1.4.3

Vagrantでローカルネットワーク内のホストと通信可能なブリッジネットワークを作成するにはVagrantfileに以下のように記述する。

:
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|

  config.vm.box = "centos65_64"

  config.vm.network :public_network, ip: "192.168.0.100", bridge: "eth0"
:

bridgeパラメータで接続するインタフェースを指定しておかないとvagrant up時に毎回どのインタフェースに接続するか聞かれるのでここで指定しておくとよい。

bridge名を確認するにはVBoxManageのコマンドを利用する。

% VBoxManage list bridgedifs | grep ^Name:
Name:            eth0
Name:            eth1

関連資料・記事

2010/10/15更新

対応バージョン: 1.4.3

vagrant destroyコマンドにて仮想マシンを削除しようとすると以下のようなメッセージを出して失敗する。

% vagrant destroy s2
Are you sure you want to destroy the 's2' VM? [y/N] y
[s2] Destroying VM and associated drives...

There was an error while executing `VBoxManage`, a CLI used by Vagrant
for controlling VirtualBox. The command and stderr is shown below.

Command: ["unregistervm", "6080f160-8732-4316-b18b-e2e2a96c9afc", "--delete"]

Stderr: VBoxManage: error: Cannot unregister the machine 'ha_s2_1413207998391_70783' while it is locked
VBoxManage: error: Details: code VBOX_E_INVALID_OBJECT_STATE (0x80bb0007), component Machine, interface IMachine, callee nsISupports
VBoxManage: error: Context: "Unregister(CleanupMode_DetachAllReturnHardDisksOnly, ComSafeArrayAsOutParam(aMedia))" at line 158 of file VBoxManageMisc.cpp

このような場合、ホストOS上でVBoxHeadlessをkillしてから改めてvagrant destroyを実行すればよい。

% VBoxManage list vms
:
"ha_s2_1413207998391_70783" {6080f160-8732-4316-b18b-e2e2a96c9afc}

% ps -ef | grep -i vboxheadless | grep ha_s2_1413207998391_70783
foo 16694 13380  4 22:46 ?        00:01:09 /usr/lib/virtualbox/VBoxHeadless --comment ha_s2_1413207998391_70783 --startvm 6080f160-8732-4316-b18b-e2e2a96c9afc --vrde config

% kill 16694

% vagrant destroy s2
Are you sure you want to destroy the 's2' VM? [y/N] y
[s2] Forcing shutdown of VM...
[s2] Destroying VM and associated drives...
[s2] Running cleanup tasks for 'shell' provisioner...

2019/04/28更新

対応バージョン: 2.2.4

Vagrantを導入し、VirtualBox環境で仮想マシンを動作させる手順を示す。

ホストOSはmacOS 10.14.4(Mojave)とする。

公式サイト

インストール

Vagrantインストール

以下からmacOS用のバイナリをダウンロード
「vagrant_2.2.4_x86_64.dmg」をダブルクリック
「Vagrant.pkg」をダブルクリックして [続ける] > [インストール] > パスワードを入力して[ソフトウェアをインストール]
% vagrant -v
Vagrant 2.2.4
Guest Additionsのバージョンが正しくない時に自動でアップデートしてくれるためのプラグイン「vagrant-vbguest」をインストール
% vagrant plugin install vagrant-vbguest
Installing the 'vagrant-vbguest' plugin. This can take a few minutes...
Fetching: micromachine-2.0.0.gem (100%)
Fetching: vagrant-vbguest-0.17.2.gem (100%)
Installed the plugin 'vagrant-vbguest (0.17.2)'!

VirtualBoxインストール

以下からmacOS用のバイナリをダウンロード
「VirtualBox-x.x.x-xxxxxx-OSX.dmg」をダブルクリック
「VirtualBox.pkg」をダブルクリックして [続ける] > [続ける] > [インストール] > パスワードを入力して[ソフトウェアをインストール]
VirtualBoxを起動して「Extension Packが古いのでインストールするか」と表示されたら指示に従ってExtension Packをダウンロードしてインストール

BOX取得

次に仮想マシンのテンプレートとなるBOXを取得する。

以下のサイトでいろいろなBOXが配布されているが、ここではCentOS 7.2(64bit)を導入する。

BOXの取得はvagrant box addコマンドを使い、引数として任意の仮想マシン名と取得元ファイルを指定する。

% vagrant box add centos72_64 https://github.com/CommanderK5/packer-centos-template/releases/download/0.7.2/vagrant-centos-7.2.box

% vagrant box list
centos72_64 (virtualbox, 0)

ここまでで~/.vagrant.d/boxes配下に仮想マシン名のディレクトリ、さらにその下に仮想マシンを動作させるハイパーバイザ名のディレクトリができてテンプレートが保存される。仮想マシンを削除してもこのテンプレートがあるので何度でも再作成できる。

% cd ~/.vagrant.d/boxes
% tree .
.
└── centos72_64
    └── 0
        └── virtualbox
            ├── Vagrantfile
            ├── box.ovf
            ├── centos-vm-disk1.vmdk
            └── metadata.json

仮想マシン初期化、仮想マシン起動

BOXが取得できたら仮想マシンを初期化する。

まず仮想マシンの設定ファイルを作成する任意のディレクトリを作成し、以降はその場所で作業する。

% cd
% mkdir -p vagrant/centos72
% cd vagrant/centos72

仮想マシンの初期化は以下のようにする。

% vagrant init centos72_64
% ls
Vagrantfile

ここで作成されたVagrantfileに変更を加えることで仮想マシンの挙動を制御することができる。今はとりあえずそのままの状態で仮想マシンを起動する。

% vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'centos72_64'...
==> default: Matching MAC address for NAT networking...
==> default: Setting the name of the VM: centos72_default_1556375501669_16376
Vagrant is currently configured to create VirtualBox synced folders with
the `SharedFoldersEnableSymlinksCreate` option enabled. If the Vagrant
guest is not trusted, you may want to disable this option. For more
information on this option, please refer to the VirtualBox manual:

  https://www.virtualbox.org/manual/ch04.html#sharedfolders

This option can be disabled globally with an environment variable:

  VAGRANT_DISABLE_VBOXSYMLINKCREATE=1

or on a per folder basis within the Vagrantfile:

  config.vm.synced_folder '/host/path', '/guest/path', SharedFoldersEnableSymlinksCreate: false
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
==> default: Forwarding ports...
    default: 22 (guest) => 2222 (host) (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 reset. 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 it's present...
    default: Key inserted! Disconnecting and reconnecting using new SSH key...
==> default: Machine booted and ready!
==> default: Checking for guest additions in VM...
    default: The guest additions on this VM do not match the installed version of
    default: VirtualBox! In most cases this is fine, but in rare cases it can
    default: prevent things such as shared folders from working properly. If you see
    default: shared folder errors, please make sure the guest additions within the
    default: virtual machine match the version of VirtualBox you have installed on
    default: your host and reload your VM.
    default:
    default: Guest Additions Version: 4.3.30
    default: VirtualBox Version: 6.0
==> default: Mounting shared folders...
    default: /vagrant => /Users/xxx/vagrant/centos72

ここまで進むとVirtualBox上に仮想マシンが作成される。

~/VirtualBox VMs配下には以下のファイルが作成されている。

% cd ~/VirtualBox\ VMs
% tree .
.
└── centos72_default_1556291324827_95278
    ├── Logs
    │   └── VBox.log
    ├── centos-vm-disk1.vmdk
    ├── centos72_default_1556291324827_95278.vbox
    └── centos72_default_1556291324827_95278.vbox-prev

仮想マシン操作

仮想マシンが作成されたら以下のような操作が可能になる。必要に応じて使用する。

状態表示

% cd ~/vagrant/centos72
% 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 suspend
==> default: Saving VM state and suspending execution...

% vagrant status
Current machine states:

default                   saved (virtualbox)

To resume this VM, simply run `vagrant up`.

レジューム

スリープから復帰する。

% vagrant resume
==> default: Resuming suspended VM...
==> 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: Machine booted and ready!
==> default: Machine already provisioned. Run `vagrant provision` or use the `--provision`
==> default: flag to force provisioning. Provisioners marked to run always will still run.

シャットダウン

% vagrant halt
==> default: Attempting graceful shutdown of VM...

% vagrant status
Current machine states:

default                   poweroff (virtualbox)

The VM is powered off. To restart the VM, simply run `vagrant up`

再起動

仮想マシン起動中にVagrantfileを書き換えた場合は以下のようにして仮想マシンを再起動することで変更内容が有効になる。

% vagrant reload

仮想マシン削除

仮想マシンは簡単に削除することができる。削除してもVagrantfileは消えないので再度vagrant upを実行すれば仮想マシンを再作成できる。

% vagrant destroy
    default: Are you sure you want to destroy the 'default' VM? [y/N] <--- y
==> default: Destroying VM and associated drives...

仮想マシン接続

vagrant sshコマンドにて仮想マシンに接続できる。ログインアカウントはvagrant専用ユーザとなる。

% vagrant up <--- 前項で仮想マシンを削除したのでまず作成

% vagrant ssh
[vagrant@localhost ~]$ id
uid=1000(vagrant) gid=1000(vagrant) groups=1000(vagrant)

仮想マシン内でのIPアドレスやルーティング等の設定は以下のようになっている。

IPアドレス

10.0.2.15

デフォルトルータ

10.0.2.2

DNSサーバ

10.0.2.3

[vagrant@localhost ~]$ ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: enp0s3: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether xx:xx:xx:xx:xx:xx brd ff:ff:ff:ff:ff:ff
    inet 10.0.2.15/24 brd 10.0.2.255 scope global dynamic enp0s3
       valid_lft 86355sec preferred_lft 86355sec
    inet6 fe80::xxx:xxxx:xxxx:xxxx/64 scope link
       valid_lft forever preferred_lft forever

[vagrant@localhost ~]$ ip r
default via 10.0.2.2 dev enp0s3  proto static  metric 100
10.0.2.0/24 dev enp0s3  proto kernel  scope link  src 10.0.2.15  metric 100

[vagrant@localhost ~]$ cat /etc/resolv.conf
# Generated by NetworkManager
search xxx.local
nameserver 10.0.2.3

共有ディレクトリアクセス

ホストOS側で作成した~/vagrant/centos72ディレクトリが仮想マシン上の/vagrantにマウントされているのでここを使って両者でファイルのやり取りができる。

[vagrant@localhost ~]$ LANG=C df -h /vagrant
Filesystem      Size  Used Avail Use% Mounted on
none            234G  115G  120G  49% /vagrant

[vagrant@localhost ~]$ mount | grep /vagrant
none on /vagrant type vboxsf (rw,nodev,relatime)

プロビジョニング

先の共有ディレクトリを使って仮想マシン上でシェルスクリプトを実行させることができる。

例えば仮想マシンにApacheをインストールしたい場合、まずVagrantfileと同じディレクトリに以下のようなシェルスクリプトを作成する。

これはホストOS上で作業しても仮想マシン上で作業してもよい。

% vi startup.sh
#!/bin/bash

yum update
yum -y install httpd

次に仮想マシンが起動した時にこのシェルスクリプトが実行されるようにVagrantfileを以下のように編集する。ファイルのパスはVagrantfileが配置されているディレクトリからの相対パスで指定する。

:
Vagrant.configure(2) do |config|

  config.vm.box = "centos72_64"

  config.vm.provision "shell", path: "startup.sh"
:

ここまで終わったら仮想マシンを起動する。

% vagrant up (既に仮想マシンが起動していたらvagrant reloadを実行)

起動したらApacheがインストールされていることを確認する。

% vagrant ssh
[vagrant@localhost ~]$ yum list httpd
:
httpd.x86_64    2.4.6-40.el7.centos            base

その他

ポートフォワーディング

ホストOSでhttp://127.0.0.1:8080/にアクセスした場合に仮想マシンの80番ポートに接続するにはVagrantfileを以下のように編集する。

:
Vagrant.configure(2) do |config|

  config.vm.box = "centos72_64"

  config.vm.network "forwarded_port", guest: 80, host: 8080
:

ホストオンリーネットワーク

デフォルトではNAT接続による仮想マシンから外部へのアクセスしかできないため、ホストOSから仮想マシンにアクセスしたい場合はVagrantfileを以下のように編集する。

:
Vagrant.configure(2) do |config|

  config.vm.box = "centos72_64"

  config.vm.network "private_network", ip: "192.168.33.10"
:

こうすることで仮想マシン側で新たな仮想NICにIPアドレスが割り当てられ、ホストOS側のルーティングも自動的に設定される。

% vagrant ssh

[vagrant@localhost ~]$ ip a
:
3: enp0s8: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether xx:xx:xx:xx:xx:xx brd ff:ff:ff:ff:ff:ff
    inet 192.168.33.10/24 brd 192.168.33.255 scope global enp0s8
       valid_lft forever preferred_lft forever
    inet6 fe80::xxx:xxxx:xxxx:xxxx/64 scope link
       valid_lft forever preferred_lft forever

[vagrant@localhost ~]$ exit

% ssh vagrant@192.168.33.10
vagrant@192.168.33.10's password: ***** <- アカウントと同じ
[vagrant@localhost ~]$ 

ブリッジネットワークの作成方法は以下を参照のこと。

関連資料・記事

仮想マシンのエクスポート・インポート

仮想マシンの状態をまとめてエクスポートして他のBOX(テンプレート)として再利用することができる。

方法は簡単で、以下のコマンドを実行してできあがったファイルを移動先でインポートして初期化・起動するだけである。

エクスポート
% vagrant package
==> default: Attempting graceful shutdown of VM...
==> default: Clearing any previously set forwarded ports...
==> default: Exporting VM...
==> default: Compressing package to: /Users/xxx/vagrant/centos72/package.box

% ls -l package.box
-rw-r--r-- 1 xxx xxx 653633798  4 27 23:56 package.box
インポート、仮想マシン初期化 & 起動
% vagrant box add centos72_2 package.box
% vagrant init centos72_2
% vagrant up

他にも様々な制御ができるがVagrantfileファイルそのものに詳しい説明が書かれているので割愛する。

参考サイト

2015/12/29更新

対応バージョン: 1.7.4

Vagrantを導入し、VirtualBox環境で仮想マシンを動作させる手順を示す。

ホストOSはUbuntu 15.10(64bit)とする。

公式サイト

インストール

Vagrantインストール

% sudo apt install vagrant
% vagrant -v
Vagrant 1.7.4

VirtualBoxインストール

以下からUbuntu用のバイナリをダウンロードしてインストール

BOX取得

次に仮想マシンのテンプレートとなるBOXを取得する。

以下のサイトでいろいろなBOXが配布されているが、ここではCentOS 7.1(64bit)を導入する。

BOXの取得はvagrant box addコマンドを使い、引数として任意の仮想マシン名と取得元ファイルを指定する。

% vagrant box add centos71_64 https://github.com/CommanderK5/packer-centos-template/releases/download/0.7.1/vagrant-centos-7.1.box

% vagrant box list
centos71_64 (virtualbox)

ここまでで~/.vagrant.d/boxes配下に仮想マシン名のディレクトリ、さらにその下に仮想マシンを動作させるハイパーバイザ名のディレクトリができてテンプレートが保存される。仮想マシンを潰してもこのテンプレートがあるので何度でも再作成できる。

% cd
% ls -lR .vagrant.d/boxes
.vagrant.d/boxes:
合計 4
drwxrwxr-x 3 neo neo 4096 12月 29 20:49 centos71_64/

.vagrant.d/boxes/centos71_64:
合計 4
drwxrwxr-x 3 neo neo 4096 12月 29 20:49 0/

.vagrant.d/boxes/centos71_64/0:
合計 4
drwxrwxr-x 2 neo neo 4096 12月 29 20:49 virtualbox/

.vagrant.d/boxes/centos71_64/0/virtualbox:
合計 608596
-rw-r--r-- 1 neo neo       258 12月 29 20:49 Vagrantfile
-rw-r--r-- 1 neo neo     11941 12月 29 20:49 box.ovf
-rw-r--r-- 1 neo neo 623177216 12月 29 20:49 centos-vm-disk1.vmdk
-rw-r--r-- 1 neo neo        26 12月 29 20:49 metadata.json

仮想マシン初期化、仮想マシン起動

BOXが取得できたら仮想マシンを初期化する。

まず仮想マシンの設定ファイルを作成する任意のディレクトリを作成し、以降はその場所で作業する。

% cd
% mkdir -p vagrant/centos71
% cd vagrant/centos71

仮想マシンの初期化は以下のようにする。

% vagrant init centos71_64
% ls
Vagrantfile

ここで作成されたVagrantfileに変更を加えることで仮想マシンの挙動を制御することができる。今はとりあえずそのままの状態で仮想マシンを起動する。

% vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'centos71_64'...
==> default: Matching MAC address for NAT networking...
:
    default: VirtualBox Version: 5.0
==> default: Mounting shared folders...
    default: /vagrant => /home/neo/vagrant/centos71

ここまで進むとVirtualBox上に仮想マシンが作成される。

~/VirtualBox VMs配下には以下のファイルが作成されている。

% cd
% ls -lR VirtualBox\ VMs
VirtualBox VMs:
合計 4
drwx------ 3 neo neo 4096 12月 29 20:54 centos71_default_1451390070861_65585/

VirtualBox VMs/centos71_default_1451390070861_65585:
合計 1545664
drwx------ 2 neo neo       4096 12月 29 20:54 Logs/
-rw------- 1 neo neo 1583742976 12月 29 20:55 centos-vm-disk1.vmdk
-rw------- 1 neo neo       7971 12月 29 20:54 centos71_default_1451390070861_65585.vbox
-rw------- 1 neo neo       7971 12月 29 20:54 centos71_default_1451390070861_65585.vbox-prev

VirtualBox VMs/centos71_default_1451390070861_65585/Logs:
合計 68
-rw------- 1 neo neo 65819 12月 29 20:54 VBox.log

仮想マシン操作

仮想マシンが作成されたら以下のような操作が可能になる。必要に応じて使用する。

状態表示

% 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 suspend
==> default: Saving VM state and suspending execution...

% vagrant status
Current machine states:

default                   saved (virtualbox)

To resume this VM, simply run `vagrant up`.

レジューム

スリープから復帰する。

% vagrant resume
==> default: Resuming suspended VM...
==> 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: Machine booted and ready!

シャットダウン

% vagrant halt
==> default: Attempting graceful shutdown of VM...

% vagrant status
Current machine states:

default                   poweroff (virtualbox)

The VM is powered off. To restart the VM, simply run `vagrant up`

再起動

仮想マシン起動中にVagrantfileを書き換えた場合は以下のようにして仮想マシンを再起動することで変更内容が有効になる。

% vagrant reload

仮想マシン削除

仮想マシンはいとも簡単に削除することができる。削除してもVagrantfileは消えないので再度vagrant upを実行すれば仮想マシンを再作成できる。

% vagrant destroy
    default: Are you sure you want to destroy the 'default' VM? [y/N] <--- y
==> default: Forcing shutdown of VM...
==> default: Destroying VM and associated drives...

仮想マシン接続

vagrant sshコマンドにて仮想マシンに接続できる。ログインアカウントはvagrant専用ユーザとなる。

% vagrant up <--- 前項で仮想マシンを削除したのでまず作成

% vagrant ssh
[vagrant@localhost ~]$ id
uid=1000(vagrant) gid=1000(vagrant) groups=1000(vagrant)

仮想マシン内でのIPアドレスやルーティング等の設定は以下のようになっている。

IPアドレス

10.0.2.15

デフォルトルータ

10.0.2.2

DNSサーバ

10.0.2.3

[vagrant@localhost ~]$ ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN 
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: enp0s3: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 08:00:27:51:d1:5e brd ff:ff:ff:ff:ff:ff
    inet 10.0.2.15/24 brd 10.0.2.255 scope global dynamic enp0s3
       valid_lft 86353sec preferred_lft 86353sec
    inet6 fe80::a00:27ff:fe51:d15e/64 scope link 
       valid_lft forever preferred_lft forever

[vagrant@localhost ~]$ ip r
default via 10.0.2.2 dev enp0s3  proto static  metric 100 
10.0.2.0/24 dev enp0s3  proto kernel  scope link  src 10.0.2.15  metric 100 

[vagrant@localhost ~]$ cat /etc/resolv.conf
# Generated by NetworkManager
search elecom
nameserver 10.0.2.3

共有ディレクトリアクセス

ホストOS側で作成した~/vagrant/centos71ディレクトリが仮想マシン上の/vagrantにマウントされているのでここを使って両者でファイルのやり取りができる。

[vagrant@localhost ~]$ LANG=C df -h /vagrant
Filesystem      Size  Used Avail Use% Mounted on
none            451G  291G  160G  65% /vagrant

[vagrant@localhost ~]$ mount | grep /vagrant
none on /vagrant type vboxsf (rw,nodev,relatime)

プロビジョニング

先の共有ディレクトリを使って仮想マシン上でシェルスクリプトを実行させることができる。

例えば仮想マシンにApacheをインストールしたい場合、まずVagrantfileと同じディレクトリに以下のようなシェルスクリプトを作成する。

これはホストOS上で作業しても仮想マシン上で作業してもよい。

% vi startup.sh
#!/bin/bash

yum update
yum -y install httpd

次に仮想マシンが起動した時にこのシェルスクリプトが実行されるようにVagrantfileを以下のように編集する。ファイルのパスはVagrantfileが配置されているディレクトリからの相対パスで指定する。

:
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|

  config.vm.box = "centos71_64"

  config.vm.provision :shell, :path => "startup.sh"
:

ここまで終わったら仮想マシンを起動する。

% vagrant up (既に仮想マシンが起動していたらvagrant reloadを実行)

起動したらApacheがインストールされていることを確認する。

% vagrant ssh
[vagrant@localhost ~]$ yum list httpd
:
httpd.x86_64      2.4.6-40.el7.centos      @base

その他

ポートフォワーディング

ホストOSでhttp://127.0.0.1:8080/にアクセスした場合に仮想マシンの80番ポートに接続するにはVagrantfileを以下のように編集する。

:
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|

  config.vm.box = "centos71_64"

  config.vm.network :forwarded_port, guest: 80, host: 8080
:

ホストオンリーネットワーク

デフォルトではNAT接続による仮想マシンから外部へのアクセスしかできないため、ホストOSから仮想マシンにアクセスしたい場合はVagrantfileを以下のように編集する。

:
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|

  config.vm.box = "centos71_64"

  config.vm.network :private_network, ip: "192.168.33.10"
:

こうすることで仮想マシン側で新たな仮想NICにIPアドレスが割り当てられ、ホストOS側のルーティングも自動的に設定される。

% vagrant ssh

[vagrant@localhost ~]$ ip a
:
3: enp0s8: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 08:00:27:45:08:4a brd ff:ff:ff:ff:ff:ff
    inet 192.168.33.10/24 brd 192.168.33.255 scope global enp0s8
       valid_lft forever preferred_lft forever
    inet6 fe80::a00:27ff:fe45:84a/64 scope link 
       valid_lft forever preferred_lft forever

[vagrant@localhost ~]$ exit

% ip r
:
192.168.33.0/24 dev vboxnet1  proto kernel  scope link  src 192.168.33.1 
:

% ssh vagrant@192.168.33.10
vagrant@192.168.33.10's password: ***** <- アカウントと同じ
[vagrant@localhost ~]$ 

ブリッジネットワークの作成方法は以下を参照のこと。

関連資料・記事

仮想マシンのエクスポート・インポート

仮想マシンの状態をまとめてエクスポートして他のBOX(テンプレート)として再利用することができる。

方法は簡単で、以下のコマンドを実行してできあがったファイルを移動先でインポートして初期化・起動するだけである。

エクスポート
% vagrant package
==> default: Attempting graceful shutdown of VM...
==> default: Clearing any previously set forwarded ports...
==> default: Exporting VM...
==> default: Compressing package to: /xxx/yyy/package.box

% ls -l package.box
-rw-rw-r-- 1 neo neo 627712676 12月 29 21:26 package.box
インポート、仮想マシン初期化 & 起動
% vagrant box add centos71_2 package.box
% vagrant init centos71_2
% vagrant up

他にも様々な制御ができるがVagrantfileファイルそのものに詳しい説明が書かれているので割愛する。

参考サイト