おっさんエンジニアの忘備録

Linux系の各種作業を自分用の忘備録として残しています

Vagrant + Chefでの環境構築自動化

Vagrantで仮想環境の構築を行うタイミングで、環境構築も一緒に出来るようにします。
今回の例ではnginxをインストール&起動するようにしています。

環境

◆ホストOS(RHEL6.7)
◆ゲストOS(CentOS6.7)
◆Chef: 12.9.38 ※既にVagrantに追加している「centos67」というBOXを利用します

検証用のディレクトリ作成

今回は「/root/chef-test」ディレクトリを作成しています。

# cd
# mkdir chef-test

この中にVagrantfileやchefの各ファイルを格納することとします。

Gemfile作成

# cd /root/chef-test
# vi Gemfile
source 'https://rubygems.org'

gem 'chef'
gem 'knife-solo'
gem 'berkshelf'

Gemのインストール

# cd /root/chef-test
# bundle install
Don't run Bundler as root. Bundler can ask for sudo if it is needed, and installing your
bundle as root will break this application for all non-root users on this machine.
Fetching gem metadata from https://rubygems.org/.........
Fetching version metadata from https://rubygems.org/...
Fetching dependency metadata from https://rubygems.org/..
Resolving dependencies.....
Using addressable 2.4.0
Using multipart-post 2.0.0
Using httpclient 2.7.2
Using buff-extensions 1.0.0
Installing hashie 3.4.4
Using buff-ignore 1.1.1
Using buff-ruby_engine 0.1.0
Installing hitimes 1.2.4 with native extensions
Using nio4r 1.2.1
Using fuzzyurl 0.8.0
Using mixlib-config 2.2.1
Using mixlib-shellout 2.2.6
Using erubis 2.7.0
Using json 1.8.3
Using mixlib-log 1.6.0
Using rspec-support 3.4.1
Using diff-lcs 1.2.5
Using retryable 2.0.3
Using semverse 1.2.1
Using cleanroom 1.0.0
Using minitar 0.5.4
Installing molinillo 0.4.5
Using thor 0.19.1
Using builder 3.2.2
Using bundler 1.11.2
Using libyajl2 1.2.0
Using rack 1.6.4
Using uuidtools 2.1.5
Using highline 1.7.8
Installing mixlib-cli 1.6.0
Using net-ssh 2.9.4
Using ffi 1.9.10
Using ipaddress 0.8.3
Using plist 3.2.0
Using systemu 2.6.5
Using wmi-lite 1.0.0
Using proxifier 1.0.3
Installing multi_json 1.12.0
Using net-telnet 0.1.1
Using sfl 2.2
Using syslog-logger 1.6.8
Using faraday 0.9.2
Using varia_model 0.4.1
Using buff-shell_out 0.2.0
Using timers 4.0.4
Installing chef-config 12.9.41
Using rspec-core 3.4.4
Using rspec-expectations 3.4.0
Using rspec-mocks 3.4.1
Using solve 2.0.3
Using ffi-yajl 2.2.3
Using net-sftp 2.1.2
Using net-ssh-gateway 1.2.0
Using net-scp 1.2.1
Using sawyer 0.7.0
Using buff-config 1.0.1
Using celluloid 0.16.0
Using rspec_junit_formatter 0.2.3
Using rspec-its 1.2.0
Using mixlib-authentication 1.4.0
Using rspec 3.4.0
Installing chef-zero 4.6.2
Installing ohai 8.15.1
Using net-ssh-multi 1.2.1
Installing specinfra 2.57.2
Using octokit 4.3.0
Using celluloid-io 0.16.2
Installing serverspec 2.34.0
Using ridley 4.5.0
Installing chef 12.9.41
Using berkshelf-api-client 2.0.2
Using knife-solo 0.5.1
Using berkshelf 4.3.2
Bundle complete! 3 Gemfile dependencies, 73 gems now installed.
Use `bundle show [gemname]` to see where a bundled gem is installed.
# ls -l
合計 12
-rw-r--r-- 1 root root   76  5月  6 13:33 2016 Gemfile
-rw-r--r-- 1 root root 5219  5月  6 13:37 2016 Gemfile.lock

vagrant 初期化(Vagrantfileの作成)

# cd /root/chef-test
# vagrant init centos67
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.
[root@124x39x29x22 chef-test]# ls -l
合計 16
-rw-r--r-- 1 root root   76  5月  6 13:33 2016 Gemfile
-rw-r--r-- 1 root root 5219  5月  6 13:37 2016 Gemfile.lock
-rw-r--r-- 1 root root 3020  5月  6 13:45 2016 Vagrantfile

nginx用のクックブック作成

# cd /root/chef-test
# bundle exec knife cookbook create nginx -o ./site-cookbooks
** Creating cookbook nginx in /root/chef-test/site-cookbooks
** Creating README for cookbook: nginx
** Creating CHANGELOG for cookbook: nginx
** Creating metadata for cookbook: nginx
# ls -l
合計 24
-rw-r--r-- 1 root root   84  5月  6 14:22 2016 Berksfile
-rw-r--r-- 1 root root   76  5月  6 13:33 2016 Gemfile
-rw-r--r-- 1 root root 5219  5月  6 13:37 2016 Gemfile.lock
-rw-r--r-- 1 root root 3079  5月  6 13:58 2016 Vagrantfile
drwxr-xr-x 4 root root 4096  5月  6 14:29 2016 site-cookbooks
# cd site-cookbooks/
# ls -l
合計 8
drwxr-xr-x 10 root root 4096  5月  6 14:29 2016 nginx

nginx用のレシピ作成

# vi /root/chef-test/site-cookbooks/nginx/recipes/default.rb
#
# Cookbook Name:: nginx
# Recipe:: default
#
# Copyright 2016, YOUR_COMPANY_NAME
#
# All rights reserved - Do Not Redistribute
#

