とあるセキュリティエンジニアの技術系日記

セキュリティエンジニアが自己研鑽目的で書いてくだけの場所です

macでchefとvagrantを動かしたい!

今まで挑戦してこなかったことに、今更挑戦してみよう!と思ったので

最近メインで使用しているMac Book ProにChef+Vagrant環境を

構築してみようと思う。

基本的に私は思い立ったらすぐ、あるいは出来るだけ早くがモットーなので

この記事の執筆をしながらの環境構築作業である。

故に多数の誤字脱字等による不備が見つかるだろうが、

暖かい目で見守ってやってほしい。


ところで今回chef+vagrantで何をするのかと言うと、以前より"管理コマンドが

変更されたCentOS7"が気になっていたため、ちょっと試してみようと

そういうわけだ。

*1

参考サイト:

Mac(Yosemite)にChef(12.0.3)とVagrant(1.7.2)を入れてプロビジョニングしてみた - カタカタブログ

さて、環境構築に移ろう!

構成

先述したとおり私の環境はMac Book Proである。

まな板?包丁?みたいなAirではないので悪しからず。

  • ホスト環境: Mac OS X Yosemite 10.10.2
  • 仮想ノードOS: Cent OS 7
  • Vagrant 1.7.2
  • Virtual Box 4.3.3
  • Ruby 2.1.5
  • Chef 12.0.3
    • knife-solo 0.4.2
  • berkshelf 3.2.3

上記は先ほどの参考サイトであるカタカタブログさんの記事から引用したものである。

私のMacでは

となっている。*2

Virtual BoxとVagrantの導入

それぞれ最新版を導入した

Virtual Boxについては以前より導入済みのため今回はVagrantのみを導入した。

ここではVirtual Box,Vagrantのインストール手順は割愛する。

Vagrant Pluginのインストール

vagrant-vbguestインストール

$ vagrant plugin install vagrant-vbguest
Installing the 'vagrant-vbguest' plugin. This can take a few minutes...
Installed the plugin 'vagrant-vbguest (0.10.1)'!

chefプラグインインストール

$ vagrant plugin install vagrant-omnibus
Installing the 'vagrant-omnibus' plugin. This can take a few minutes...
Installed the plugin 'vagrant-omnibus (1.4.1)'!

Cent OS 7のBoxをvagrantbox.esから取得

$ mkdir centos7
$ vagrant box add centos7 https://github.com/tommy-muehle/puppet-vagrant-boxes/releases/download/1.1.0/centos-7.0-x86_64.box
==> box: Box file was not detected as metadata. Adding it directly...
==> box: Adding box 'centos7' (v0) for provider: 
    box: Downloading: https://github.com/tommy-muehle/puppet-vagrant-boxes/releases/download/1.1.0/centos-7.0-x86_64.box
==> box: Successfully added box 'centos7' (v0) for 'virtualbox'!

vagrantでCent OS 7の仮想マシンを作成

$ cd centos7/
$ vagrant init centos7
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.

lsで作成されたものを確認

$ ls -al
total 8
drwxr-xr-x  3 masa  staff   102 10 15 17:17 .
drwxr-xr-x  3 masa  staff   102 10 12 19:31 ..
-rw-r--r--  1 masa  staff  3019 10 15 17:17 Vagrantfile

Vagrantfileを編集

Vagrantfile
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure(2) do |config|
  config.vm.box = "centos7"
  config.vm.network "private_network", ip: "192.168.33.100"
  config.vm.hostname = "vmcentos"
  config.vbguest.auto_update = false # Guest Additions自動更新無効
  config.vm.provider "virtualbox" do |vb|
    vb.name = "centos7_vagrant"
    vb.memory = "2048"
  end
end

度々登場する参考サイトではGuest Additionのバージョン不一致で起動できないとのことだが、
私の環境では特に手動更新することなく起動した。

仮想マシンを起動する

