k-holyのPHPとか諸々メモ

Webで働くk-holyがPHP(スクリプト言語)とか諸々のことをメモしていきます。ソースコードはだいたいWindowsで動かしてます。

Windows7にVirtualBoxとVagrantをインストールしたメモ

開発環境に便利と話題のVirtualBoxとVagrantを、ようやくインストールしてみたメモです。

こちらの記事を参考にしました。

VirtualBoxを入れる

Downloads ? Oracle VM VirtualBox から VirtualBox 4.2.16 for Windows hosts x86/amd64 をダウンロードして実行。

Setup Wizardが起動するので Next Next。なんかOracle製のドライバ類が色々インストールされるけど気にしない。

Vagrantを入れる

Vagrant - Downloads から 最新版 v1.2.7 のページに飛び Vagrant_1.2.7.msi をダウンロードして実行。

Setup Wizardが起動するので Next Next。インストールが終わると「再起動しろ」と言われるので、再起動します。

Vagrant Boxファイルを入れる

A list of base boxes for Vagrant - Vagrantbox.es から、使いたい仮想サーバのイメージファイルを選択して、Vagrantに追加します。

今回は使い慣れた CentOSの最新版っぽい CentOS 6.4 x86_64 Minimal (VirtualBox Guest Additions 4.2.12, Chef 11.4.4, Puppet 3.1.1) を選択。

以下、コマンドはMSYSのコンソール、ホームディレクトリにて実行。

$ vagrant box add centos64_64 http://developer.nrel.gov/downloads/vagrant-boxes/CentOS-6.4-x86_64-v20130427.box
Downloading or copying the box...
Successfully added box 'centos64_64' with provider 'virtualbox'!

$ vagrant init centos64_64
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 box add を自宅でやったら回線のせいかとんでもなく時間がかかったので、可能であれば別途入手してローカルから追加した方がいいと思います。 (パス部分はローカルでも大丈夫なので)

vagrant init コマンドを実行した場所に設定ファイルVagrantfileが作成されますので、プロジェクト毎に仮想サーバを変えたい場合やバージョン管理したい場合は対象のディレクトリに移動して実行すればOKです。

Vagrant を起動してみる