include_recipe "yum-epel"

package "nginx" do
    action :install
end

service "nginx" do
    action [ :enable, :start]
    supports :status => true, :restart => true, :reload => true
end

コンフィグの内容は以下の通りです。
(1)「yum-epel」より「nginx」をインストール
(2)「nginx」を自動起動
(3)「nginx」を起動
(4)「nginx」のサービスに関して「status」「restart」「reload」を有効とする

クックブックの依存関係の定義(Berksfileの編集)

# vi /root/chef-test/Berksfile
site :opscode

cookbook "yum-epel"
cookbook "nginx", path: "./site-cookbooks/nginx"

yum-epel」は「cookbooks」ディレクトリ内のレシピを使い、nginxは「site-cookbooks」ディレクトリ内のレシピを使用します。

クックブックのダウンロード

# cd /root/chef-test
# berks vendor ./cookbooks
DEPRECATED: Your Berksfile contains a site location pointing to the Opscode Community Site (site :opscode). Site locations have been replaced by the source location. Change this to: 'source "https://supermarket.chef.io"' to remove this warning. For more information visit https://github.com/berkshelf/berkshelf/wiki/deprecated-locations
Resolving cookbook dependencies...
Fetching 'nginx' from source at site-cookbooks/nginx
Fetching cookbook index from https://supermarket.chef.io...
Using yum-epel (0.7.0)
Using yum (3.10.0)
Using nginx (0.1.0) from source at site-cookbooks/nginx
Vendoring nginx (0.1.0) to ./cookbooks/nginx
Vendoring yum (3.10.0) to ./cookbooks/yum
Vendoring yum-epel (0.7.0) to ./cookbooks/yum-epel
# ls -l
合計 32
-rw-r--r-- 1 root root   84  5月  6 14:22 2016 Berksfile
-rw------- 1 root root  139  5月  6 14:31 2016 Berksfile.lock
-rw-r--r-- 1 root root   76  5月  6 13:33 2016 Gemfile
-rw-r--r-- 1 root root 5219  5月  6 13:37 2016 Gemfile.lock
-rw-r--r-- 1 root root 3079  5月  6 13:58 2016 Vagrantfile
drwxr-xr-x 5 root root 4096  5月  6 14:31 2016 cookbooks
drwxr-xr-x 4 root root 4096  5月  6 14:29 2016 site-cookbooks
# cd cookbooks/
# ls -l
合計 12
drwxr-xr-x 10 root root 4096  5月  6 14:31 2016 nginx
drwxr-xr-x  8 root root 4096  5月  6 14:31 2016 yum
drwxr-xr-x  4 root root 4096  5月  6 14:31 2016 yum-epel

「cookbooks」ディレクトリ内にクックブックがコピーされます。

vagrant-omnibusプラグインのインストール

Vagrantを起動するときにChef Client/Chef Soloがインストールされていなければ自動でインストールさせるため、プラグインをインストールします。

# cd /root/chef-test
# vagrant plugin install vagrant-omnibus
Installing the 'vagrant-omnibus' plugin. This can take a few minutes...
Installed the plugin 'vagrant-omnibus (1.4.1)'!

Vagrantfile修正

# vi /root/chef-test/Vagrantfile
Vagrant.configure(2) do |config|
   ・
   ・
  # カスタマイズ用
  # IPアドレスの設定
  config.vm.network "private_network", ip: "192.168.33.13"

  # ポートフォワードの設定
  config.vm.network "forwarded_port", guest: 80, host: 8888

  # vagrant-omnibusの有効化
  config.omnibus.chef_version = :latest

  # プロビジョニング
  config.vm.provision :chef_solo do |chef|
    chef.cookbooks_path = ["./cookbooks", "./site-cookbooks"]
    chef.run_list = %w[
      recipe[yum-epel]
      recipe[nginx]
    ]
  end
end

赤字の箇所を追記します。

vagrant起動

# cd /root/chef-test
# vagrant up --provision

ブラウザで確認

f:id:saosao_0706:20160509174243p:plain
正常に構築が完了していれば上記のような画面が表示されます。

VagrantでマルチVM

vegrantで複数VMを立ち上げてお互いに通信させる方法をメモしておきます。

環境(前提条件)

◆以下の手順に沿って単体のVMは構築済みです。今回はこちらで構築したCentOS6.7のVM(ゲストOS)を複数立ち上げます。
saosao-0706.hatenablog.com
◆Vagrantfileの格納されているディレクトリ(ホストOS)の場所は「/root/vagrant/centos67」です。

Vagrantfile変更

# vi /root/vagrant/centos67/Vagrantfile
              ・
              ・
  config.vm.define :node1 do |node1|
    node1.vm.network "private_network", ip: "192.168.33.10"
  end

  config.vm.define :node2 do |node2|
    node2.vm.network "private_network", ip: "192.168.33.11"
  end

上記の4行を追加してnode単位に内部ネットワーク用のIPアドレスを付与するようにします。

一旦構築したVMを削除

# cd /root/vagrant/centos67/
# vagrant destroy

VM(ゲストOS)の起動

# cd /root/vagrant/centos67/
# vagrant up
Bringing machine 'node1' up with 'virtualbox' provider...
Bringing machine 'node2' up with 'virtualbox' provider...
==> node1: Importing base box 'centos67'...
==> node1: Matching MAC address for NAT networking...
==> node1: Setting the name of the VM: centos67_node1_1462177540423_22245
==> node1: Fixed port collision for 22 => 2222. Now on port 2202.
==> node1: Clearing any previously set network interfaces...
==> node1: Preparing network interfaces based on configuration...
    node1: Adapter 1: nat
    node1: Adapter 2: hostonly
==> node1: Forwarding ports...
    node1: 22 (guest) => 2202 (host) (adapter 1)
