CentOS7.1にてVagrant Base Boxを作成する

CentOS7.1でVagrant Base Boxを自作する方法について。

1. 動作確認環境

2. 前提条件

  • Vagrantがインストール済であること
  • VirtualBoxがインストール済であること
  • TeraTerm等のターミナルソフトがインストール済であること

3. Vagrant Base Box作成手順

(1) CentOS7.1 ISOファイルのダウンロード

下記URLからCentOS 7.1.1503のISOファイル(minimal)をダウンロードする。

http://ftp.riken.jp/Linux/centos/7.1.1503/isos/x86_64/
→"CentOS-7-x86_64-Minimal-1503-01.iso"

(2) VirtualBoxにてVM作成

VirtualBoxを起動し、メニューの[新規]を選択して新規VMを作成する。

  • VM名:任意*1
  • OS :Linux, Red Hat (64 bit)
  • CPU :1コア以上*2
  • MEM :512MB以上*3
  • HDD :サイズ可変, 8GB以上*4, VDI*5
(3) VM設定

Vagrantの公式ドキュメント(Creating a Base Box - Vagrant Documentation)に従い、下記のVM設定を行う。(VM設定は、該当VMを右クリックし、メニューから[設定]を選択)

  • "オーディオ"設定にて、[オーディオを有効化]のチェックを外す。
  • "USB"設定にて、[USBコントローラーを有効化]のチェックを外す。

また、OSインストール後にターミナルソフトからSSHにてログオン可能となるよう、ポートフォワーディングの設定を行う。

  1. "ネットワーク"設定にて、[アダプター1]を選択し、[高度]タブを展開する。
  2. [ポートフォワーディング]ボタンを押下する。
  3. [新規ルールを追加]ボタンを押下し、ポートフォワーディングルールを設定する。設定内容は以下の通り。
  • 名前    :任意(ssh等)
  • プロトコル :TCP
  • ホストIP  :127.0.0.1
  • ホストポート:任意(2222等)
  • ゲストポート:22
(4) CentOS7.1インストール

VM設定にて、予めDLしたISOイメージを対象VMにマウントし、VMを起動する。インストール時の設定は以下の通り。

  1. インストーラの初期画面にて、[Install CentOS 7.1]を選択する。
  2. [CentOSへようこそ]画面にて、[日本語]を選択する。
  3. [地域設定]は規定値とする。*6
  4. [ソフトウェア]は規定値とする。*7
  5. "システム"の"インストール先"を選択し、先ほど作成した仮想HDDが選択されていることを確認。また、"自動構成のパーティション構成"を選択。*8
  6. "システム"の"ネットワークとホスト名"を選択し、[イーサネット(enpOs3)]を有効化する。*9また、任意のホスト名を設定する。
  7. [インストールの開始]ボタンを押下する。
  8. "rootパスワード"を選択し、パスワードとして"vagrant"を設定する。*10
  9. "ユーザの作成"を選択し、非管理者ユーザとして、"vagrant"を作成する。パスワードは"vagrant"とする。*11
  10. インストールが正常に完了することを確認する。
(5) OS設定
a) 不要サービスの停止・無効化

最少インストール直後に動作しているサービス一覧は以下の通り。