$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'centos7'...
==> default: Matching MAC address for NAT networking...
==> default: Setting the name of the VM: centos7_vagrant
==> 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: 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: 
    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.28
    default: VirtualBox Version: 5.0
==> default: Setting hostname...
==> default: Configuring and enabling network interfaces...
==> default: Mounting shared folders...
    default: /vagrant => /Users/masa/vagrant/centos7

f:id:masatiger:20151015175248j:plain

こんなかんじで起動までされたので、とりあえず完了だろうか?

Chefセットアップ

Rubyのバージョンを確認

$ ruby -v
ruby 2.1.6p336 (2015-04-13 revision 50298) [x86_64-darwin14.0]

Gemfileを作成する

$ bundle init
Writing new Gemfile to /Users/masa/vagrant/centos7/Gemfile

Gemfileを編集する

source "https://rubygems.org"

gem "chef"
gem "knife-solo"
gem "berkshelf"
bundlerでインストール
$ bundle install
Fetching gem metadata from https://rubygems.org/.........
Fetching version metadata from https://rubygems.org/...
Fetching dependency metadata from https://rubygems.org/..
Resolving dependencies......
Using rake 10.4.2
Using addressable 2.3.8
Using multipart-post 2.0.0


Your user account isn''t allowed to install to the system Rubygems.
You can cancel this installation and run:

    bundle install --path vendor/bundle

to install the gems into ./vendor/bundle/, or you can enter your password
and install the bundled gems to Rubygems using sudo.

Password: 
Installing faraday 0.9.2
Installing httpclient 2.6.0.1
Installing berkshelf-api-client 2.0.0
Installing buff-extensions 1.0.0
Installing hashie 3.4.2
Installing varia_model 0.4.1
Installing buff-config 1.0.1
Installing buff-ruby_engine 0.1.0
Installing buff-shell_out 0.2.0
Installing hitimes 1.2.3 with native extensions
Installing timers 4.0.4
Installing celluloid 0.16.0
Installing nio4r 1.1.1 with native extensions
Installing celluloid-io 0.16.2
Installing cleanroom 1.0.0
Installing minitar 0.5.4
Installing sawyer 0.6.0
Installing octokit 3.8.0
Installing retryable 2.0.2
Installing buff-ignore 1.1.1
Using erubis 2.7.0
Using json 1.8.3
Installing mixlib-log 1.6.0
Installing mixlib-authentication 1.3.0
Installing semverse 1.2.1
Installing ridley 4.3.2
Installing dep-selector-libgecode 1.0.2 with native extensions
Using ffi 1.9.10
Installing dep_selector 1.0.3 with native extensions
Installing solve 1.2.1
Using thor 0.19.1
Installing berkshelf 4.0.1
Installing builder 3.2.2
Installing mixlib-config 2.2.1
Installing mixlib-shellout 2.2.1
Installing chef-config 12.5.1
Installing libyajl2 1.2.0 with native extensions
Installing ffi-yajl 2.2.2 with native extensions
Installing rack 1.6.4
Installing uuidtools 2.1.5
Installing chef-zero 4.3.2
Using diff-lcs 1.2.5
Installing highline 1.7.8
Installing mixlib-cli 1.5.0
Installing net-ssh 2.9.2
Installing net-ssh-gateway 1.2.0
Installing net-ssh-multi 1.2.1
Installing ipaddress 0.8.0
Installing mime-types 2.6.2
Installing systemu 2.6.5
Installing wmi-lite 1.0.0
Installing ohai 8.7.0
Installing plist 3.1.0
Using coderay 1.1.0
Using method_source 0.8.2
Using slop 3.6.0
Installing pry 0.10.3
Installing rspec-support 3.3.0
Installing rspec-core 3.3.2
Installing rspec-expectations 3.3.1
Installing rspec-mocks 3.3.2
Installing rspec_junit_formatter 0.2.3
Using multi_json 1.11.2
Installing rspec 3.3.0
Installing rspec-its 1.2.0
Installing net-scp 1.2.1
Installing net-telnet 0.1.1
Installing sfl 2.2
Installing specinfra 2.44.0
Installing serverspec 2.24.1
Installing syslog-logger 1.6.8
Installing chef 12.5.1
Installing knife-solo 0.5.1
Using bundler 1.10.5
Bundle complete! 3 Gemfile dependencies, 77 gems now installed.
Use `bundle show [gemname]` to see where a bundled gem is installed.
Post-install message from knife-solo:
Thanks for installing knife-solo!