==> node1: Booting VM...
==> node1: Waiting for machine to boot. This may take a few minutes...
    node1: SSH address: 127.0.0.1:2202
    node1: SSH username: vagrant
    node1: SSH auth method: private key
    node1: Warning: Remote connection disconnect. Retrying...
    node1:
    node1: Vagrant insecure key detected. Vagrant will automatically replace
    node1: this with a newly generated keypair for better security.
    node1:
    node1: Inserting generated public key within guest...
    node1: Removing insecure key from the guest if it's present...
    node1: Key inserted! Disconnecting and reconnecting using new SSH key...
==> node1: Machine booted and ready!
==> node1: Checking for guest additions in VM...
    node1: The guest additions on this VM do not match the installed version of
    node1: VirtualBox! In most cases this is fine, but in rare cases it can
    node1: prevent things such as shared folders from working properly. If you see
    node1: shared folder errors, please make sure the guest additions within the
    node1: virtual machine match the version of VirtualBox you have installed on
    node1: your host and reload your VM.
    node1:
    node1: Guest Additions Version: 4.3.30
    node1: VirtualBox Version: 5.0
==> node1: Configuring and enabling network interfaces...
==> node1: Mounting shared folders...
    node1: /vagrant => /root/vagrant/centos67
==> node2: Importing base box 'centos67'...
==> node2: Matching MAC address for NAT networking...
==> node2: Setting the name of the VM: centos67_node2_1462177592736_21927
==> node2: Fixed port collision for 22 => 2222. Now on port 2203.
==> node2: Clearing any previously set network interfaces...
==> node2: Preparing network interfaces based on configuration...
    node2: Adapter 1: nat
    node2: Adapter 2: hostonly
==> node2: Forwarding ports...
    node2: 22 (guest) => 2203 (host) (adapter 1)
==> node2: Booting VM...
==> node2: Waiting for machine to boot. This may take a few minutes...
    node2: SSH address: 127.0.0.1:2203
    node2: SSH username: vagrant
    node2: SSH auth method: private key
    node2: Warning: Remote connection disconnect. Retrying...
    node2:
    node2: Vagrant insecure key detected. Vagrant will automatically replace
    node2: this with a newly generated keypair for better security.
    node2:
    node2: Inserting generated public key within guest...
    node2: Removing insecure key from the guest if it's present...
    node2: Key inserted! Disconnecting and reconnecting using new SSH key...
==> node2: Machine booted and ready!
==> node2: Checking for guest additions in VM...
    node2: The guest additions on this VM do not match the installed version of
    node2: VirtualBox! In most cases this is fine, but in rare cases it can
    node2: prevent things such as shared folders from working properly. If you see
    node2: shared folder errors, please make sure the guest additions within the
    node2: virtual machine match the version of VirtualBox you have installed on
    node2: your host and reload your VM.
    node2:
    node2: Guest Additions Version: 4.3.30
    node2: VirtualBox Version: 5.0
==> node2: Configuring and enabling network interfaces...
==> node2: Mounting shared folders...
    node2: /vagrant => /root/vagrant/centos67

2つのVMが起動しています。

ホストOSからPINGを打ってみる

# ping 192.168.33.10
PING 192.168.33.10 (192.168.33.10) 56(84) bytes of data.
64 bytes from 192.168.33.10: icmp_seq=1 ttl=64 time=8.46 ms
64 bytes from 192.168.33.10: icmp_seq=2 ttl=64 time=0.184 ms
64 bytes from 192.168.33.10: icmp_seq=3 ttl=64 time=0.158 ms
64 bytes from 192.168.33.10: icmp_seq=4 ttl=64 time=0.298 ms
^C
--- 192.168.33.10 ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3312ms
rtt min/avg/max/mdev = 0.158/2.277/8.469/3.575 ms


# ping 192.168.33.11
PING 192.168.33.11 (192.168.33.11) 56(84) bytes of data.
64 bytes from 192.168.33.11: icmp_seq=1 ttl=64 time=0.673 ms
64 bytes from 192.168.33.11: icmp_seq=2 ttl=64 time=0.197 ms
64 bytes from 192.168.33.11: icmp_seq=3 ttl=64 time=0.235 ms
64 bytes from 192.168.33.11: icmp_seq=4 ttl=64 time=0.231 ms
^C
--- 192.168.33.11 ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3981ms
rtt min/avg/max/mdev = 0.197/0.334/0.673/0.196 ms

問題なさそうです。

SSHの設定

ホストOSからゲストOSにSSHログインする際にオプションを付けずにログインできるようにしておきます。

# cd /root/vagrant/centos67/
# vagrant ssh-config --host 192.168.33.10 node1 >> ~/.ssh/config
# vagrant ssh-config --host 192.168.33.11 node2 >> ~/.ssh/config
# cat ~/.ssh/config
Host 192.168.33.10
  HostName 127.0.0.1
  User vagrant
  Port 2202
  UserKnownHostsFile /dev/null
  StrictHostKeyChecking no
  PasswordAuthentication no
  IdentityFile "/root/vagrant/centos67/.vagrant/machines/node1/virtualbox/private_key"
  IdentitiesOnly yes
  LogLevel FATAL

Host 192.168.33.11
  HostName 127.0.0.1
  User vagrant
  Port 2203
  UserKnownHostsFile /dev/null
  StrictHostKeyChecking no
  PasswordAuthentication no
  IdentityFile "/root/vagrant/centos67/.vagrant/machines/node2/virtualbox/private_key"
  IdentitiesOnly yes
  LogLevel FATAL

ちょっと分かりずらいのですが、

# vagrant ssh --host [IPアドレス] [ノード名] 

で各ノードのSSH情報をHostをIPアドレス名に変換した形で標準出力に出力し、
その出力結果をrootユーザの「.ssh/config」に書き込んでいます。

