VagrantのBaseBox（VirtualBox）を自作する

# VagrantのBaseBox（VirtualBox）の自作

* [VirtualBox](http://vagrantup.com "VirtualBox")
* [Vagrant](http://vagrantup.com "Vagrant")

* [Creating A Base Box](https://docs.vagrantup.com/v2/boxes/base.html "Creating A Base Box")


## ホストOSの設定

* BIOS設定で`Intel VT-x`を有効化しておく。


## VirtualBoxのインストール

* VirtualBoxおよびVirtualBox Extension Packをダウンロードしてインストールする
    * https://www.virtualbox.org/wiki/Downloads
* VirtualBox Extension Packは`[ファイル]->[環境設定]->[機能拡張]`にインストールする


## Vagrantのインストール

* Vagrantをダウンロードしてインストールする
    * https://www.vagrantup.com/downloads.html


## BaseBoxスペック

|  項目  |      設定値       |
| :----- | :---------------- |
| OS     | CentOS 6.5 x86_64 |
| CPU    | 1CPU              |
| Memory | 640MB             |
| HDD    | 14GB              |
| NIC1   | HostOnly          |


## VirtualBox設定

* 一般
    * 基本
        * centos65x64-base  
* システム
    * マザーボード
        * ■ I/O APICを有効化
        * □ ハードウェアクロックをUTCにする
    * アクセラレーション
        * ■ VT-x/AMD-Vを有効化
* オーディオ
    * □ オーディオを有効化
* アダプター１
    * ■ ネットワークアダプターを有効化
        * ホストオンリーアダプター


## OSインストール

|        項目        |              設定値               |
| :----------------- | :-------------------------------- |
| 言語設定           | Japanase(日本語)                  |
| キーボード設定     | 日本語                            |
| ホスト名           | centos65x64.base.example.com      |
| ネットワーク設定   | ■自動接続する                     |
| 地域設定           | □システムクロックでUTCを使用      |
| rootパスワード     | `vagrant`                         |
| ソフトウェアセット | `Basic Server` → 今すぐカスタマイズ |

### 今すぐカスタマイズ

変更点のみ（□：除外／■：追加）

* ベースシステム
    * □ ディレクトリ接続クライアント
    * □ 大規模システムのパフォーマンス
* サーバー
    * ■ システム管理ツール
* デスクトップ
    * ■ X Window System
    * ■ グラフィカル管理ツール
    * ■ デスクトップ
    * ■ フォント
    * ■ 汎用デスクトップ（GNOMEデスクトップ）
* アプリケーション
    * ■ インターネットブラウザ


## 仮想マシン設定

* UTCを無効化（`/etc/sysconfig/clock`）

```diff:/etc/sysconfig/clock
 ZONE="Asia/Tokyo"
+UTC="false"
```

### SELinuxの無効化（`/etc/selinux/config`）

```diff:/etc/selinux/config
 #     enforcing - SELinux security policy is enforced.
 #     permissive - SELinux prints warnings instead of enforcing.
 #     disabled - No SELinux policy is loaded.
-SELINUX=enforcing
+SELINUX=disabled
 # SELINUXTYPE= can take one of these two values:
 #     targeted - Targeted processes are protected,
 #     mls - Multi Level Security protection.
```

### 不要サービスの自動起動停止

* `NetworkManager`、`kdump`、`iptables`、`ip6tables`を停止して後はお好みで

```text:自動起動停止サービス
NetworkManager
acpid
auditd
bluetooth
cpuspeed
cups
firstboot
httpd
ip6tables
iptables
irqbalance
kdump
mdmonitor
netconsole
netfs
nfs
nfslock
ntpd
ntpdate
postfix
psacct
quota_nld
rdisc
rngd
rpcbind
rpcgssd
saslauthd
smartd
spice-vdagentd
sysstat
wdaemon
```

```diff:
-NetworkManager         0:off   1:off   2:on    3:on    4:on    5:on    6:off
+NetworkManager         0:off   1:off   2:off   3:off   4:off   5:off   6:off
 abrt-ccpp              0:off   1:off   2:off   3:on    4:off   5:on    6:off
 abrtd                  0:off   1:off   2:off   3:on    4:off   5:on    6:off
-acpid                  0:off   1:off   2:on    3:on    4:on    5:on    6:off
+acpid                  0:off   1:off   2:off   3:off   4:off   5:off   6:off
 atd                    0:off   1:off   2:off   3:on    4:on    5:on    6:off
-auditd                 0:off   1:off   2:on    3:on    4:on    5:on    6:off
+auditd                 0:off   1:off   2:off   3:off   4:off   5:off   6:off
 autofs                 0:off   1:off   2:off   3:on    4:on    5:on    6:off
 blk-availability       0:off   1:on    2:on    3:on    4:on    5:on    6:off
-bluetooth              0:off   1:off   2:off   3:on    4:on    5:on    6:off
-cpuspeed               0:off   1:on    2:on    3:on    4:on    5:on    6:off
+bluetooth              0:off   1:off   2:off   3:off   4:off   5:off   6:off
+cpuspeed               0:off   1:off   2:off   3:off   4:off   5:off   6:off
 crond                  0:off   1:off   2:on    3:on    4:on    5:on    6:off
-cups                   0:off   1:off   2:on    3:on    4:on    5:on    6:off
+cups                   0:off   1:off   2:off   3:off   4:off   5:off   6:off
 dnsmasq                0:off   1:off   2:off   3:off   4:off   5:off   6:off
 firstboot              0:off   1:off   2:off   3:off   4:off   5:off   6:off
 haldaemon              0:off   1:off   2:off   3:on    4:on    5:on    6:off
 htcacheclean           0:off   1:off   2:off   3:off   4:off   5:off   6:off
 httpd                  0:off   1:off   2:off   3:off   4:off   5:off   6:off
-ip6tables              0:off   1:off   2:on    3:on    4:on    5:on    6:off
-iptables               0:off   1:off   2:on    3:on    4:on    5:on    6:off
-irqbalance             0:off   1:off   2:off   3:on    4:on    5:on    6:off
+ip6tables              0:off   1:off   2:off   3:off   4:off   5:off   6:off
+iptables               0:off   1:off   2:off   3:off   4:off   5:off   6:off
+irqbalance             0:off   1:off   2:off   3:off   4:off   5:off   6:off
 kdump                  0:off   1:off   2:off   3:off   4:off   5:off   6:off
 lvm2-monitor           0:off   1:on    2:on    3:on    4:on    5:on    6:off
 mcelogd                0:off   1:off   2:off   3:on    4:off   5:on    6:off
-mdmonitor              0:off   1:off   2:on    3:on    4:on    5:on    6:off
+mdmonitor              0:off   1:off   2:off   3:off   4:off   5:off   6:off
 messagebus             0:off   1:off   2:on    3:on    4:on    5:on    6:off
 netconsole             0:off   1:off   2:off   3:off   4:off   5:off   6:off
-netfs                  0:off   1:off   2:off   3:on    4:on    5:on    6:off
+netfs                  0:off   1:off   2:off   3:off   4:off   5:off   6:off
 network                0:off   1:off   2:on    3:on    4:on    5:on    6:off
 nfs                    0:off   1:off   2:off   3:off   4:off   5:off   6:off
-nfslock                0:off   1:off   2:off   3:on    4:on    5:on    6:off
+nfslock                0:off   1:off   2:off   3:off   4:off   5:off   6:off
 ntpd                   0:off   1:off   2:off   3:off   4:off   5:off   6:off
 ntpdate                0:off   1:off   2:off   3:off   4:off   5:off   6:off
 portreserve            0:off   1:off   2:on    3:on    4:on    5:on    6:off
-postfix                0:off   1:off   2:on    3:on    4:on    5:on    6:off
+postfix                0:off   1:off   2:off   3:off   4:off   5:off   6:off
 psacct                 0:off   1:off   2:off   3:off   4:off   5:off   6:off
 quota_nld              0:off   1:off   2:off   3:off   4:off   5:off   6:off
 rdisc                  0:off   1:off   2:off   3:off   4:off   5:off   6:off
 restorecond            0:off   1:off   2:off   3:off   4:off   5:off   6:off
 rngd                   0:off   1:off   2:off   3:off   4:off   5:off   6:off
-rpcbind                0:off   1:off   2:on    3:on    4:on    5:on    6:off
-rpcgssd                0:off   1:off   2:off   3:on    4:on    5:on    6:off
+rpcbind                0:off   1:off   2:off   3:off   4:off   5:off   6:off
+rpcgssd                0:off   1:off   2:off   3:off   4:off   5:off   6:off
 rpcsvcgssd             0:off   1:off   2:off   3:off   4:off   5:off   6:off
 rsyslog                0:off   1:off   2:on    3:on    4:on    5:on    6:off
 saslauthd              0:off   1:off   2:off   3:off   4:off   5:off   6:off
 smartd                 0:off   1:off   2:off   3:off   4:off   5:off   6:off
-spice-vdagentd         0:off   1:off   2:off   3:off   4:off   5:on    6:off
+spice-vdagentd         0:off   1:off   2:off   3:off   4:off   5:off   6:off
 sshd                   0:off   1:off   2:on    3:on    4:on    5:on    6:off
-sysstat                0:off   1:on    2:on    3:on    4:on    5:on    6:off
+sysstat                0:off   1:off   2:off   3:off   4:off   5:off   6:off
 udev-post              0:off   1:on    2:on    3:on    4:on    5:on    6:off
 wdaemon                0:off   1:off   2:off   3:off   4:off   5:off   6:off
 winbind                0:off   1:off   2:off   3:off   4:off   5:off   6:off
```

### リモートホスト名を確認しないようにする（`/etc/ssh/sshd_config`）

```diff:/etc/ssh/sshd_config
-#UseDNS yes
+UseDNS no
```

### IPv6の無効化（`/etc/sysctl.conf`、`/etc/hosts`）

```diff:/etc/sysctl.conf
@@ -23,9 +23,9 @@
 net.ipv4.tcp_syncookies = 1

 # Disable netfilter on bridges.
-net.bridge.bridge-nf-call-ip6tables = 0
-net.bridge.bridge-nf-call-iptables = 0
-net.bridge.bridge-nf-call-arptables = 0
+#net.bridge.bridge-nf-call-ip6tables = 0
+#net.bridge.bridge-nf-call-iptables = 0
+#net.bridge.bridge-nf-call-arptables = 0

 # Controls the default maxmimum size of a mesage queue
 kernel.msgmnb = 65536
@@ -38,3 +38,6 @@

 # Controls the maximum number of shared memory segments, in pages
 kernel.shmall = 4294967296
+
+net.ipv6.conf.all.disable_ipv6 = 1
+net.ipv6.conf.default.disable_ipv6 = 1
```

```diff:/etc/hosts
 127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
-::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
+#::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
```

### MACアドレスとNICの対応付けの無効化

* MACアドレス情報が保存されないようにする

```shell-session
# ln -s -f /dev/null /etc/udev/rules.d/70-persistent-net.rules
# ll /etc/udev/rules.d/70-persistent-net.rules
lrwxrwxrwx 1 root root 9  8月 20 23:21 2014 /etc/udev/rules.d/70-persistent-net.rules -> /dev/null
#
```

* NICをMACアドレスの代わりにPCIアドレスで管理する

```shell-session
# ethtool -i eth0
driver: e1000
version: 7.3.21-k8-NAPI
firmware-version:
bus-info: 0000:00:03.0
supports-statistics: yes
supports-test: yes
supports-eeprom-access: yes
supports-register-dump: yes
supports-priv-flags: no
```

* `/etc/udev/rules.d/65-eth.rules`を新規作成して`bus-info`と`ethX`を対応付ける

```bash:/etc/udev/rules.d/65-eth.rules
ACTION=="add", KERNEL=="eth*", ID=="0000:00:03.0", DRIVERS=="?*", ATTR{type}=="1", NAME="eth0", OPTIONS="last_rule"
```

* `HWADDR`、`UUID`、`NM_CONTROLLED`を無効化する

```diff:/etc/sysconfig/network-scripts/ifcfg-eth0
@@ -1,10 +1,10 @@
 DEVICE=eth0
 TYPE=Ethernet
-UUID=204122e2-2b9b-4d79-9606-1e8402fd612a
+#UUID=204122e2-2b9b-4d79-9606-1e8402fd612a
 ONBOOT=yes
-NM_CONTROLLED=yes
+NM_CONTROLLED=no
 BOOTPROTO=dhcp
-HWADDR=08:00:27:5B:73:10
+#HWADDR=08:00:27:69:F5:0C
 DEFROUTE=yes
 PEERDNS=yes
 PEERROUTES=yes
```

### DVD用リポジトリを作成する

```shell-session
# mkdir -p /mnt/cdrom
```

```bash:/etc/yum.repos.d/CentOS-dvd.repo
# To use this repo, put in your DVD and use it with the other repos too:
#  yum --enablerepo=c6-media [command]
#
# or for ONLY the media repo, do this:
#
#  yum --disablerepo=\* --enablerepo=c6-media [command]

[CentOS-dvd]
name=CentOS-6.5 - x86_64 - DVD
baseurl=file:///mnt/cdrom
enabled=1
gpgcheck=1
gpgkey=file:///mnt/cdrom/RPM-GPG-KEY-CentOS-6
```

### VirtualBox Guest Additionsをインストールする

* 前提パッケージをインストールする
    * OSディスク（DVD）をマウント

```shell-session
# mount /dev/cdrom /mnt/cdrom/
mount: ブロックデバイス /dev/sr0 は書き込み禁止です、読込み専用でマウントします
#
# yum --disablerepo=\* --enablerepo=CentOS-dvd install gcc kernel-devel
Loaded plugins: fastestmirror, priorities, refresh-packagekit, security
Loading mirror speeds from cached hostfile
Setting up Install Process
Resolving Dependencies
--> Running transaction check
---> Package gcc.x86_64 0:4.4.7-4.el6 will be installed
--> Processing Dependency: cpp = 4.4.7-4.el6 for package: gcc-4.4.7-4.el6.x86_64
--> Processing Dependency: cloog-ppl >= 0.15 for package: gcc-4.4.7-4.el6.x86_64
---> Package kernel-devel.x86_64 0:2.6.32-431.el6 will be installed
--> Running transaction check
---> Package cloog-ppl.x86_64 0:0.15.7-1.2.el6 will be installed
--> Processing Dependency: libppl_c.so.2()(64bit) for package: cloog-ppl-0.15.7-1.2.el6.x86_64
--> Processing Dependency: libppl.so.7()(64bit) for package: cloog-ppl-0.15.7-1.2.el6.x86_64
---> Package cpp.x86_64 0:4.4.7-4.el6 will be installed
--> Processing Dependency: libmpfr.so.1()(64bit) for package: cpp-4.4.7-4.el6.x86_64
--> Running transaction check
---> Package mpfr.x86_64 0:2.4.1-6.el6 will be installed
---> Package ppl.x86_64 0:0.10.2-11.el6 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

====================================================================================
 Package             Arch          Version                  Repository         Size
====================================================================================
Installing:
 gcc                 x86_64        4.4.7-4.el6              centos-dvd         10 M
 kernel-devel        x86_64        2.6.32-431.el6           centos-dvd        8.7 M
Installing for dependencies:
 cloog-ppl           x86_64        0.15.7-1.2.el6           centos-dvd         93 k
 cpp                 x86_64        4.4.7-4.el6              centos-dvd        3.7 M
 mpfr                x86_64        2.4.1-6.el6              centos-dvd        157 k
 ppl                 x86_64        0.10.2-11.el6            centos-dvd        1.3 M

Transaction Summary
====================================================================================
Install       6 Package(s)

Total download size: 24 M
Installed size: 57 M
Is this ok [y/N]: y
Downloading Packages:
------------------------------------------------------------------------------------
Total                                               113 MB/s |  24 MB     00:00
Running rpm_check_debug
Running Transaction Test
Transaction Test Succeeded
Running Transaction
  Installing : ppl-0.10.2-11.el6.x86_64                                         1/6
  Installing : cloog-ppl-0.15.7-1.2.el6.x86_64                                  2/6
  Installing : mpfr-2.4.1-6.el6.x86_64                                          3/6
  Installing : cpp-4.4.7-4.el6.x86_64                                           4/6
  Installing : gcc-4.4.7-4.el6.x86_64                                           5/6
  Installing : kernel-devel-2.6.32-431.el6.x86_64                               6/6
  Verifying  : cpp-4.4.7-4.el6.x86_64                                           1/6
  Verifying  : mpfr-2.4.1-6.el6.x86_64                                          2/6
  Verifying  : kernel-devel-2.6.32-431.el6.x86_64                               3/6
  Verifying  : gcc-4.4.7-4.el6.x86_64                                           4/6
  Verifying  : ppl-0.10.2-11.el6.x86_64                                         5/6
  Verifying  : cloog-ppl-0.15.7-1.2.el6.x86_64                                  6/6

Installed:
  gcc.x86_64 0:4.4.7-4.el6           kernel-devel.x86_64 0:2.6.32-431.el6

Dependency Installed:
  cloog-ppl.x86_64 0:0.15.7-1.2.el6            cpp.x86_64 0:4.4.7-4.el6
  mpfr.x86_64 0:2.4.1-6.el6                    ppl.x86_64 0:0.10.2-11.el6

Complete!
```

* VirtualBox Guest Additionsをインストールする
    * 環境変数`KERN_DIR`にカーネルのパスを設定
    * Guest AdditionsのCDをマウント

```shell-session
# export KERN_DIR=/usr/src/kernels/`uname -r`
# mount /dev/cdrom /mnt/cdrom
# cd /mnt/cdrom/
# ./VBoxLinuxAdditions.run
Verifying archive integrity... All good.
Uncompressing VirtualBox 4.3.12 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
Installing X.Org Server 1.13 modules                       [  OK  ]
Setting up the Window System to use the Guest Additions    [  OK  ]
You may need to restart the hal service and the Window System (or just restart
the guest system) to enable the Guest Additions.

Installing graphics libraries and desktop services componen[  OK  ]
```

* バージョン確認

```shell-session
# VBoxControl --version
4.3.12r93733
# VBoxService --version
4.3.12r93733
```


### vagrantユーザの作成

* パスワードは`vagrant`

```shell-session
# groupadd -g 5000 vagrant
# groupadd -g 5001 admin
# useradd -g vagrant -G admin -u 5000 vagrant
# passwd vagrant
ユーザー vagrant のパスワードを変更。
新しいパスワード:
よくないパスワード: 辞書の単語に基づいています
よくないパスワード: 簡単すぎます
新しいパスワードを再入力してください:
passwd: 全ての認証トークンが正しく更新できました。
# id vagrant
uid=5000(vagrant) gid=5000(vagrant) 所属グループ=5000(vagrant),5001(admin)
```


### パスワードなしで`sudo`できるようにする

```diff:/etc/sudoers
@@ -53,7 +53,7 @@
 # Disable "ssh hostname sudo <cmd>", because it will show the password in clear.
 #         You have to run "ssh -t hostname sudo <cmd>".
 #
-Defaults    requiretty
+#Defaults    requiretty

 #
 # Refuse to run if unable to disable echo on the tty. This setting should also be
@@ -116,3 +116,7 @@

 ## Read drop-in files from /etc/sudoers.d (the # here does not mean a comment)
 #includedir /etc/sudoers.d
+
+vagrant ALL=(ALL) ALL
+%admin ALL=(ALL) NOPASSWD:ALL
+Defaults env_keep += "SSH_AUTH_SOCK"
```

### 公開鍵を設置する

```shell-session
# mkdir /home/vagrant/.ssh
# chmod 0700 /home/vagrant/.ssh
# curl -L -o authorized_keys https://raw.github.com/mitchellh/vagrant/master/keys/vagrant.pub
# chmod 0600 /home/vagrant/.ssh/authorized_keys
# chown -R vagrant:vagrant /home/vagrant/.ssh
```


### カスタマイズ（お好みで）

#### vimのカラースキーマをSolarizedに

* [
CentOS環境にSolarizedカラースキームを適用する](http://qiita.com/mashumashu/items/edea85ff4253cde064d7 "
CentOS環境にSolarizedカラースキームを適用する")

#### ~/.bashrc

* LS_COLORSにSolarized
* lessカラー化
* grepカラー化
* デバッグプロンプト
 
```bash:~/.bashrc
# .bashrc

# User specific aliases and functions

alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'


# Customize - Add alias

alias vi='vim'
vim_version=$(vim --version | head -1 | sed 's/^.*\ \([0-9]\)\.\([0-9]\)\ .*$/\1\2/')
alias lessc="/usr/share/vim/vim${vim_version}/macros/less.sh"

# Customize - Debug Prompt

export PS4='+ (${BASH_SOURCE}:${LINENO}): ${FUNCNAME:+$FUNCNAME(): }'

# Customize - Environment Variable

export EDITOR="vim"
export GREP_OPTIONS="--binary-files=without-match --color=auto"

# Customize - Add LS_COLORS

LS_COLORS='no=00;38;5;244:rs=0:di=00;38;5;33:ln=00;38;5;37:mh=00:pi=48;5;230;38;5;136;01:so=48;5;230;38;5;136;01:do=48;5;230;38;5;136;01:bd=48;5;230;38;5;244;01:cd=48;5;230;38;5;244;01:or=48;5;235;38;5;160:su=48;5;160;38;5;230:sg=48;5;136;38;5;230:ca=30;41:tw=48;5;64;38;5;230:ow=48;5;235;38;5;33:st=48;5;33;38;5;230:ex=00;38;5;64:*.tar=00;38;5;61:*.tgz=00;38;5;61:*.arj=00;38;5;61:*.taz=00;38;5;61:*.lzh=00;38;5;61:*.lzma=00;38;5;61:*.tlz=00;38;5;61:*.txz=00;38;5;61:*.zip=00;38;5;61:*.z=00;38;5;61:*.Z=00;38;5;61:*.dz=00;38;5;61:*.gz=00;38;5;61:*.lz=00;38;5;61:*.xz=00;38;5;61:*.bz2=00;38;5;61:*.bz=00;38;5;61:*.tbz=00;38;5;61:*.tbz2=00;38;5;61:*.tz=00;38;5;61:*.deb=00;38;5;61:*.rpm=00;38;5;61:*.jar=00;38;5;61:*.rar=00;38;5;61:*.ace=00;38;5;61:*.zoo=00;38;5;61:*.cpio=00;38;5;61:*.7z=00;38;5;61:*.rz=00;38;5;61:*.apk=00;38;5;61:*.gem=00;38;5;61:*.jpg=00;38;5;136:*.JPG=00;38;5;136:*.jpeg=00;38;5;136:*.gif=00;38;5;136:*.bmp=00;38;5;136:*.pbm=00;38;5;136:*.pgm=00;38;5;136:*.ppm=00;38;5;136:*.tga=00;38;5;136:*.xbm=00;38;5;136:*.xpm=00;38;5;136:*.tif=00;38;5;136:*.tiff=00;38;5;136:*.png=00;38;5;136:*.svg=00;38;5;136:*.svgz=00;38;5;136:*.mng=00;38;5;136:*.pcx=00;38;5;136:*.dl=00;38;5;136:*.xcf=00;38;5;136:*.xwd=00;38;5;136:*.yuv=00;38;5;136:*.cgm=00;38;5;136:*.emf=00;38;5;136:*.eps=00;38;5;136:*.CR2=00;38;5;136:*.ico=00;38;5;136:*.tex=00;38;5;245:*.rdf=00;38;5;245:*.owl=00;38;5;245:*.n3=00;38;5;245:*.ttl=00;38;5;245:*.nt=00;38;5;245:*.torrent=00;38;5;245:*.xml=00;38;5;245:*Makefile=00;38;5;245:*Rakefile=00;38;5;245:*build.xml=00;38;5;245:*rc=00;38;5;245:*1=00;38;5;245:*.nfo=00;38;5;245:*README=00;38;5;245:*README.txt=00;38;5;245:*readme.txt=00;38;5;245:*.md=00;38;5;245:*README.markdown=00;38;5;245:*.ini=00;38;5;245:*.yml=00;38;5;245:*.cfg=00;38;5;245:*.conf=00;38;5;245:*.c=00;38;5;245:*.cpp=00;38;5;245:*.cc=00;38;5;245:*.log=00;38;5;240:*.bak=00;38;5;240:*.aux=00;38;5;240:*.lof=00;38;5;240:*.lol=00;38;5;240:*.lot=00;38;5;240:*.out=00;38;5;240:*.toc=00;38;5;240:*.bbl=00;38;5;240:*.blg=00;38;5;240:*~=00;38;5;240:*#=00;38;5;240:*.part=00;38;5;240:*.incomplete=00;38;5;240:*.swp=00;38;5;240:*.tmp=00;38;5;240:*.temp=00;38;5;240:*.o=00;38;5;240:*.pyc=00;38;5;240:*.class=00;38;5;240:*.cache=00;38;5;240:*.aac=00;38;5;166:*.au=00;38;5;166:*.flac=00;38;5;166:*.mid=00;38;5;166:*.midi=00;38;5;166:*.mka=00;38;5;166:*.mp3=00;38;5;166:*.mpc=00;38;5;166:*.ogg=00;38;5;166:*.ra=00;38;5;166:*.wav=00;38;5;166:*.m4a=00;38;5;166:*.axa=00;38;5;166:*.oga=00;38;5;166:*.spx=00;38;5;166:*.xspf=00;38;5;166:*.mov=00;38;5;166:*.mpg=00;38;5;166:*.mpeg=00;38;5;166:*.m2v=00;38;5;166:*.mkv=00;38;5;166:*.ogm=00;38;5;166:*.mp4=00;38;5;166:*.m4v=00;38;5;166:*.mp4v=00;38;5;166:*.vob=00;38;5;166:*.qt=00;38;5;166:*.nuv=00;38;5;166:*.wmv=00;38;5;166:*.asf=00;38;5;166:*.rm=00;38;5;166:*.rmvb=00;38;5;166:*.flc=00;38;5;166:*.avi=00;38;5;166:*.fli=00;38;5;166:*.flv=00;38;5;166:*.gl=00;38;5;166:*.m2ts=00;38;5;166:*.divx=00;38;5;166:*.webm=00;38;5;166:*.axv=00;38;5;166:*.anx=00;38;5;166:*.ogv=00;38;5;166:*.ogx=00;38;5;166:'
export LS_COLORS

if [ -f ~/.dircolors ]; then
    if type dircolors > /dev/null 2>&1; then
        eval $(dircolors ~/.dircolors)
    elif type gdircolors > /dev/null 2>&1; then
        eval $(gdircolors ~/.dircolors)
    fi
fi

# Source global definitions

if [ -f /etc/bashrc ]; then
        . /etc/bashrc
fi
```


### 不要データの削除

* /var/tmpの配下削除

```shell-session
# rm -r /var/tmp/*
```

* DHCPリソース情報を削除する

```shell-session
# rm -rf /var/lib/dhcp/*
```

* yumキャッシュのクリア

```shell-session
# yum clean all
Loaded plugins: fastestmirror, refresh-packagekit, security
Cleaning repos: CentOS-dvd base extras updates
Cleaning up Everything
Cleaning up list of fastest mirrors
```

* 未使用領域のゼロフィル

```shell-session
# dd if=/dev/zero of=/EMPTY bs=1M
# rm -f /EMPTY
```

* コマンド履歴の削除

```shell-session
# sudo -u vagrant cat /dev/null >~/.bash_history
# cat /dev/null >~/.bash_history
```


## BaseBoxの作成

* 仮想マシンをシャットダウンして、BaseBoxを作成する
* ホストOS上で以降のコマンドを実行する
    * コマンドを実行したディレクトリ直下に作成されるので、事前にcdしておく

```bat:構文
vagrant package --base <vboxファイル>
```

```bat:コマンドプロンプト
> cd /d "N:\development\binary\Vagrant\BaseBox\CentOS65x64"
> vagrant package --output "centos65x64-base.box" --base "E:\VirtualBox-VMs\centos65x64
-base\centos65x64-base.vbox"
==> E:\VirtualBox-VMs\centos65x64-base\centos65x64-base.vbox: Exporting VM...
==> E:\VirtualBox-VMs\centos65x64-base\centos65x64-base.vbox: Compressing package to: N:/development/binary/Vagrant/BaseBox/CentOS65x64/centos65x64-base.box
```


## BaseBoxをVagrantに登録

```bat:構文
vagrant box add <BaseBox登録名> <BaseBoxファイル>
```

```bat:コマンドプロンプト
> vagrant box add my-centos-6.5-x86_64-base "N:\development\binary\Vagrant\BaseBox\Cent
OS65x64\centos65x64-base.box"
==> box: Adding box 'my-centos-6.5-x86_64-base' (v0) for provider:
    box: Downloading: file://N:/development/binary/Vagrant/BaseBox/CentOS65x64/centos65x64-base.box
    box: Progress: 100% (Rate: 791M/s, Estimated time remaining: --:--:--)
==> box: Successfully added box 'my-centos-6.5-x86_64-base' (v0) for 'virtualbox'!
```

* 登録されていることを確認

```bat:コマンドプロンプト
> vagrant box list
my-centos-6.5-x86_64-base (virtualbox, 0)
```


## Vagrantの初期化

* カレントフォルダに設定ファイル(`Vagrantfile`)を作成する

```bat:構文
vagrant init <box名>
```

```bat:コマンドプロンプト
> cd /d E:\Vagrant-Machines
> mkdir myCentOS65x64-test01
> cd myCentOS65x64-test01
> vagrant init my-centos-6.5-x86_64-base
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.
```


## Vagrantによる仮想マシンの起動

* `Vagrantfile`があるディレクトリ上で`vagrant up`コマンドを実行することで仮想マシンが起動する

```bat:構文
vagrant up
```

```bat:コマンドプロンプト
> vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'my-centos-6.5-x86_64-base'...
==> default: Matching MAC address for NAT networking...
==> default: Setting the name of the VM: myCentOS65x64-test01
==> 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: Running 'pre-boot' VM customizations...
==> 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: Warning: Remote connection disconnect. Retrying...
==> default: Machine booted and ready!
==> default: Checking for guest additions in VM...
==> default: Checking for host entries
==> default: Setting hostname...
==> default: Mounting shared folders...
    default: /vagrant => E:/Vagrant-Machines/myCentOS65x64-test01
```

```rb:Vagrantfile
# -*- mode: ruby -*-
# vi: set ft=ruby :

# Vagrantfile API/syntax version. Don't touch unless you know what you're doing!
VAGRANTFILE_API_VERSION = "2"

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
  # All Vagrant configuration is done here. The most common configuration
  # options are documented and commented below. For a complete reference,
  # please see the online documentation at vagrantup.com.

  # Every Vagrant virtual environment requires a box to build off of.
  config.vm.box = "my-centos-6.5-x86_64-base"

  # Disable automatic box update checking. If you disable this, then
  # boxes will only be checked for updates when the user runs
  # `vagrant box outdated`. This is not recommended.
  # config.vm.box_check_update = false

  # Create a forwarded port mapping which allows access to a specific port
  # within the machine from a port on the host machine. In the example below,
  # accessing "localhost:8080" will access port 80 on the guest machine.
  # config.vm.network "forwarded_port", guest: 80, host: 8080

  # Create a private network, which allows host-only access to the machine
  # using a specific IP.
  # config.vm.network "private_network", ip: "192.168.33.10"

  # Create a public network, which generally matched to bridged network.
  # Bridged networks make the machine appear as another physical device on
  # your network.
  # config.vm.network "public_network"

  config.vm.hostname = "test01.centos65x64.example.com"

  # If true, then any SSH connections made will enable agent forwarding.
  # Default value: false
  # config.ssh.forward_agent = true

  # Share an additional folder to the guest VM. The first argument is
  # the path on the host to the actual folder. The second argument is
  # the path on the guest to mount the folder. And the optional third
  # argument is a set of non-required options.
  # config.vm.synced_folder "../data", "/vagrant_data"

  # Provider-specific configuration so you can fine-tune various
  # backing providers for Vagrant. These expose provider-specific options.
  # Example for VirtualBox:
  #
  # config.vm.provider "virtualbox" do |vb|
  #   # Don't boot with headless mode
  #   vb.gui = true
  #
  #   # Use VBoxManage to customize the VM. For example to change memory:
  #   vb.customize ["modifyvm", :id, "--memory", "1024"]
  # end
  #
  # View the documentation for the provider you're using for more
  # information on available options.

  config.vm.provider "virtualbox" do |vb|
    vb.name = "myCentOS65x64-test01"
    vb.customize ["modifyvm", :id, "--rtcuseutc", "off"]
    vb.customize ["modifyvm", :id, "--memory", "512"]
  end

  # Enable provisioning with CFEngine. CFEngine Community packages are
  # automatically installed. For example, configure the host as a
  # policy server and optionally a policy file to run:
  #
  # config.vm.provision "cfengine" do |cf|
  #   cf.am_policy_hub = true
  #   # cf.run_file = "motd.cf"
  # end
  #
  # You can also configure and bootstrap a client to an existing
  # policy server:
  #
  # config.vm.provision "cfengine" do |cf|
  #   cf.policy_server_address = "10.0.2.15"
  # end

  # Enable provisioning with Puppet stand alone.  Puppet manifests
  # are contained in a directory path relative to this Vagrantfile.
  # You will need to create the manifests directory and a manifest in
  # the file default.pp in the manifests_path directory.
  #
  # config.vm.provision "puppet" do |puppet|
  #   puppet.manifests_path = "manifests"
  #   puppet.manifest_file  = "site.pp"
  # end

  # Enable provisioning with chef solo, specifying a cookbooks path, roles
  # path, and data_bags path (all relative to this Vagrantfile), and adding
  # some recipes and/or roles.
  #
  # config.vm.provision "chef_solo" do |chef|
  #   chef.cookbooks_path = "../my-recipes/cookbooks"
  #   chef.roles_path = "../my-recipes/roles"
  #   chef.data_bags_path = "../my-recipes/data_bags"
  #   chef.add_recipe "mysql"
  #   chef.add_role "web"
  #
  #   # You may also specify custom JSON attributes:
  #   chef.json = { mysql_password: "foo" }
  # end

  # Enable provisioning with chef server, specifying the chef server URL,
  # and the path to the validation key (relative to this Vagrantfile).
  #
  # The Opscode Platform uses HTTPS. Substitute your organization for
  # ORGNAME in the URL and validation key.
  #
  # If you have your own Chef Server, use the appropriate URL, which may be
  # HTTP instead of HTTPS depending on your configuration. Also change the
  # validation key to validation.pem.
  #
  # config.vm.provision "chef_client" do |chef|
  #   chef.chef_server_url = "https://api.opscode.com/organizations/ORGNAME"
  #   chef.validation_key_path = "ORGNAME-validator.pem"
  # end
  #
  # If you're using the Opscode platform, your validator client is
  # ORGNAME-validator, replacing ORGNAME with your organization name.
  #
  # If you have your own Chef Server, the default validation client name is
  # chef-validator, unless you changed the configuration.
  #
  #   chef.validation_client_name = "ORGNAME-validator"
end
```


## Vagrantによる仮想マシンの停止

* `Vagrantfile`があるディレクトリ上で`vagrant halt`コマンドを実行することで仮想マシンが停止する

```bat:構文
vagrant halt
```

```bat:コマンドプロンプト
> vagrant halt
==> default: Attempting graceful shutdown of VM...
==> default: Removing hosts
```


## Vagrant基本コマンド

* `Vagrantfile`があるディレクトリ上でコマンド実行する

| 仮想マシンへの操作 |      コマンド     |
| :----------------- | :---------------- |
| 状態確認           | `vagrant status`  |
| 起動               | `vagrant up`      |
| 再起動             | `vagrant reload`  |
| 停止               | `vagrant halt`    |
| スリープ           | `vagrant suspend` |
| 復帰               | `vagrant resume`  |
| 削除               | `vagrant destroy` |


## 仮想マシンへの接続

* コマンドプロンプトにはsshクライアントがないので、直接接続できない。

```bat:コマンドプロンプト
>vagrant ssh
`ssh` executable not found in any directories in the %PATH% variable. Is an
SSH client installed? Try installing Cygwin, MinGW or Git, all of which
contain an SSH client. Or use your favorite SSH client with the following
authentication information shown below:

Host: 127.0.0.1
Port: 2222
Username: vagrant
Private key: C:/Users/<ユーザ名>/.vagrant.d/insecure_private_key
```

* sshクライアントが入っている場合は、すぐアクセスできる

```bat:sshクライアントありターミナル
> vagrant ssh
Last login: Tue Aug 26 22:54:21 2014 from 10.0.2.2
[vagrant@test01 ~]$
```

* TeraTermなどのターミナルソフトを用いてアクセスすることができる
    * ホストOSの`127.0.0.1:2222`にアクセスすることで仮想マシンの`:22`にポートフォワードされる