[root@centos71 ~]# systemctl list-units --type=service
UNIT                               LOAD   ACTIVE SUB     DESCRIPTION
auditd.service                     loaded active running Security Auditing Service
crond.service                      loaded active running Command Scheduler
dbus.service                       loaded active running D-Bus System Message Bus
firewalld.service                  loaded active running firewalld - dynamic firewall daemon
getty@tty1.service                 loaded active running Getty on tty1
kdump.service                      loaded failed failed  Crash recovery kernel arming
kmod-static-nodes.service          loaded active exited  Create list of required static device nodes for the current kernel
lvm2-lvmetad.service               loaded active running LVM2 metadata daemon
lvm2-monitor.service               loaded active exited  Monitoring of LVM2 mirrors, snapshots etc. using dmeventd or progress
lvm2-pvscan@8:2.service            loaded active exited  LVM2 PV scan on device 8:2
network.service                    loaded active exited  LSB: Bring up/down networking
NetworkManager.service             loaded active running Network Manager
polkit.service                     loaded active running Authorization Manager
postfix.service                    loaded active running Postfix Mail Transport Agent
rhel-dmesg.service                 loaded active exited  Dump dmesg to /var/log/dmesg
rhel-import-state.service          loaded active exited  Import network configuration from initramfs
rhel-readonly.service              loaded active exited  Configure read-only root support
rsyslog.service                    loaded active running System Logging Service
sshd.service                       loaded active running OpenSSH server daemon
systemd-journald.service           loaded active running Journal Service
systemd-logind.service             loaded active running Login Service
systemd-random-seed.service        loaded active exited  Load/Save Random Seed
systemd-remount-fs.service         loaded active exited  Remount Root and Kernel File Systems
systemd-sysctl.service             loaded active exited  Apply Kernel Variables
systemd-tmpfiles-setup-dev.service loaded active exited  Create static device nodes in /dev
systemd-tmpfiles-setup.service     loaded active exited  Create Volatile Files and Directories
systemd-udev-trigger.service       loaded active exited  udev Coldplug all Devices
systemd-udevd.service              loaded active running udev Kernel Device Manager
systemd-update-utmp.service        loaded active exited  Update UTMP about System Reboot/Shutdown
systemd-user-sessions.service      loaded active exited  Permit User Sessions
systemd-vconsole-setup.service     loaded active exited  Setup Virtual Console
tuned.service                      loaded active running Dynamic System Tuning Daemon

LOAD   = Reflects whether the unit definition was properly loaded.
ACTIVE = The high-level unit activation state, i.e. generalization of SUB.
SUB    = The low-level unit activation state, values depend on unit type.

32 loaded units listed. Pass --all to see loaded but inactive units, too.
To show all installed unit files use 'systemctl list-unit-files'.

今回は、firewalldとpostfixを無効化する。firewalld無効化の例を以下に示す。

[root@centos71 ~]# systemctl status firewalld
firewalld.service - firewalld - dynamic firewall daemon
   Loaded: loaded (/usr/lib/systemd/system/firewalld.service; enabled)
   Active: active (running) since 金 2015-05-29 10:56:27 JST; 3min 39s ago
 Main PID: 542 (firewalld)
   CGroup: /system.slice/firewalld.service
           mq542 /usr/bin/python -Es /usr/sbin/firewalld --nofork --nopid

 529 10:56:27 centos71 systemd[1]: Started firewalld - dynamic firewall daemon.
[root@centos71 ~]# systemctl stop firewalld
[root@centos71 ~]# systemctl disable firewalld
rm '/etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service'
rm '/etc/systemd/system/basic.target.wants/firewalld.service'
[root@centos71 ~]# systemctl status firewalld
firewalld.service - firewalld - dynamic firewall daemon
   Loaded: loaded (/usr/lib/systemd/system/firewalld.service; disabled)
   Active: inactive (dead)

 529 10:56:22 centos71 systemd[1]: Starting firewalld - dynamic firewall daemon...
 529 10:56:27 centos71 systemd[1]: Started firewalld - dynamic firewall daemon.
 529 11:00:15 centos71 systemd[1]: Stopping firewalld - dynamic firewall daemon...
 529 11:00:15 centos71 systemd[1]: Stopped firewalld - dynamic firewall daemon.
b) SELinuxの無効化

開発時は不要なため、SELinuxを無効化しておく。

[root@centos71 ~]# vi /etc/selinux/config

編集内容は以下の通り。

[root@centos71 ~]# diff selinux_config_before selinux_config_after
< SELINUX=enforcing
---
> SELINUX=disabled
c) sudo設定

vagrantユーザがパスワード無しでsudo実行可能とする。

インストール時にvagrantユーザを作成した場合、規定でvagrantグループに所属しているため、以下ではvagrantグループに対して設定を行っている。

[root@centos71 ~]# visudo

編集内容は以下の通り。

[root@centos71 ~]# diff sudoers_before sudoers_after
56c56
< Defaults    requiretty
---
> #Defaults    requiretty
108a109
> %vagrant      ALL=(ALL)       NOPASSWD: ALL
d) SSH設定

vagrantユーザにてSSHする際に使用するInsecure Private Keyを登録しておく。