SSHログイン確認

# ssh 192.168.33.10
Last login: Mon May  2 09:50:35 2016 from 10.0.2.2
[vagrant@localhost ~]$ exit
logout
Connection to 127.0.0.1 closed.
# ssh 192.168.33.11
Last login: Mon May  2 09:50:39 2016 from 10.0.2.2

問題なくSSHログインできます。

ゲストOS同士のPING確認

# ssh 192.168.33.10
Last login: Mon May  2 09:53:02 2016 from 10.0.2.2
[vagrant@localhost ~]$ ping 192.168.33.11      ※node1⇒node2へのPING
PING 192.168.33.11 (192.168.33.11) 56(84) bytes of data.
64 bytes from 192.168.33.11: icmp_seq=1 ttl=64 time=0.411 ms
64 bytes from 192.168.33.11: icmp_seq=2 ttl=64 time=0.331 ms
64 bytes from 192.168.33.11: icmp_seq=3 ttl=64 time=0.371 ms
64 bytes from 192.168.33.11: icmp_seq=4 ttl=64 time=0.421 ms
e64 bytes from 192.168.33.11: icmp_seq=5 ttl=64 time=0.378 ms
^C
--- 192.168.33.11 ping statistics ---
5 packets transmitted, 5 received, 0% packet loss, time 4458ms
rtt min/avg/max/mdev = 0.331/0.382/0.421/0.036 ms
[vagrant@localhost ~]$ exit
logout
Connection to 127.0.0.1 closed.
# ssh 192.168.33.11
Last login: Mon May  2 09:53:07 2016 from 10.0.2.2
[vagrant@localhost ~]$ ping 192.168.33.10      ※node2⇒node1へのPING
PING 192.168.33.10 (192.168.33.10) 56(84) bytes of data.
64 bytes from 192.168.33.10: icmp_seq=1 ttl=64 time=0.291 ms
64 bytes from 192.168.33.10: icmp_seq=2 ttl=64 time=0.316 ms
64 bytes from 192.168.33.10: icmp_seq=3 ttl=64 time=0.237 ms
64 bytes from 192.168.33.10: icmp_seq=4 ttl=64 time=0.313 ms
^C
--- 192.168.33.10 ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3246ms
rtt min/avg/max/mdev = 0.237/0.289/0.316/0.033 ms

問題なさそうです。

【chef】knife-soloでchef-soloをリモート実行(Apache+MySQL)

【chef】knife-soloでchef-soloをリモート実行saosao-0706.hatenablog.com

先日こちらの記事を書かせていただきましたが、こちらの環境で今度はApacheMysqlをセットアップしてみたいと思います。

環境

上記の記事をご参照ください。

apacheMySQL用のcookbookを作成

# cd /root/vagrant/centos67
# knife cookbook create apache -o site-cookbooks
** Creating cookbook apache in /root/vagrant/centos67/site-cookbooks
** Creating README for cookbook: apache
** Creating CHANGELOG for cookbook: apache
** Creating metadata for cookbook: apache
# knife cookbook create mysql -o site-cookbooks
** Creating cookbook mysql in /root/vagrant/centos67/site-cookbooks
** Creating README for cookbook: mysql
** Creating CHANGELOG for cookbook: mysql
** Creating metadata for cookbook: mysql
# cd /root/vagrant/centos67/site-cookbooks/
# ls -l
合計 12
drwxr-xr-x 10 root root 4096  4月 26 16:50 2016 apache
drwxr-xr-x 10 root root 4096  4月 26 09:48 2016 dovecot
drwxr-xr-x 10 root root 4096  4月 26 16:50 2016 mysql

「site-cookbooks」ディレクトリ内にcookbookが生成されます。
「/root/vagrant/centos67」はsite-cookbooksがあるディレクトリです。

Nodeオブジェクト(ランリスト)の編集

# vi /root/vagrant/centos67/nodes/192.168.33.10.json
{
  "run_list": [
    "recipe[dovecot]",
    "recipe[apache]",
    "recipe[mysql]"
  ],
  "automatic": {
    "ipaddress": "192.168.33.10"
  }
}

こちらを追加することで、knife-solo実行時にApacheMySQL用のレシピが実行されます。

apacheのレシピを書く

# vi /root/vagrant/centos67/site-cookbooks/apache/recipes/default.rb
#
# Cookbook Name:: apache
# Recipe:: default
#
# Copyright 2016, YOUR_COMPANY_NAME
#
# All rights reserved - Do Not Redistribute
#
package "httpd" do
    action :install
end

service "httpd" do
    action [ :enable, :start]
end

赤字の行を追加します。
上記のレシピの意味は以下の通りです。
◆action :install
apacheのインストール
◆action [ :enable, :start]
enableはOS起動時のサービス有効化(chkconfig httpd on)、startはサービスの起動(service httpd start)

mysqlのレシピを書く

# vi /root/vagrant/centos67/site-cookbooks/mysql/recipes/default.rb
#
# Cookbook Name:: mysql
# Recipe:: default
#
# Copyright 2016, YOUR_COMPANY_NAME
#
# All rights reserved - Do Not Redistribute
#
package "mysql-server" do
    action :install
end

service "mysqld" do
    action [ :enable, :start]
end

赤字の行を追加します。
上記のレシピの意味は以下の通りです。

knife-solo実行