If you run into any issues please let us know at:
  https://github.com/matschaffer/knife-solo/issues

If you are upgrading knife-solo please uninstall any old versions by
running `gem clean knife-solo` to avoid any errors.

See http://bit.ly/CHEF-3255 for more information on the knife bug
that causes this.

権限が無くて途中パスワード聞かれたのだろうか?
パスワード入力して続行。
数分後、knife-soloをインストールしてくれてありがとうみたいな文字が見える。

$ bundle list | grep chef
  * chef (12.5.1)
  * chef-config (12.5.1)
  * chef-zero (4.3.2)
$ bundle list | grep knife
  * knife-solo (0.5.1)
$ bundle list | grep berkshelf
  * berkshelf (4.0.1)
  * berkshelf-api-client (2.0.0)

hosts登録

今後の運用を楽にするため
hostsファイルへ仮想マシンipアドレスに対応したホスト名を登録しておく

/etc/hosts
192.168.33.100  vm7

仮想マシンにChefをインストールする

knife solo bootstrapコマンドでインストールするそうだ

$ bundle exec knife solo bootstrap vagrant@vm7
WARNING: No knife configuration file found
Bootstrapping Chef...
vagrant@vm7's password: 
vagrant@vm7's password: 
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 18736  100 18736    0     0  11043      0  0:00:01  0:00:01 --:--:-- 11040
Downloading Chef 12.5.1 for el...
downloading https://www.opscode.com/chef/metadata?v=12.5.1&prerelease=false&nightlies=false&p=el&pv=7&m=x86_64
  to file /tmp/install.sh.4930/metadata.txt
trying wget...
url	https://opscode-omnibus-packages.s3.amazonaws.com/el/7/x86_64/chef-12.5.1-1.el7.x86_64.rpm
md5	9333136ba8a11bd6cad6d28fcd26a2c7
sha256	7a937d8c0ab68a1f342aba4ad33417fc4ba8cb1a71f46e4a18b5e76c363e4075
downloaded metadata file looks valid...
downloading https://opscode-omnibus-packages.s3.amazonaws.com/el/7/x86_64/chef-12.5.1-1.el7.x86_64.rpm
  to file /tmp/install.sh.4930/chef-12.5.1-1.el7.x86_64.rpm
trying wget...
Comparing checksum with sha256sum...
Installing Chef 12.5.1
installing with rpm...
警告: /tmp/install.sh.4930/chef-12.5.1-1.el7.x86_64.rpm: ヘッダー V4 DSA/SHA1 Signature、鍵 ID 83ef826a: NOKEY
準備しています...              ################################# [100%]
更新中 / インストール中...
   1:chef-12.5.1-1.el7                ################################# [100%]
Thank you for installing Chef!
Generating node config 'nodes/vm7.json'...
Running Chef on vm7...
Uploading the kitchen...
vagrant@vm7's password: 
vagrant@vm7's password: 
Saving password to keychain failed
vagrant@vm7's password: 
WARNING: Local cookbook_path '/Users/masa/vagrant/centos7/cookbooks' does not exist
WARNING: Local role_path './roles' does not exist
WARNING: Local data_bag_path './data_bags' does not exist
WARNING: Local environment_path './environments' does not exist
Generating solo config...
Running Chef: sudo chef-solo -c ~/chef-solo/solo.rb -j ~/chef-solo/dna.json
Starting Chef Client, version 12.5.1
Compiling Cookbooks...
Converging 0 resources