[root@centos71 ~]# mkdir /home/vagrant/.ssh
[root@centos71 ~]# chmod 700 /home/vagrant/.ssh
[root@centos71 ~]# curl https://raw.githubusercontent.com/mitchellh/vagrant/master/keys/vagrant.pub >> /home/vagrant/.ssh/authorized_keys
[root@centos71 ~]# chmod 600 /home/vagrant/.ssh/authorized_keys
[root@centos71 ~]# chown -R vagrant:vagrant /home/vagrant/.ssh

Insecure Private KeyをDLする際は必要に応じてhttps_proxyの設定を行う。

[root@centos71 ~]# export https_proxy=https://<user>:<pass>@<proxyserver>:<port>/
e) 既存パッケージのアップデート

既存パッケージを最新化しておく。

[root@centos71 ~]# yum -y update
f) 追加パッケージのインストール

開発で必要な追加パッケージをインストールする。
下記最後の1行はrubyインストール時に必要となるパッケージ群。

[root@centos71 ~]# yum -y groupupdate "Development Tools"
[root@centos71 ~]# yum -y install man-pages-ja wget vim-enhanced
[root@centos71 ~]# yum -y install gcc zlib-devel openssl-devel sqlite sqlite-devel mysql-devel readline-devel libffi-devel
g) rubyインストール

ruby(最新安定板)をソースコードからインストールする。

[root@centos71 ~]# wget http://cache.ruby-lang.org/pub/ruby/2.2/ruby-2.2.2.tar.gz
[root@centos71 ~]# tar xzvf ./ruby-2.2.2.tar.gz
[root@centos71 ~]# cd ./ruby-2.2.2
[root@centos71 ~]# ./configure
[root@centos71 ~]# make
[root@centos71 ~]# make install
h) VirtualBox Guest Additionsのインストール

VirtualBoxのメニューから、[デバイス] > [Guest Additions のCDイメージを挿入...]を選択し、以下の手順でインストールする。

[root@centos71 ~]# mkdir /media/cdrom
[root@centos71 ~]# mount -r /dev/cdrom /media/cdrom
[root@centos71 ~]# sh /media/cdrom/VBoxLinuxAdditions.run
Verifying archive integrity... All good.
Uncompressing VirtualBox 4.3.28 Guest Additions for Linux............
VirtualBox Guest Additions installer
Copying additional installer modules ...
Installing additional modules ...
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  ]
Installing the Window System drivers
Could not find the X.Org or XFree86 Window System, skipping.

[root@centos71 ~]# umount /media/cdrom
i) udevルールの削除

OS起動時にネットワークデバイスのエラーが発生するのを防ぐため、以下のudevルールを削除する。

[root@centos71 ~]# rm /etc/udev/rules.d/70-persistent-ipoib.rules
j) GRUB設定

CentOS7起動時に"Fast TSC calibration failed"エラーが表示されるのを防止するため、GRUB設定を行う。*12

[root@centos71 ~]# vi /etc/default/grub

編集内容は以下の通り。

[root@centos71 ~]# diff grub_before grub_after
5c5
< GRUB_CMDLINE_LINUX="rd.lvm.lv=centos/root rd.lvm.lv=centos/swap crashkernel=auto rhgb quiet"
---
> GRUB_CMDLINE_LINUX="rd.lvm.lv=centos/root rd.lvm.lv=centos/swap crashkernel=auto rhgb quiet clocksource=tsc"
6a7
> GRUB_CMDLINE_LINUX="clocksource=tsc"
k) yum cleanの実施とシャットダウン

OS設定の最後にyum cleanを実行し、シャットダウンする。

(6) Base Box作成
a) ポートフォワーディング設定削除

事前に設定したポートフォワーディング設定を削除する。

b) Base Box作成

コマンドプロンプトから、下記の手順でBase Boxを作成及び登録する。

C:\tmp> vagrant package --base centos71 package.box
C:\tmp> vagrant box add --name centos7.1 package.box
==> box: Adding box 'centos7.1' (v0) for provider:
    box: Downloading: file://C:/tmp/package.box
    box: Progress: 100% (Rate: 75.3M/s, Estimated time remaining: --:--:--)
==> box: Successfully added box 'centos7.1' (v0) for 'virtualbox'!

C:\tmp> vagrant box list
centos7.1 (virtualbox, 0)

トラブルシュート