# cd /root/vagrant/centos67
# knife solo cook 192.168.33.10
Running Chef on 192.168.33.10...
Checking Chef version...
/root/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/net-ssh-2.9.4/lib/net/ssh/transport/session.rb:67:in `initialize': Object#timeout is deprecated, use Timeout.timeout instead.
/root/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/net-ssh-2.9.4/lib/net/ssh/transport/session.rb:84:in `initialize': Object#timeout is deprecated, use Timeout.timeout instead.
/root/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/net-ssh-2.9.4/lib/net/ssh/transport/session.rb:67:in `initialize': Object#timeout is deprecated, use Timeout.timeout instead.
/root/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/net-ssh-2.9.4/lib/net/ssh/transport/session.rb:84:in `initialize': Object#timeout is deprecated, use Timeout.timeout instead.
Installing Berkshelf cookbooks to 'cookbooks'...
Resolving cookbook dependencies...
Uploading the kitchen...
WARNING: Local cookbook_path '/root/vagrant/centos67/cookbooks' 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.9.38
Installing Cookbook Gems:
Compiling Cookbooks...
Converging 5 resources
Recipe: dovecot::default
  * yum_package[dovecot] action install (up to date)
Recipe: apache::default
  * yum_package[httpd] action install
    - install version 2.2.15-47.el6.centos.4 of package httpd
  * service[httpd] action enable
    - enable service service[httpd]
  * service[httpd] action start
    - start service service[httpd]
Recipe: mysql::default
  * yum_package[mysql-server] action install
    - install version 5.1.73-5.el6_7.1 of package mysql-server
  * service[mysqld] action enable
    - enable service service[mysqld]
  * service[mysqld] action start
    - start service service[mysqld]

Running handlers:
Running handlers complete
Chef Client finished, 6/7 resources updated in 24 seconds

ApacheMySQLの作業を行った旨のログが出力されます。

ゲストOSにログインして確認

 
# ssh 192.168.33.10
Last login: Thu Apr 28 05:36:54 2016 from 10.0.2.2
$ ps -ef | grep httpd
root      4747     1  0 05:37 ?        00:00:00 /usr/sbin/httpd
apache    4749  4747  0 05:37 ?        00:00:00 /usr/sbin/httpd
apache    4750  4747  0 05:37 ?        00:00:00 /usr/sbin/httpd
apache    4751  4747  0 05:37 ?        00:00:00 /usr/sbin/httpd
apache    4752  4747  0 05:37 ?        00:00:00 /usr/sbin/httpd
apache    4753  4747  0 05:37 ?        00:00:00 /usr/sbin/httpd
apache    4754  4747  0 05:37 ?        00:00:00 /usr/sbin/httpd
apache    4755  4747  0 05:37 ?        00:00:00 /usr/sbin/httpd
apache    4756  4747  0 05:37 ?        00:00:00 /usr/sbin/httpd
vagrant   5093  5077  0 05:38 pts/0    00:00:00 grep httpd
$ ps -ef | grep mysql
root      4955     1  0 05:37 ?        00:00:00 /bin/sh /usr/bin/mysqld_safe --datadir=/var/lib/mysql --socket=/var/lib/mysql/mysql.sock --pid-file=/var/run/mysqld/mysqld.pid --basedir=/usr --user=mysql
mysql     5057  4955  0 05:37 ?        00:00:00 /usr/libexec/mysqld --basedir=/usr --datadir=/var/lib/mysql --user=mysql --log-error=/var/log/mysqld.log --pid-file=/var/run/mysqld/mysqld.pid --socket=/var/lib/mysql/mysql.sock
vagrant   5095  5077  0 05:38 pts/0    00:00:00 grep mysql
$ chkconfig --list | grep httpd
httpd           0:off   1:off   2:on    3:on    4:on    5:on    6:off
$ chkconfig --list | grep mysql
mysqld          0:off   1:off   2:on    3:on    4:on    5:on    6:off

ApacheMySQLがインストールされ、サービスが起動しています。
また、OS起動時にサービスが起動する設定となっています。

ちなみに、knife-solo実行時に文法エラーがあった場合は以下のようなエラーメッセージが出力されます。

# knife solo cook 192.168.33.10
Running Chef on 192.168.33.10...
Checking Chef version...
/root/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/net-ssh-2.9.4/lib/net/ssh/transport/session.rb:67:in `initialize': Object#timeout is deprecated, use Timeout.timeout instead.
/root/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/net-ssh-2.9.4/lib/net/ssh/transport/session.rb:84:in `initialize': Object#timeout is deprecated, use Timeout.timeout instead.
/root/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/net-ssh-2.9.4/lib/net/ssh/transport/session.rb:67:in `initialize': Object#timeout is deprecated, use Timeout.timeout instead.
/root/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/net-ssh-2.9.4/lib/net/ssh/transport/session.rb:84:in `initialize': Object#timeout is deprecated, use Timeout.timeout instead.
ERROR: JSON::ParserError: 419: unexpected token at '"recipe[apache]"
        "recipe[mysql]"
  ],
  "automatic": {
    "ipaddress": "192.168.33.10"
  }
}

【chef】knife-soloでchef-soloをリモート実行

今回はVagrantで構築したゲストOSに対してknife-soloを使ってchef-soloをリモート実行してみます

環境

◆ホストOS(RHEL6.7)
◆ゲストOS(CentOS6.7)
※1、Vagrantで仮想環境を構築
※2、内部IPアドレスは192.168.33.10
※3、ホストOS(ユーザ:root)からゲストOS(ユーザ:vagrant)へのSSHはパスワードなしでログインできる

必要なモジュールのインストール(ホストOS)

# gem install knife-solo
# gem install berkshelf

「knife-solo」は作業用マシン上に用意したCookbookなどの設定ファイルを設定対象のマシンにコピーし、 設定対象のマシン上でchef-soloコマンドを実行する、という一連の作業を自動実行するツールです。
設定ファイルのコピーにはrsyncが、chef-soloコマンドの実行にはsshを使います。
「berkshelf」は定義ファイルに使うcookbookを定義しておけば、リポジトリから勝手に依存関係を解消 した上で落としてきてくれるツールのようです。

リポジトリ作成(ホストOS)

Vagrantfileがあるディレクトリ上にリポジトリを作成します

