Vagrantは2013年の記事 Windows7にVirtualBoxとVagrantをインストールしたメモ でインストールはしてみたものの、日々の開発作業に追われるまま長らく使っていませんでした。
実はこのブログでは一番人気の記事で、言及リンクしていただいた数も最も多いのですが、書いた私自身はほぼそれっきりでVagrant使ってなかったという…。(ノ∀`)
ローカル開発で常用するには重くて厳しいし、そもそも担当者は自分だけで管理してるサーバも片手で数えられる程、root権限貰って一から構築できる機会もない、といった理由で学習コストに見合う利点がまだ感じられなかったのです。
(自分自身がそうなんだから、上司にとってはもっとそうだろうなぁと…なかなかこういう開発環境構築、みたいな作業に何日も使うのも難しいんですよね。)
しかし、今回再び新規サーバ環境を構築機会ができ、そろそろ一人担当からも卒業しなければ、という流れにもなってきましたので、再び入門してみたメモです。
以下、手順は途中まで前の記事そのままですが、Windowsで開発中のApache + MySQL + PHPアプリケーションのテスト環境構築をAnsibleで自動化するというのが真の目標なので、とりあえずVagrantBoxのインストールと起動、Vagrantfileの編集までに留めます。
また、ゲストOSからホストOSの所属するLAN上のデータベースを利用したいので、プライベートネットワークを有効にします。
VirtualBoxを入れる
Downloads - Oracle VM VirtualBox から VirtualBox 4.3.26 for Windows hosts x86/amd64 をダウンロードして実行。
Setup Wizardが起動するので Next Next。なんかOracle製のドライバ類が色々インストールされるけど気にしない。
Vagrantを入れる
Download Vagrant - Vagrant から WINDOWS Universal (32 and 64-bit) をダウンロードして実行。
Setup Wizardが起動するので Next Next。インストールが終わると「再起動しろ」と言われるので、再起動します。
Vagrant Boxファイルを入れる
A list of base boxes for Vagrant - Vagrantbox.es から、使いたい仮想サーバのイメージファイルを選択して、Vagrantに追加します。
今回も使い慣れたCentOS6系で CentOS 6.4 i386 Minimal (VirtualBox Guest Additions 4.3.2, Chef 11.8.0, Puppet 3.3.1) を選択。
以下、コマンドはNYAOSでホームディレクトリにて実行。
ホームディレクトリにてVagrant boxを追加
$ vagrant box add centos64_i386 http://developer.nrel.gov/downloads/vagrant-boxes/CentOS-6.4-i386-v20131103.box
==> box: Adding box 'centos64_i386' (v0) for provider:
box: Downloading: http://developer.nrel.gov/downloads/vagrant-boxes/CentOS-6.4-i386-v20131103.box
box: Progress: 100% (Rate: 9639k/s, Estimated time remaining: --:--:--)
==> box: Successfully added box 'centos64_i386' (v0) for 'virtualbox'!
以前と比べて、進捗が分かりやすく表示されています。
'centos64_i386' (v0) と表示されているのは、今のVagrantではboxファイルのバージョン管理を行ってくれるためのようです。
Vagrantが管理しているboxは追加の際に付けた名前でディレクトリが作成され、例えば今回の場合は ~/.vagrant.d/boxes/centos64_i386/0/virtualbox 以下にファイルが配置されます。間の 0 がバージョン番号になるんでしょうか。
プロジェクトのVagrant設定
Vagrantの設定も含めてプロジェクト単位でgitのバージョン管理下に入れるため、以後はプロジェクトディレクトリ内で行います。
プロジェクト名は "delivery" としました。
$ cd ~/Documents/Projects/delivery $ mkdir vagrant $ cd vagrant $ vagrant init centos64_i386 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 init コマンドを実行した場所にVagrantfileが作成されました。
ひとまず準備できたので起動してみます。
$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'centos64_i386'...
==> default: Matching MAC address for NAT networking...
==> default: Setting the name of the VM: vagrant_default_1430453933460_60304
==> 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: Warning: Connection timeout. Retrying...
default: Warning: Remote connection disconnect. 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: Mounting shared folders...
default: /vagrant => C:/Users/k_horii/Documents/Projects/delivery/vagrant
以前はPageant(PuTTY authentication agent)を起動していると怒られたんですが、改善されたみたいですね。これは嬉しい。
$ vagrant ssh Welcome to your Vagrant-built virtual machine. [vagrant@localhost ~]$ pwd /home/vagrant
無事に入れました。
[vagrant@localhost ~]$ sudo vi /etc/sysconfig/network NETWORKING=yes HOSTNAME=localhost.localdomain
以前はPuTTY経由でないとできなかったファイルの編集も、できるようになってます。
Vagrantのプライベートネットワークを利用する
プライベートネットワークを利用して、ゲストOSからホストOSが所属するLANにアクセスできるようにします。
Vagranfileの内容を確認してみます。
# -*- mode: ruby -*- # vi: set ft=ruby : # All Vagrant configuration is done below. The "2" in Vagrant.configure # configures the configuration version (we support older styles for # backwards compatibility). Please don't change it unless you know what # you're doing. Vagrant.configure(2) do |config| # The most common configuration options are documented and commented below. # For a complete reference, please see the online documentation at # https://docs.vagrantup.com. # Every Vagrant development environment requires a box. You can search for # boxes at https://atlas.hashicorp.com/search. config.vm.box = "centos64_i386" # 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" # 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| # # Display the VirtualBox GUI when booting the machine # vb.gui = true # # # Customize the amount of memory on the VM: # vb.memory = "1024" # end # # View the documentation for the provider you are using for more # information on available options. # Define a Vagrant Push strategy for pushing to Atlas. Other push strategies # such as FTP and Heroku are also available. See the documentation at # https://docs.vagrantup.com/v2/push/atlas.html for more information. # config.push.define "atlas" do |push| # push.app = "YOUR_ATLAS_USERNAME/YOUR_APPLICATION_NAME" # end # Enable provisioning with a shell script. Additional provisioners such as # Puppet, Chef, Ansible, Salt, and Docker are also available. Please see the # documentation for more information about their specific syntax and use. # config.vm.provision "shell", inline: <<-SHELL # sudo apt-get update # sudo apt-get install -y apache2 # SHELL end
めっちゃ英語 (((;゚Д゚))) ですが、変えるのはここだけ。
# 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"
プライベートネットワークを有効、ゲストOSのIPアドレスを "192.168.33.10" とし、vagrant reload で再起動します。
$ vagrant reload
==> default: Attempting graceful shutdown of VM...
==> 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: Adapter 2: hostonly
==> 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: Warning: Connection timeout. Retrying...
default: Warning: Remote connection disconnect. Retrying...
==> default: Machine booted and ready!
==> default: Checking for guest additions in VM...
==> default: Configuring and enabling network interfaces...
==> default: Mounting shared folders...
default: /vagrant => C:/Users/k_horii/Documents/Projects/delivery/vagrant
==> default: Machine already provisioned. Run `vagrant provision` or use the `--provision`
==> default: to force provisioning. Provisioners marked to run always will still run.
前回の起動時は Adapter 1: nat だけだったのが、Adapter 2: hostonly が追加されています。
ゲストOSに入ってネットワーク設定を確認してみます。
$ vagrant ssh
Welcome to your Vagrant-built virtual machine.
[vagrant@localhost ~]$ ifconfig
eth0 Link encap:Ethernet HWaddr **:**:**:**:**:**
inet addr:10.0.2.15 Bcast:10.0.2.255 Mask:255.255.255.0
inet6 addr: fe80::a00:27ff:fe5a:fb02/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:774 errors:0 dropped:0 overruns:0 frame:0
TX packets:579 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:81387 (79.4 KiB) TX bytes:69757 (68.1 KiB)
eth1 Link encap:Ethernet HWaddr **:**:**:**:**:**
inet addr:192.168.33.10 Bcast:192.168.33.255 Mask:255.255.255.0
inet6 addr: fe80::a00:27ff:fe87:e4a1/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:5 errors:0 dropped:0 overruns:0 frame:0
TX packets:8 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:326 (326.0 b) TX bytes:552 (552.0 b)
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:16436 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:0 (0.0 b) TX bytes:0 (0.0 b)
eth1 として 192.168.33.10 が追加されています。
ホストOSからゲストOS (192.168.33.10)にpingしてみます。
$ ping -n 3 192.168.33.10
192.168.33.10 に ping を送信しています 32 バイトのデータ:
192.168.33.10 からの応答: バイト数 =32 時間 <1ms TTL=64
192.168.33.10 からの応答: バイト数 =32 時間 <1ms TTL=64
192.168.33.10 からの応答: バイト数 =32 時間 <1ms TTL=64
192.168.33.10 の ping 統計:
パケット数: 送信 = 3、受信 = 3、損失 = 0 (0% の損失)、
ラウンド トリップの概算時間 (ミリ秒):
最小 = 0ms、最大 = 0ms、平均 = 0ms
ちゃんと届いています。
ゲストOS (192.168.33.10)からホストOSが所属するLAN内にある開発サーバ (192.168.1.100)にpingしてみます。
[vagrant@localhost ~]$ ping -c 3 192.168.1.100 PING 192.168.1.100 (192.168.1.100) 56(84) bytes of data. 64 bytes from 192.168.1.100: icmp_seq=1 ttl=63 time=4.11 ms 64 bytes from 192.168.1.100: icmp_seq=2 ttl=63 time=1.03 ms 64 bytes from 192.168.1.100: icmp_seq=3 ttl=63 time=0.969 ms --- 192.168.1.100 ping statistics --- 3 packets transmitted, 3 received, 0% packet loss, time 2004ms rtt min/avg/max/mdev = 0.969/2.039/4.111/1.465 ms
こちらも届きました。
念のため、LAN内にある開発サーバ (192.168.1.100)からゲストOS (192.168.33.10)にpingしてみます。
[develop@centos6 ~]$ ping -c 3 192.168.33.10 PING 192.168.33.10 (192.168.33.10) 56(84) bytes of data. --- 192.168.33.10 ping statistics --- 3 packets transmitted, 0 received, 100% packet loss, time 12000ms
プライベートネットワークなので届きません。
参考にした記事
上の記事では更に、ゲストOS同士でのホストOSでのポートフォワーディングによって、ゲストOSに接続させる方法についても書かれています。
他にもQiitaの vagarnt タグを見ると、現在1200件以上の投稿があります。
共有フォルダのマウントで引っ掛かったり、CentOSだとカーネルを更新したらVirtualBox GuestAdditionsが壊れたとか、そういった情報が散見されます。
いくつか気になる記事をメモしておきます。
- vagrant + ansible + CentOS7.0 + VirtualBox 環境で仮想マシンを良い感じに初期化する - Qiita
- Vagrantで自作boxをDropboxで共有しつつバージョニングもしたい - Qiita
後はAnsibleを覚えて、コマンドコピペ作業からちゃんと卒業したいです。
(Fabricは…今のところバックアップ作業や開発サーバへのgitリポジトリ作成などに使ってますが、再利用可能なコマンドとしてまとめる程の作業量が発生しないというか…)