Running handlers:
Running handlers complete
Chef Client finished, 0/0 resources updated in 01 seconds

これまた参考サイトさんと同じく何度もパスワードを聞いてくるため、
適当に入力していた。正確にはvagrantと何度も・・・
ま、後でログインして変更しますがね。

仮想マシンにログインしてバージョンを確認

$ vagrant ssh
Last login: Thu Oct 15 11:22:56 2015 from 192.168.33.1
Welcome to your Vagrant-built virtual machine.
[vagrant@vmcentos7 ~]$ knife -v
Chef: 12.5.1

Chefクックブックの作成

クックブックの雛形を作成
$ bundle exec knife solo init .
Creating kitchen...
Creating knife.rb in kitchen...
Creating cupboards...
$ ls
Gemfile		Vagrantfile	data_bags	nodes		site-cookbooks
Gemfile.lock	cookbooks	environments	roles

↑これだけしかファイルないけど大丈夫なのか?
ま、動けばいいか

apacheのクックブックを作成

$ bundle exec knife cookbook create apache -o site-cookbooks
** Creating cookbook apache in /Users/masa/vagrant/centos7/site-cookbooks
** Creating README for cookbook: apache
** Creating CHANGELOG for cookbook: apache
** Creating metadata for cookbook: apache

apacheレシピ作成


以下のように編集する

site-cookbooks/apache/recipes/default.rb
package "httpd" do
  action :install
end
service "httpd" do
  action [ :enable, :start ]
end

node情報記載

nodes/vm7.jsonapacheレシピを追記する
{
  "run_list": ["recipe[apache]"],
  "automatic": {
    "ipaddress": "vmdev"
  }
}

Chef-soloを実行してapacheをインストールする

$ bundle exec knife solo cook vagrant@vm7
Running Chef on vm7...
Checking Chef version...
vagrant@vm7's password: 
vagrant@vm7's password: 
Uploading the kitchen...
Saving password to keychain failed
vagrant@vm7's password: 
Generating solo config...
Running Chef: sudo chef-solo -c ~/chef-solo/solo.rb -j ~/chef-solo/dna.json
Starting Chef Client, version 12.5.1
Compiling Cookbooks...
Converging 2 resources
Recipe: apache::default
  * yum_package[httpd] action install
    - install version 2.4.6-31.el7.centos.1 of package httpd
  * service[httpd] action enable
    - enable service service[httpd]
  * service[httpd] action start
    - start service service[httpd]

Running handlers:
Running handlers complete
Chef Client finished, 3/3 resources updated in 10 seconds

何度目かのパスワード問答
もういいよ。。。

仮想マシンにログインしてapacheがインストールされたかを確認

$ vagrant ssh
Last login: Fri Oct 16 05:44:07 2015 from 192.168.33.1
Welcome to your Vagrant-built virtual machine.
[vagrant@vmcentos7 ~]$ ps -ef |grep httpd
root      4661     1  0 05:44 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
apache    4662  4661  0 05:44 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
apache    4663  4661  0 05:44 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
apache    4664  4661  0 05:44 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
apache    4665  4661  0 05:44 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
apache    4666  4661  0 05:44 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
vagrant   4697  4673  0 05:48 pts/0    00:00:00 grep --color=auto httpd

apacheが起動してる。

まとめ

長い道のりだったが、ひとまずChefとVagrantのインストールと起動・確認ができた。
apacheも動いたから当初の目標は達成した。
基盤のみ構築しておけばシステム屋さんも一行コピーして構築ということができる。
次回はDockerあたりを触ってみたいと思う。

*1:本当は参考にさせていただいたサイトさんがCentOS7を使っていたからというのが 大部分を占めるわけだが

*2:*2015年10月12日現在