# cd /root/vagrant/centos67
# knife solo init .
WARNING: No knife configuration file found
Creating kitchen...
Creating knife.rb in kitchen...
Creating cupboards...
Setting up Berkshelf...
# ls -l
合計 32
-rw-r--r-- 1 root root   35  4月 26 09:37 2016 Berksfile
-rw-r--r-- 1 root root 3080  4月 25 16:04 2016 Vagrantfile
drwxr-xr-x 2 root root 4096  4月 26 09:37 2016 cookbooks
drwxr-xr-x 2 root root 4096  4月 26 09:37 2016 data_bags
drwxr-xr-x 2 root root 4096  4月 26 09:37 2016 environments
drwxr-xr-x 2 root root 4096  4月 26 09:37 2016 nodes
drwxr-xr-x 2 root root 4096  4月 26 09:37 2016 roles
drwxr-xr-x 2 root root 4096  4月 26 09:37 2016 site-cookbooks

リポジトリ関連のファイルが生成されます

ゲストOSにChef Soloのインストール(ホストOS)

「knife solo bootstrap [ホスト名 or IPアドレス]」コマンドを実行します。
「knife solo bootstrap」コマンドは、knife solo prepareによるChefのインストールとknife solo cookによるカレントリポジトリのアップロード とchef-soloの実行を同時に実施してくれるコマンドとなります。

# knife solo bootstrap 192.168.33.10
Bootstrapping Chef...
/root/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/net-ssh-2.9.4/lib/net/ssh/transport/session.rb:67:in `initialize': Object#timeout is deprecated, use Timeout.timeout instead.
/root/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/net-ssh-2.9.4/lib/net/ssh/transport/session.rb:84:in `initialize': Object#timeout is deprecated, use Timeout.timeout instead.
/root/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/net-ssh-2.9.4/lib/net/ssh/transport/session.rb:67:in `initialize': Object#timeout is deprecated, use Timeout.timeout instead.
/root/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/net-ssh-2.9.4/lib/net/ssh/transport/session.rb:84:in `initialize': Object#timeout is deprecated, use Timeout.timeout instead.
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 19602  100 19602    0     0  18652      0  0:00:01  0:00:01 --:--:-- 67593
el 6 x86_64
Getting information for chef stable 12.9.38 for el...
downloading https://omnitruck-direct.chef.io/stable/chef/metadata?v=12.9.38&p=el&pv=6&m=x86_64
  to file /tmp/install.sh.2869/metadata.txt
trying wget...
sha1    2b859af3d6e99502b7a1d75671a4f629a224e9ad
sha256  0aca8e46ff8ada7af09b0d65b6f7738eb7b25d269482000be1dee7aaba154011
url     https://packages.chef.io/stable/el/6/chef-12.9.38-1.el6.x86_64.rpm
version 12.9.38
downloaded metadata file looks valid...
downloading https://packages.chef.io/stable/el/6/chef-12.9.38-1.el6.x86_64.rpm
  to file /tmp/install.sh.2869/chef-12.9.38-1.el6.x86_64.rpm
trying wget...
Comparing checksum with sha256sum...
Installing chef 12.9.38
installing with rpm...
警告: /tmp/install.sh.2869/chef-12.9.38-1.el6.x86_64.rpm: ヘッダ V4 DSA/SHA1 Signature, key ID 83ef826a: NOKEY
準備中...                ########################################### [100%]
   1:chef                   ########################################### [100%]
Thank you for installing Chef!
Generating node config 'nodes/192.168.33.10.json'...
Running Chef on 192.168.33.10...
Installing Berkshelf cookbooks to 'cookbooks'...
Resolving cookbook dependencies...
Uploading the kitchen...
/root/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/net-ssh-2.9.4/lib/net/ssh/transport/session.rb:67:in `initialize': Object#timeout is deprecated, use Timeout.timeout instead.
/root/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/net-ssh-2.9.4/lib/net/ssh/transport/session.rb:84:in `initialize': Object#timeout is deprecated, use Timeout.timeout instead.
/root/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/net-ssh-2.9.4/lib/net/ssh/transport/session.rb:67:in `initialize': Object#timeout is deprecated, use Timeout.timeout instead.
/root/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/net-ssh-2.9.4/lib/net/ssh/transport/session.rb:84:in `initialize': Object#timeout is deprecated, use Timeout.timeout instead.
WARNING: Local cookbook_path '/root/vagrant/centos67/cookbooks' 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.9.38
Installing Cookbook Gems:
Compiling Cookbooks...
Converging 0 resources

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

ゲストOSにログインして確認

# ssh 192.168.33.10
Last login: Tue Apr 26 01:43:34 2016 from 10.0.2.2
[vagrant@localhost ~]$ che           (tabキーを押して補完表示させてます)
checkmodule  checkpolicy  chef-apply   chef-client  chef-shell   chef-solo/

chef solo関連のプログラムが表示されています

クックブックの作成(ホストOS)

# cd /root/vagrant/centos67
# knife cookbook create dovecot -o site-cookbooks
** Creating cookbook dovecot in /root/vagrant/centos67/site-cookbooks
** Creating README for cookbook: dovecot
** Creating CHANGELOG for cookbook: dovecot
** Creating metadata for cookbook: dovecot

レシピの編集(ホストOS)

# vi /root/vagrant/centos67/site-cookbooks/dovecot/recipes/default.rb
#
# Cookbook Name:: dovecot
# Recipe:: default
#
# Copyright 2016, YOUR_COMPANY_NAME
#
# All rights reserved - Do Not Redistribute
#
package "dovecot" do
        action :install
end

上記の3行を追加します。
上記はdovecotをインストールするレシピとなります。

ノードオブジェクト(ランリスト)の修正(ホストOS)