$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
[default] Importing base box 'centos64_64'...
[default] Matching MAC address for NAT networking...
[default] Setting the name of the VM...
[default] Clearing any previously set forwarded ports...
[default] Creating shared folders metadata...
[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 VM to boot. This can take a few minutes.
[default] Forcing shutdown of VM...
[default] Destroying VM and associated drives...
c:/Applications/HashiCorp/Vagrant/embedded/gems/gems/net-ssh-2.6.8/lib/net/ssh/authentication/agent/socket.rb:81:in `neg
otiate!': unknown response from agent: 1, "\x00\x00\x00-\x01\x00\x00\x00(SSH-2.0-Ruby/Net::SSH_2.6.8 i386-mingw32" (Net:
:SSH::Authentication::AgentError)

なんか怒られました。 検索してみたところ、どうもWindowsでPuTTYのAgentを起動しているとこうなるみたいです。

AgentError, unknown response from agent on Windows with 64-bit PuTTY ・ Issue #1455 ・ mitchellh/vagrant

一旦Pageantを終了してもう一度…(普段の開発にはPageantないと不便なんだけどなぁ…)

$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
[default] Importing base box 'centos64_64'...
[default] Matching MAC address for NAT networking...
[default] Setting the name of the VM...
[default] Clearing any previously set forwarded ports...
[default] Creating shared folders metadata...
[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 VM to boot. This can take a few minutes.
[default] VM booted and ready for use!
[default] Mounting shared folders...
[default] -- /vagrant

※追記注

vagrant upコマンド実行時に作成される .vagrant/machines/default/virtualbox/id ファイルにはVirtualBox VMのIDが書き込まれていて、このIDがホームディレクトリに作成される .VirtualBox/VirtualBox.xml で参照先の .vbox ファイルに関連付けられています。

VirtualBox単体の利用経験はないのですが、VirtualBox.xml内のコメントを見たところ、このファイルは本来は VBoxManage.exe や VirtualBox Manager GUI を通じて作成されるもので、vagrantコマンドがそれを代行してくれてるみたいです。

※追記その2 vagrant upの途中で固まってVMが起動しない場合

vagrant upコマンド実行後、"Waiting for VM to boot. This can take a few minutes."で固まってしまう場合は、Vagrantfileで以下の設定を有効にして、VirtualBoxGUIモードで起動してみてください。

config.vm.provider :virtualbox do |vb|
  vb.gui = true
end

GUI上に「仮想化支援機構(VT-x/AMD-V)を有効化できません」というダイアログが出てVMが起動していない場合、BIOSで機能が無効にされているかもしれません。

自宅のWindows8 VAIO(SVE14A2AJ)のBIOS初期設定で "Intel(R) Virtualization Technology" がDisabledに設定されており、この問題に当たりました。

仮想サーバに接続してみる

仮想サーバが起動したようなので、接続してみます。

$ vagrant ssh
Welcome to your Vagrant-built virtual machine.
[vagrant@localhost ~]$

何もすることなく、あっさり入れてしまいました。

[vagrant@localhost ~]$ sudo vi /etc/sysconfig/network
E437: terminal capability "cm" required
Press ENTER or type command to continue"/etc/sysconfig/network"

しかし、何かファイルを編集しようとするとエラーが発生し、画面表示がおかしくなってしまいます。

参考サイト Window 7 でVagrantでCent OS 6.3入れてみた - 僕の車輪の再発明 によればPuTTY推奨とのことなので、PuTTYに変えてみました。

ホスト vagrant@127.0.0.1 ポート 2222

パスワードを聞かれますが、"vagrant"で通りました。

[vagrant@localhost ~]$ sudo vi /etc/sysconfig/network
NETWORKING=yes
HOSTNAME=localhost.localdomain

PuTTYの場合は編集もばっちりです。

PuTTYで入ってる時にVMを停止したらどうなるかな。

$ vagrant halt
[default] Attempting graceful shutdown of VM...

[vagrant@localhost ~]$
Broadcast message from vagrant@localhost.localdomain
...
The system is going down for halt NOW!

普通に落とされました(笑)

一度起動すれば普通のサーバと同じなので、ユーザー作成して公開鍵設置してsshdの設定を適宜すれば、Pageantで公開鍵認証も普通にできると思います。

(Vagrantの起動時にPageant下げなきゃいけないのが面倒ですが…)

saharaプラグインを入れてみる

Vagrantのサンドボックスモードでコミットとロールバックを実現するというsaharaプラグインを入れてみます。

$ vagrant plugin install sahara
Installing the 'sahara' plugin. This can take a few minutes...
Installed the plugin 'sahara (0.0.15)'!

$ vagrant sandbox on
0%...10%...20%...30%...40%...50%...60%...70%...80%...90%...100%

$ vagrant up

PuTTYで入って適当にディレクトリ作成してみます。

[vagrant@localhost ~]$ mkdir .bin
[vagrant@localhost ~]$ ls -lsa
total 32
4 drwx------  4 vagrant vagrant 4096 Aug 30 06:03 .
4 drwxr-xr-x. 4 root    root    4096 Apr 27 10:05 ..
4 -rw-------  1 vagrant vagrant  290 Aug 30 05:44 .bash_history
4 -rw-r--r--  1 vagrant vagrant   18 Feb 21  2013 .bash_logout
4 -rw-r--r--  1 vagrant vagrant  176 Feb 21  2013 .bash_profile
4 -rw-r--r--  1 vagrant vagrant  124 Feb 21  2013 .bashrc
4 drwxrwxr-x  2 vagrant vagrant 4096 Aug 30 06:03 .bin
4 drwx------  2 vagrant root    4096 Apr 27 10:05 .ssh

サンドボックスをコミット(結構時間かかります)

$ vagrant sandbox commit
0%...10%...20%...30%...40%...50%...60%...70%...80%...90%...100%
0%...10%...20%...30%...40%...50%...60%...70%...80%...90%...100%

ディレクトリを削除してみます。

[vagrant@localhost ~]$ rm -rf .bin
[vagrant@localhost ~]$ ls -lsa
total 28
4 drwx------  3 vagrant vagrant 4096 Aug 30 06:08 .
4 drwxr-xr-x. 4 root    root    4096 Apr 27 10:05 ..
4 -rw-------  1 vagrant vagrant  290 Aug 30 05:44 .bash_history
4 -rw-r--r--  1 vagrant vagrant   18 Feb 21  2013 .bash_logout
4 -rw-r--r--  1 vagrant vagrant  176 Feb 21  2013 .bash_profile
4 -rw-r--r--  1 vagrant vagrant  124 Feb 21  2013 .bashrc
4 drwx------  2 vagrant root    4096 Apr 27 10:05 .ssh

一度ログアウトして、サンドボックスロールバック

$ vagrant sandbox rollback
0%...10%...20%...30%...40%...50%...60%...70%...80%...90%...100%
0%...10%...20%...30%...40%...50%...60%...70%...80%...90%...100%

ログインし直して確認してみる。

[vagrant@localhost ~]$ ls -lsap
total 32
4 drwx------  4 vagrant vagrant 4096 Aug 30 06:03 ./
4 drwxr-xr-x. 4 root    root    4096 Apr 27 10:05 ../
4 -rw-------  1 vagrant vagrant  290 Aug 30 05:44 .bash_history
4 -rw-r--r--  1 vagrant vagrant   18 Feb 21  2013 .bash_logout
4 -rw-r--r--  1 vagrant vagrant  176 Feb 21  2013 .bash_profile
4 -rw-r--r--  1 vagrant vagrant  124 Feb 21  2013 .bashrc
4 drwxrwxr-x  2 vagrant vagrant 4096 Aug 30 06:03 .bin/
4 drwx------  2 vagrant root    4096 Apr 27 10:05 .ssh/

復活してます。よしよし

vagrant-vbox-snapshotプラグインを入れてみる(→削除)

VirtualBoxのスナップショット機能をvagrantコマンドで使えるようにするという、超便利なプラグインを入れてみます。

$ vagrant plugin install vagrant-vbox-snapshot
Installing the 'vagrant-vbox-snapshot' plugin. This can take a few minutes...
Installed the plugin 'vagrant-vbox-snapshot (0.0.2)'!
$ vagrant snapshot take centos64_64_1
$ vagrant snapshot list

参考記事の通り、本当にうんともすんとも言わない…Windowsで動かないのかな。それにしてもエラーメッセージひとつ返さないのってどうなの…。

よく分からないので、なかったことにします。

$ vagrant plugin uninstall vagrant-vbox-snapshot
$ vagrant plugin list
sahara (0.0.15)

実際、環境構築の自動化までいくと、そこまでの機能は使わないんじゃないかという気もしますし。

検索しても便利だ便利だという声しか聞こえてこないので、Windowsユーザーのためにここに書き残しておきます。

IPアドレスを変更してみる

IPアドレスがこのままの 127.0.0.1 だと競合して使えないので一旦終了、Vagrantfile設定ファイルを変更してみます。

ホームディレクトリに作成されていた初期状態の Vagrantfile は、以下の内容でした。

Rubyで書かれた設定ファイルのようです。

# -*- 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 = "centos64_64"

  # The url from where the 'config.vm.box' box will be fetched if it
  # doesn't already exist on the user's system.
  # config.vm.box_url = "http://domain.com/path/to/above.box"

  # 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

  # 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.

  # 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 centos64_64.pp in the manifests_path directory.
  #
  # An example Puppet manifest to provision the message of the day:
  #
  # # group { "puppet":
  # #   ensure => "present",
  # # }
  # #
  # # File { owner => 0, group => 0, mode => 0644 }
  # #
  # # file { '/etc/motd':
  # #   content => "Welcome to your Vagrant-built virtual machine!
  # #               Managed by Puppet.\n"
  # # }
  #
  # config.vm.provision :puppet do |puppet|
  #   puppet.manifests_path = "manifests"
  #   puppet.manifest_file  = "init.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

めっちゃ英語 (((;゚Д゚)))

でも、ここだけに注目すれば何とかなりそうです。

# 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"

公式ドキュメント Networking - Public Network - Vagrant Documentation

要は、ホストOSから見たIPアドレスをここで設定できるようです。

Webで検索すると :hostonly:bridged といった、旧バージョンの設定ファイルの書き方がたくさんヒットするので要注意です。

上記設定のコメントを削除して、vagrant reload で再起動します。(Pageantの常駐解除を忘れずに…)

Apache + PHP入れてみる

yumでガシガシ入れます。とりあえずの確認なので最小限のパッケージで、細かい設定はパス。

$ sudo yum -y install httpd
Installed:
  httpd.x86_64 0:2.2.15-29.el6.centos

Dependency Installed:
  apr.x86_64 0:1.3.9-5.el6_2                 apr-util.x86_64 0:1.3.9-3.el6_0.1  apr-util-ldap.x86_64 0:1.3.9-3.el6_0.1
  httpd-tools.x86_64 0:2.2.15-29.el6.centos  mailcap.noarch 0:2.1.31-2.el6

Complete!

$ sudo yum -y install php 
Installed:
  php.x86_64 0:5.3.3-23.el6_4

Dependency Installed:
  php-cli.x86_64 0:5.3.3-23.el6_4                           php-common.x86_64 0:5.3.3-23.el6_4

Complete!

$ sudo chkconfig httpd on
$ sudo service httpd start

iptablesが初期設定ではポート22のみ通す設定になってるので、80も通すように。

$ sudo vi /etc/sysconfig/iptables
# Firewall configuration written by system-config-firewall
# Manual customization of this file is not recommended.
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
COMMIT

$ sudo service iptables restart

phpinfo()を実行するスクリプトを設置します。

$ sudo vi /var/www/html/index.php
<?php phpinfo();

ブラウザで http://192.168.33.10/ を開くと…

http://cdn.mogile.archive.st-hatena.com/v1/image/k-holy/297783820098874484.png

キタワァ・゜゚・:.。..。.:*・゜(n'∀')η゚・

とりあえずここまでで、一旦ロールバックします。

$ vagrant sandbox rollback
0%...10%...20%...30%...40%...50%...60%...70%...80%...90%...100%
0%...10%...20%...30%...40%...50%...60%...70%...80%...90%...100%

終了する時はVagrantの停止を忘れずに。

$ 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`

今後のための参考

ホストOSとのディレクトリ共有設定とか、Vagrantfileはプロジェクト毎にバージョン管理せよとか、参考になる内容です。

環境設定の自動化は、よく名前を見るChefはなんか準備がめんどくさそう、SoloとかKnifeとか色々あってよう分からんし、私のような弱小PHPerからするとRubyっていうだけでもう…。 (((;゚Д゚)))

何より、すでにFabric使っててPythonの環境があるので、最近ちょくちょく見るAnsibleの方を試してみようかと…思ったのですが…。

For the central Ansible machine, you will need an environment with Python 2.6 or greater installed. If you are running Python 2.5 on an “Enterprise Linux 5” variant, we’ll show you how to add 2.6 to your distribution, but most platforms already have a new enough Python. (Note that Windows is not supported as the Ansible control machine.)

…。

Windows is not supported as the Ansible control machine.

。・゚・(ノД`)・゚・。

[追記]

参考記事と同じBlogですが、Windows環境でのAnsibleに挑戦されてました。

Cygwinで挑戦されてる方も。

その他参考になりそうな記事

ChocolateyというWindows版apt-getのようなパッケージ管理システムを使ってインストールされた方

VagrantからのSSHの接続情報を確認する方法とか

Vagrantは色々めんどくさいことを自動で(デフォルト設定で)やってくれてるようなので、先へ進む前に公式ドキュメントも目的に合わせて読んだ方が良さそうですね…。