作成したBase Boxから新規VMを作成して起動したら、起動シーケンスで以下のエラーが表示された。

(略)

==> default: Machine booted and ready!
GuestAdditions seems to be installed (4.3.28) correctly, but not running.
Starting vboxadd (via systemctl):  Job for vboxadd.service failed. See 'systemct
l status vboxadd.service' and 'journalctl -xn' for details.
[??????]
Removing existing VirtualBox non-DKMS kernel modules[  OK  ]
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.
The missing package can be probably installed with
yum install kernel-devel-3.10.0-229.el7.x86_64

Building the main Guest Additions module[??????]
(Look at /var/log/vboxadd-install.log to find out what went wrong)
Doing non-kernel setup of the Guest Additions[  OK  ]
Restarting VM to apply changes...

GuestAdditionsがnot runningなので、vboxaddサービスの起動に失敗している。その後、予め導入しておいたVagrantプラグイン"vagrant-vbguest"がGuestAdditionsの再構成を試みているものの、失敗している。

そこで、"/var/log/vboxadd-install.log"を確認してみる。

(略)

/tmp/vbox.0/Makefile.include.header:97: *** Error: unable to find the sources of your current Linux kernel. Specify KERN_DIR=<directory> and run Make again.  中止.
Creating user for the Guest Additions.
Creating udev rule for the Guest Additions kernel module.

なるほど、Linux kernelのソースコードが見つからないと。原因を探ってみると、"uname -r"の結果と、"/usr/src/kernels"配下のディレクトリ名が異なっているため、上記のエラーが出ているらしい。

[root@centos01 ~]# uname -r
3.10.0-229.el7.x86_64
[root@centos01 ~]#
[root@centos01 ~]# ls -l /usr/src/kernels/
合計 4
drwxr-xr-x. 22 root root 4096  5月 28 14:50 3.10.0-229.4.2.el7.x86_64

"3.10.0-229"までは同一だが、kernelソースコードディレクトリ名ではその後に".4.2"とある。これが原因。

なぜこういうことになっているかよくわからないが、パッチレベルまで一致しているし、とにかくVirtualBox的には"uname -r"の結果と同一名のディレクトリが存在していないといけないようなので、シンボリックリンクを貼っておく。その上で、"vboxadd setup"を実行。

[root@centos01 ~]# ln -s /usr/src/kernels/3.10.0-229.4.2.el7.x86_64 /usr/src/kernels/3.10.0-229.el7.x86_64
[root@centos01 ~]# /etc/init.d/vboxadd setup
Removing existing VirtualBox non-DKMS kernel modules       [  OK  ]
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.
The missing package can be probably installed with
yum install kernel-devel-3.10.0-229.el7.x86_64

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  ]

エラーメッセージは出力されているものの、無事正常終了。ちなみに、"kernel-devel-3.10.0-229.el7.x86_64"はインストール済。"vagrant reload"でVMを再起動すると、正常にVMが起動した。

(略)

GuestAdditions 4.3.28 running --- OK.
==> default: Checking for guest additions in VM...
==> default: Setting hostname...
==> default: Configuring and enabling network interfaces...
==> default: Mounting shared folders...
    default: /vagrant => C:/vm/centos01

*1:VirtualBox上でVMを識別する際に使用される名称。OSのホスト名ではない。

*2:VM作成ウィザードではコア数を指定できない(1固定)。VM作成後に設定画面にてコア数を変更可能。

*3:最低サイズ以上で任意の値を指定。

*4:最低サイズ以上で任意のサイズを指定

*5:要件に合わせてファイルタイプを選択

*6:ようこそ画面で日本語を選択したため、自動的に設定される。

*7:一旦最小構成でインストールし、開発ツール等の必要パッケージはインストール後に導入する。

*8:要件に応じてパーティション構成を手動設定する。

*9:ここで有効化しない場合、インストール後にVirtualBoxのコンソールからログインし、有効化する。また、IPv4アドレスはdhcpによる取得(規定)とする。

*10:Vagrant公式ドキュメントの指示に従う。

*11:Vagrant公式ドキュメントの指示に従う。このタイミングでは作成せず、インストール後に作成しても良い。

*12:ぷにおちゃん ~ CentOS 7起動時のTSC calibration failedを消す方法