# vi /root/vagrant/centos67/nodes/192.168.33.10.json
{
  "run_list": [
    "recipe[dovecot]"
  ],
  "automatic": {
    "ipaddress": "192.168.33.10"
  }
}

上記の1行を追加します。
上記を記述することにより「knife-solo」コマンド実行時にクックブックを明示的に指定する必要が無くなります。

knife-solo実行(ホストOS)

# cd /root/vagrant/centos67
# knife solo cook 192.168.33.10
Running Chef on 192.168.33.10...
Checking Chef version...
/root/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/net-ssh-2.9.4/lib/net/ssh/transport/session.rb:67:in `initialize': Object#timeout is deprecated, use Timeout.timeout instead.
/root/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/net-ssh-2.9.4/lib/net/ssh/transport/session.rb:84:in `initialize': Object#timeout is deprecated, use Timeout.timeout instead.
/root/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/net-ssh-2.9.4/lib/net/ssh/transport/session.rb:67:in `initialize': Object#timeout is deprecated, use Timeout.timeout instead.
/root/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/net-ssh-2.9.4/lib/net/ssh/transport/session.rb:84:in `initialize': Object#timeout is deprecated, use Timeout.timeout instead.
Installing Berkshelf cookbooks to 'cookbooks'...
Resolving cookbook dependencies...
Uploading the kitchen...
WARNING: Local cookbook_path '/root/vagrant/centos67/cookbooks' 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.9.38
Installing Cookbook Gems:
Compiling Cookbooks...
Converging 1 resources
Recipe: dovecot::default
  * yum_package[dovecot] action install
    - install version 2.0.9-19.el6_7.2 of package dovecot

Running handlers:
Running handlers complete
Chef Client finished, 1/1 resources updated in 14 seconds

ゲストOSにdovecotがインストールされているか確認

# ssh 192.168.33.10
Last login: Tue Apr 26 02:02:51 2016 from 10.0.2.2
[vagrant@localhost ~]$ rpm -qa | grep dovecot
dovecot-2.0.9-19.el6_7.2.x86_64
[vagrant@localhost ~]$

dovecotがインストールされています

Vagrantで構築したゲストOS(CentOS)に簡単にSSHログインさせる(パスワードなし)

基本的なことなのですが、若干ハマってしまったのでメモしておきます
通常はゲストOSのVagrantfileがあるディレクトリで、

# vagrant ssh

と入れればパスワードなしでSSHログインできますが、chefの検証(knife-solo)などでダイレクトにSSHログインしたかったため、
パスワード無しでログインできるようにします

環境

RHEL6.7(ホストOS)
Vagrant 1.8.1
CentOS6.7(ゲストOS)

Vagrantfileの修正

対象のゲストOS用のVagrantfileを修正します

  # 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"
   config.vm.network "private_network", ip: "192.168.33.10"

赤字の行を追加して、内部ネットワーク用のアドレスを保持するようにします
※今回はデフォルト値をそのまま利用しています

ゲストOSの再起動

対象のゲストOS用のVagrantfileのあるディレクトリで、以下のコマンドを実行します

# vagrant reload

念のためPING確認

ホストOS⇒ゲストOSへPINGが通ることを確認します

# ping 192.168.33.10
PING 192.168.33.10 (192.168.33.10) 56(84) bytes of data.
64 bytes from 192.168.33.10: icmp_seq=1 ttl=64 time=0.248 ms
64 bytes from 192.168.33.10: icmp_seq=2 ttl=64 time=0.232 ms
64 bytes from 192.168.33.10: icmp_seq=3 ttl=64 time=0.223 ms
64 bytes from 192.168.33.10: icmp_seq=4 ttl=64 time=0.222 ms
^C
--- 192.168.33.10 ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3556ms
rtt min/avg/max/mdev = 0.222/0.231/0.248/0.015 ms

Vagrant用のSSH設定を~/.ssh/configに追加

対象のゲストOS用のVagrantfileのあるディレクトリで、以下のコマンドを実行します

# vagrant ssh-config --host 192.168.33.10 >> ~/.ssh/config

vagrant ssh-config」コマンドはvagrantSSHコンフィグを出力させるコマンドです
「--host」オプションを付けるとHostのコンフィグが変更されたコンフィグが出力されます

「~/.ssh/config」には以下の設定が追加されます

Host 192.168.33.10
  HostName 127.0.0.1
  User vagrant
  Port 2200
  UserKnownHostsFile /dev/null
  StrictHostKeyChecking no
  PasswordAuthentication no
  IdentityFile "/root/vagrant/centos67/.vagrant/machines/default/virtualbox/private_key"
  IdentitiesOnly yes
  LogLevel FATAL

「~/.ssh/config」に設定を入れておくと、sshコマンドでオプションをわざわざ指定せずに簡単にSSHログインすることができます

SSHでログインできることを確認

# ssh 192.168.33.10
Last login: Mon Apr 25 08:41:59 2016 from 10.0.2.2
[vagrant@localhost ~]$

パスワードなしでログインできます

今回の件で「~/.ssh/config」の働きやsshコマンドのオプションに関してあまり理解できていなかったなぁ~と反省しております。。。

VagrantのCentOSにchefをインストール

VagrantのゲストOS上にchefをインストールし、簡単な動作を試してみます

環境

RHEL6.7(ホストOS)
CentOS6.7(ゲストOS) ※Vagrantで仮想環境を構築
ruby2.3.0p0 ※gemでインストールしている環境
Chef: 12.9.38

chefインストール

# gem install chef

いろいろなやり方があるかと思いますが、今回はgemでインストールしています

hello,worldを出力してみる

お決まりかもしれませんが、とりあえずこちらをやってみます

(1)クックブック格納用のディレクトリ作成

# mkdir /var/chef/ /var/chef/cookbooks

こちらはどこでもよいかと思いますが、自分が見ていた書籍のパスに合わせています

(2)クックブックの作成

「hello」がクックブック名、「/var/chef/cookbooks」がクックブックの出力先(-oオプション)となります

# knife cookbook create hello -o /var/chef/cookbooks
WARNING: No knife configuration file found
** Creating cookbook hello in /var/chef/cookbooks
** Creating README for cookbook: hello
** Creating CHANGELOG for cookbook: hello
** Creating metadata for cookbook: hello
# cd /var/chef/cookbooks
# ls -l
total 4
drwxr-xr-x 10 root root 4096 Apr 25 03:08 hello
# cd hello/
# ls -l
total 44
drwxr-xr-x 2 root root 4096 Apr 25 03:08 attributes
-rw-r--r-- 1 root root  430 Apr 25 03:08 CHANGELOG.md
drwxr-xr-x 2 root root 4096 Apr 25 03:08 definitions
drwxr-xr-x 3 root root 4096 Apr 25 03:08 files
drwxr-xr-x 2 root root 4096 Apr 25 03:08 libraries
-rw-r--r-- 1 root root  274 Apr 25 03:08 metadata.rb
drwxr-xr-x 2 root root 4096 Apr 25 03:08 providers
-rw-r--r-- 1 root root 1448 Apr 25 03:08 README.md
drwxr-xr-x 2 root root 4096 Apr 25 03:08 recipes
drwxr-xr-x 2 root root 4096 Apr 25 03:08 resources
drwxr-xr-x 3 root root 4096 Apr 25 03:08 templates

クックブック用のファイルが生成されます

(3)レシピを編集

# cd /var/chef/cookbooks/hello/recipes
# vi default.rb
#
# Cookbook Name:: hello
# Recipe:: default
#
# Copyright 2016, YOUR_COMPANY_NAME
#
# All rights reserved - Do Not Redistribute
#
log "Hello,World!"

「Hello,Word!」の行を追加します

(4)ChefSoloの実行

「hello」がクックブック名(-oオプション)となります

# chef-solo -o hello
[2016-04-25T03:13:04+01:00] WARN: *****************************************
[2016-04-25T03:13:04+01:00] WARN: Did not find config file: /etc/chef/solo.rb, using command line options.
[2016-04-25T03:13:04+01:00] WARN: *****************************************
Starting Chef Client, version 12.9.38
[2016-04-25T03:13:09+01:00] WARN: Run List override has been provided.
[2016-04-25T03:13:09+01:00] WARN: Original Run List: []
[2016-04-25T03:13:09+01:00] WARN: Overridden Run List: [recipe[hello]]
Installing Cookbook Gems:
Compiling Cookbooks...
Converging 1 resources
Recipe: hello::default
  * log[Hello,World!] action write


Running handlers:
Running handlers complete
Chef Client finished, 1/1 resources updated in 04 seconds

Hello,Wordが出力されています

特定のパッケージをインストールする

クックブックを使ってdovecotをインストールしてみます
手順に関してはほぼ先ほどと同じですが、クックブックの内容が異なります
dovecotにしたのは特に理由はありません(笑)

(1)クックブックの作成

# knife cookbook create dovecot -o /var/chef/cookbooks
WARNING: No knife configuration file found
** Creating cookbook dovecot in /var/chef/cookbooks
** Creating README for cookbook: dovecot
** Creating CHANGELOG for cookbook: dovecot
** Creating metadata for cookbook: dovecot

(2)レシピを編集

# vi /var/chef/cookbooks/dovecot/recipes/default.rb
package "dovecot" do
        action :install
end

上記の3行を追加します

(3)ChefSoloの実行

# chef-solo -o dovecot
[2016-04-25T05:03:59+01:00] WARN: *****************************************
[2016-04-25T05:03:59+01:00] WARN: Did not find config file: /etc/chef/solo.rb, using command line options.
[2016-04-25T05:03:59+01:00] WARN: *****************************************
Starting Chef Client, version 12.9.38
[2016-04-25T05:04:04+01:00] WARN: Run List override has been provided.
[2016-04-25T05:04:04+01:00] WARN: Original Run List: []
[2016-04-25T05:04:04+01:00] WARN: Overridden Run List: [recipe[dovecot]]
Installing Cookbook Gems:
Compiling Cookbooks...
Converging 1 resources
Recipe: dovecot::default
  * yum_package[dovecot] action install
    - install version 2.0.9-19.el6_7.2 of package dovecot

Running handlers:
Running handlers complete
Chef Client finished, 1/1 resources updated in 18 seconds

dovecotがインストールされた旨の出力があります

(4)実際にインストールされているか確認

# rpm -qa | grep dovecot
dovecot-2.0.9-19.el6_7.2.x86_64

実際にインストールされていることが確認できます

【RubyGems】ライブラリのRDoc参照方法(ローカル環境)

いろいろRubyGemsのライブラリを入れたりしてプログラムを作ってみたりしているのですが、リファレンス的なものがググっても出て こない状況^^;
いろいろ調べてみたらローカルでRDoc参照できるみたいなので、参照方法をメモしておきます。

環境

RHEL6.7
ruby 2.3.0p0
gem2.5.1

gem serverコマンドを実行して、HTTPサーバを立ち上げる

# gem server
Server started at http://0.0.0.0:8808
Server started at http://[::]:8808

HTTPサーバが立ち上がります

ブラウザでHTTPサーバにアクセス

ブラウザで「http://[サーバのIPアドレス]:8808」へアクセスするとトップページが表示されます
f:id:saosao_0706:20160422153209p:plain

詳細を見たいライブラリの「rdoc」のリンクをクリックするとRDocのドキュメントを見ることができます
f:id:saosao_0706:20160422154018p:plain

全部英語なのでなかなか厳しいですが、見れないよりは。。。

参照元

www.task-notes.com