24
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Chef Solo入門

Last updated at Posted at 2018-02-16

はじめに

Chefの勉強をしようと思ったのですが、ネットの情報が古かったり、参考書の情報が古かったりでどハマりしたので備忘録にこの記事を書こうと思いました。

環境情報

ホストOS環境

  • OS X 10.13.1
  • Vagrant 2.0.2
  • VirtualBox 5.2.6
  • Chef: 13.6.4
  • Chef Development Kit Version: 2.4.17
  • chef-client version: 13.6.4
  • berks version: 6.3.1
  • kitchen version: 1.19.2
  • inspec version: 1.45.13

ゲストOS環境

  • CentOS 7
  • Chef: 13.7.16
  • Chef Development Kit Version: 0.7.0
  • chef-client version: 12.4.1
  • berks version: 3.2.4
  • kitchen version: 1.4.2

環境構築基礎編

Vagrantで仮想環境を構築

ホストOS:terminal
$ vagrant init centos/7
実行結果
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.
ホストOS:terminal
$ vagrant up
実行結果
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'centos/7'...
==> default: Matching MAC address for NAT networking...
==> default: Checking if box 'centos/7' is up to date...
==> default: Setting the name of the VM: chef_default_1518704178759_43369
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
==> default: Forwarding ports...
    default: 22 (guest) => 2222 (host) (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: 
    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: No guest additions were detected on the base box for this VM! Guest
    default: additions are required for forwarded ports, shared folders, host only
    default: networking, and more. If SSH fails on this machine, please install
    default: the guest additions and repackage the box to continue.
    default: 
    default: This is not an error message; everything may continue to work properly,
    default: in which case you may ignore this message.
==> default: Rsyncing folder: {your current directory} => /vagrant

SSH設定

ホストOS:terminal
$ vagrant ssh-config --host {host name} >> ~/.ssh/config

上記の設定を行うことでssh {host name}でログインが可能になります。

プライベートネットワーク設定

config.vm.network "private_network", ip: "192.168.33.10"のコメントアウトを外す

Vagrantfile
# -*- 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://vagrantcloud.com/search.
  config.vm.box = "centos/7"

  # 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.
  # NOTE: This will enable public access to the opened port
  # config.vm.network "forwarded_port", guest: 80, host: 8080

  # Create a forwarded port mapping which allows access to a specific port
  # within the machine from a port on the host machine and only allow access
  # via 127.0.0.1 to disable public access
  # config.vm.network "forwarded_port", guest: 80, host: 8080, host_ip: "127.0.0.1"

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

  # 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
  #   apt-get update
  #   apt-get install -y apache2
  # SHELL
end

Vagrantの再起動

$ vagrant halt
$ vagrant reload

CentOSにChef Soloをインストール

ログイン

ホストOS:terminal
$ ssh {host name}

Chefをインストール

ゲストOS:terminal
$ curl -L https://www.opscode.com/chef/install.sh | sudo bash
実行結果
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 23432  100 23432    0     0  16256      0  0:00:01  0:00:01 --:--:-- 16272
el 7 x86_64
Getting information for chef stable  for el...
downloading https://omnitruck-direct.chef.io/stable/chef/metadata?v=&p=el&pv=7&m=x86_64
  to file /tmp/install.sh.2667/metadata.txt
trying curl...
sha1	0d8b0f9b3ce0a2721f7e8ff7ea46330fd712df46
sha256	89c96addb749370044964b63d16382149f0756d54e833602dd91cf039a92a9f7
url	https://packages.chef.io/files/stable/chef/13.7.16/el/7/chef-13.7.16-1.el7.x86_64.rpm
version	13.7.16
downloaded metadata file looks valid...
downloading https://packages.chef.io/files/stable/chef/13.7.16/el/7/chef-13.7.16-1.el7.x86_64.rpm
  to file /tmp/install.sh.2667/chef-13.7.16-1.el7.x86_64.rpm
trying curl...
Comparing checksum with sha256sum...

WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING

You are installing an omnibus package without a version pin.  If you are installing
on production servers via an automated process this is DANGEROUS and you will
be upgraded without warning on new releases, even to new major releases.
Letting the version float is only appropriate in desktop, test, development or
CI/CD environments.

WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING

Installing chef 
installing with rpm...
warning: /tmp/install.sh.2667/chef-13.7.16-1.el7.x86_64.rpm: Header V4 DSA/SHA1 Signature, key ID 83ef826a: NOKEY
Preparing...                          ################################# [100%]
Updating / installing...
   1:chef-13.7.16-1.el7               ################################# [100%]
Thank you for installing Chef!
ゲストOS:terminal
$ chef-solo -v
実行結果
Chef: 13.7.16

ChefDKをインストール

wgetをインストールする

ゲストOS:terminal
$ sudo yum install wget
実行結果
Failed to set locale, defaulting to C
Loaded plugins: fastestmirror
base                                                                                                                 | 3.6 kB  00:00:00     
extras                                                                                                               | 3.4 kB  00:00:00     
updates                                                                                                              | 3.4 kB  00:00:00     
(1/4): base/7/x86_64/group_gz                                                                                        | 156 kB  00:00:00     
(2/4): extras/7/x86_64/primary_db                                                                                    | 166 kB  00:00:00     
(3/4): base/7/x86_64/primary_db                                                                                      | 5.7 MB  00:00:02     
(4/4): updates/7/x86_64/primary_db                                                                                   | 6.0 MB  00:00:02     
Determining fastest mirrors
 * base: ftp.iij.ad.jp
 * extras: mirror.0x.sg
 * updates: mirror.nus.edu.sg
Resolving Dependencies
--> Running transaction check
---> Package wget.x86_64 0:1.14-15.el7_4.1 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

============================================================================================================================================
 Package                      Arch                           Version                                  Repository                       Size
============================================================================================================================================
Installing:
 wget                         x86_64                         1.14-15.el7_4.1                          updates                         547 k

Transaction Summary
============================================================================================================================================
Install  1 Package

Total download size: 547 k
Installed size: 2.0 M
Is this ok [y/d/N]: y
Downloading packages:
warning: /var/cache/yum/x86_64/7/updates/packages/wget-1.14-15.el7_4.1.x86_64.rpm: Header V3 RSA/SHA256 Signature, key ID f4a80eb5: NOKEY
Public key for wget-1.14-15.el7_4.1.x86_64.rpm is not installed
wget-1.14-15.el7_4.1.x86_64.rpm                                                                                      | 547 kB  00:00:00     
Retrieving key from file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
Importing GPG key 0xF4A80EB5:
 Userid     : "CentOS-7 Key (CentOS 7 Official Signing Key) <security@centos.org>"
 Fingerprint: 6341 ab27 53d7 8a78 a7c2 7bb1 24c6 a8a7 f4a8 0eb5
 Package    : centos-release-7-4.1708.el7.centos.x86_64 (@anaconda)
 From       : /etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
Is this ok [y/N]: y
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
Warning: RPMDB altered outside of yum.
  Installing : wget-1.14-15.el7_4.1.x86_64                                                                                              1/1 
  Verifying  : wget-1.14-15.el7_4.1.x86_64                                                                                              1/1 

Installed:
  wget.x86_64 0:1.14-15.el7_4.1                                                                                                             

Complete!

ChefDKをインストール

ゲストOS:terminal
$ sudo rpm -Uvh https://packages.chef.io/files/stable/chefdk/2.4.17/el/7/chefdk-2.4.17-1.el7.x86_64.rpm
実行結果
Retrieving https://packages.chef.io/files/stable/chefdk/2.4.17/el/7/chefdk-2.4.17-1.el7.x86_64.rpm
warning: /var/tmp/rpm-tmp.Q1Py2Y: Header V4 DSA/SHA1 Signature, key ID 83ef826a: NOKEY
Preparing...                          ################################# [100%]
Updating / installing...
   1:chefdk-2.4.17-1.el7              ################################# [100%]
ゲストOS:terminal
$ chef -v
実行結果
Chef Development Kit Version: 2.4.17
chef-client version: 13.6.4
delivery version: master (73ebb72a6c42b3d2ff5370c476be800fee7e5427)
berks version: 6.3.1
kitchen version: 1.19.2
inspec version: 1.45.13

クックブックを作成

まずはHelloクックブックを作成してChef Soloを実行します

ディレクトリを作成

ゲストOS:terminal
$ sudo mkdir -p /var/chef/cookbooks
ゲストOS:terminal
$ cd /var/chef/

クックブックを作成

ゲストOS:terminal
$ sudo chef generate cookbook cookbooks/hello hello
実行結果
Generating cookbook hello
- Ensuring correct cookbook file content
- Ensuring delivery configuration
- Ensuring correct delivery build cookbook content

Your cookbook is ready. Type `cd cookbooks/hello` to enter it.

There are several commands you can run to get started locally developing and testing your cookbook.
Type `delivery local --help` to see a full list.

Why not start by writing a test? Tests for the default recipe are stored at:

test/smoke/default/default_test.rb

If you'd prefer to dive right in, the default recipe can be found at:

recipes/default.rb

レシピを編集

ゲストOS:terminal
$ sudo vi /var/chef/cookbooks/hello/recipes/default.rb
default.rb
#
# Cookbook:: hello
# Recipe:: default
#
# Copyright:: 2018, The Authors, All Rights Reserved.
log "hello world!"

Chef Soloを実行

ゲストOS:terminal
$ sudo chef-solo -o hello
実行結果
[2018-02-15T14:57:59+00:00] WARN: *****************************************
[2018-02-15T14:57:59+00:00] WARN: Did not find config file: /etc/chef/solo.rb, using command line options.
[2018-02-15T14:57:59+00:00] WARN: *****************************************
[2018-02-15T14:57:59+00:00] WARN: *****************************************
[2018-02-15T14:57:59+00:00] WARN: *****************************************
[2018-02-15T14:57:59+00:00] WARN: Did not find config file: /etc/chef/client.rb, using command line options.
[2018-02-15T14:57:59+00:00] WARN: Did not find config file: /etc/chef/client.rb, using command line options.
[2018-02-15T14:57:59+00:00] WARN: *****************************************
[2018-02-15T14:57:59+00:00] WARN: *****************************************
Starting Chef Client, version 13.6.4
[2018-02-15T14:58:01+00:00] WARN: Run List override has been provided.
[2018-02-15T14:58:01+00:00] WARN: Run List override has been provided.
[2018-02-15T14:58:01+00:00] WARN: Original Run List: []
[2018-02-15T14:58:01+00:00] WARN: Original Run List: []
[2018-02-15T14:58:01+00:00] WARN: Overridden Run List: [recipe[hello]]
[2018-02-15T14:58:01+00:00] WARN: Overridden Run List: [recipe[hello]]
resolving cookbooks for run list: ["hello"]
Synchronizing Cookbooks:
  - hello (0.1.0)
Installing Cookbook Gems:
Compiling Cookbooks...
Converging 1 resources
Recipe: hello::default
  * log[hello world!] action write

Chef Soloでパッケージをインストール

クックブックを作成

ゲストOS:terminal
$ sudo chef generate cookbook cookbooks/dstat dstat
実行結果
Generating cookbook dstat
- Ensuring correct cookbook file content
- Ensuring delivery configuration
- Ensuring correct delivery build cookbook content

Your cookbook is ready. Type `cd cookbooks/dstat` to enter it.

There are several commands you can run to get started locally developing and testing your cookbook.
Type `delivery local --help` to see a full list.

Why not start by writing a test? Tests for the default recipe are stored at:

test/smoke/default/default_test.rb

If you'd prefer to dive right in, the default recipe can be found at:

recipes/default.rb

レシピを作成

ゲストOS:terminal
$ sudo vi cookbooks/dstat/recipes/default.rb 
default.rb
#
# Cookbook:: dstat
# Recipe:: default
#
# Copyright:: 2018, The Authors, All Rights Reserved.
package "dstat" do
 action :install
end

Chef Soloを実行

ゲストOS:terminal
$ sudo chef-solo -o hello,dstat
実行結果
[2018-02-15T15:03:39+00:00] WARN: *****************************************
[2018-02-15T15:03:39+00:00] WARN: Did not find config file: /etc/chef/solo.rb, using command line options.
[2018-02-15T15:03:39+00:00] WARN: *****************************************
[2018-02-15T15:03:39+00:00] WARN: *****************************************
[2018-02-15T15:03:39+00:00] WARN: *****************************************
[2018-02-15T15:03:39+00:00] WARN: Did not find config file: /etc/chef/client.rb, using command line options.
[2018-02-15T15:03:39+00:00] WARN: Did not find config file: /etc/chef/client.rb, using command line options.
[2018-02-15T15:03:39+00:00] WARN: *****************************************
[2018-02-15T15:03:39+00:00] WARN: *****************************************
Starting Chef Client, version 13.6.4
[2018-02-15T15:03:41+00:00] WARN: Run List override has been provided.
[2018-02-15T15:03:41+00:00] WARN: Run List override has been provided.
[2018-02-15T15:03:41+00:00] WARN: Original Run List: []
[2018-02-15T15:03:41+00:00] WARN: Original Run List: []
[2018-02-15T15:03:41+00:00] WARN: Overridden Run List: [recipe[hello], recipe[dstat]]
[2018-02-15T15:03:41+00:00] WARN: Overridden Run List: [recipe[hello], recipe[dstat]]
resolving cookbooks for run list: ["hello", "dstat"]
Synchronizing Cookbooks:
  - hello (0.1.0)
  - dstat (0.1.0)
Installing Cookbook Gems:
Compiling Cookbooks...
Converging 2 resources
Recipe: hello::default
  * log[hello world!] action write
  
Recipe: dstat::default
  * yum_package[dstat] action install
    - install version 0.7.2-12.el7 of package dstat
[2018-02-15T15:03:44+00:00] WARN: Skipping final node save because override_runlist was given
[2018-02-15T15:03:44+00:00] WARN: Skipping final node save because override_runlist was given

Running handlers:
Running handlers complete
Chef Client finished, 2/2 resources updated in 05 seconds
[2018-02-15T15:03:44+00:00] WARN: *****************************************
[2018-02-15T15:03:44+00:00] WARN: *****************************************
[2018-02-15T15:03:44+00:00] WARN: Did not find config file: /etc/chef/client.rb, using command line options.
[2018-02-15T15:03:44+00:00] WARN: Did not find config file: /etc/chef/client.rb, using command line options.
[2018-02-15T15:03:44+00:00] WARN: *****************************************
[2018-02-15T15:03:44+00:00] WARN: *****************************************

Chef Soloを再実行

ゲストOS:terminal
$ sudo chef-solo -o hello,dstat
実行結果
[2018-02-15T15:04:35+00:00] WARN: *****************************************
[2018-02-15T15:04:35+00:00] WARN: Did not find config file: /etc/chef/solo.rb, using command line options.
[2018-02-15T15:04:35+00:00] WARN: *****************************************
[2018-02-15T15:04:35+00:00] WARN: *****************************************
[2018-02-15T15:04:35+00:00] WARN: *****************************************
[2018-02-15T15:04:35+00:00] WARN: Did not find config file: /etc/chef/client.rb, using command line options.
[2018-02-15T15:04:35+00:00] WARN: Did not find config file: /etc/chef/client.rb, using command line options.
[2018-02-15T15:04:35+00:00] WARN: *****************************************
[2018-02-15T15:04:35+00:00] WARN: *****************************************
Starting Chef Client, version 13.6.4
[2018-02-15T15:04:36+00:00] WARN: Run List override has been provided.
[2018-02-15T15:04:36+00:00] WARN: Run List override has been provided.
[2018-02-15T15:04:36+00:00] WARN: Original Run List: []
[2018-02-15T15:04:36+00:00] WARN: Original Run List: []
[2018-02-15T15:04:36+00:00] WARN: Overridden Run List: [recipe[hello], recipe[dstat]]
[2018-02-15T15:04:36+00:00] WARN: Overridden Run List: [recipe[hello], recipe[dstat]]
resolving cookbooks for run list: ["hello", "dstat"]
Synchronizing Cookbooks:
  - hello (0.1.0)
  - dstat (0.1.0)
Installing Cookbook Gems:
Compiling Cookbooks...
Converging 2 resources
Recipe: hello::default
  * log[hello world!] action write
  
Recipe: dstat::default
  * yum_package[dstat] action install (up to date)
[2018-02-15T15:04:38+00:00] WARN: Skipping final node save because override_runlist was given
[2018-02-15T15:04:38+00:00] WARN: Skipping final node save because override_runlist was given

Running handlers:
Running handlers complete
Chef Client finished, 1/2 resources updated in 02 seconds
[2018-02-15T15:04:38+00:00] WARN: *****************************************
[2018-02-15T15:04:38+00:00] WARN: *****************************************
[2018-02-15T15:04:38+00:00] WARN: Did not find config file: /etc/chef/client.rb, using command line options.
[2018-02-15T15:04:38+00:00] WARN: Did not find config file: /etc/chef/client.rb, using command line options.
[2018-02-15T15:04:38+00:00] WARN: *****************************************
[2018-02-15T15:04:38+00:00] WARN: *****************************************

dstatのレシピは実行されましたが、エラーにならずパッケージのインストールも行われません。
chefがパッケージの有無を確認してよしなに判断してくれます。

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

ホストOSのVagrantfileがあるディレクトリで以下を実行

ホストOS:terminal
$ bundle init

Gemfileを編集

Gemfile
# frozen_string_literal: true

source "https://rubygems.org"

git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }

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

knife-solo,berkshelfのインストール

ホストOS:terminal
$ bundle install --path vendor/bundle
実行結果
Fetching gem metadata from https://rubygems.org/........
Fetching gem metadata from https://rubygems.org/.
Resolving dependencies...
Fetching builder 3.2.3
Installing builder 3.2.3
Using bundler 1.16.1
Fetching fuzzyurl 0.8.0
Installing fuzzyurl 0.8.0
Fetching mixlib-config 2.2.5
Installing mixlib-config 2.2.5
Fetching mixlib-shellout 2.3.2
Installing mixlib-shellout 2.3.2
Fetching chef-config 12.12.15
Installing chef-config 12.12.15
Fetching libyajl2 1.2.0
Installing libyajl2 1.2.0 with native extensions
Fetching ffi-yajl 2.3.1
Installing ffi-yajl 2.3.1 with native extensions
Fetching hashie 3.5.7
Installing hashie 3.5.7
Fetching mixlib-log 1.7.1
Installing mixlib-log 1.7.1
Fetching rack 1.6.8
Installing rack 1.6.8
Fetching uuidtools 2.1.5
Installing uuidtools 2.1.5
Fetching chef-zero 4.9.0
Installing chef-zero 4.9.0
Fetching diff-lcs 1.3
Installing diff-lcs 1.3
Fetching erubis 2.7.0
Installing erubis 2.7.0
Fetching highline 1.7.10
Installing highline 1.7.10
Fetching iniparse 1.4.4
Installing iniparse 1.4.4
Fetching mixlib-authentication 1.4.2
Installing mixlib-authentication 1.4.2
Fetching mixlib-cli 1.7.0
Installing mixlib-cli 1.7.0
Fetching net-ssh 3.2.0
Installing net-ssh 3.2.0
Fetching net-sftp 2.1.2
Installing net-sftp 2.1.2
Fetching net-ssh-gateway 1.3.0
Installing net-ssh-gateway 1.3.0
Fetching net-ssh-multi 1.2.1
Installing net-ssh-multi 1.2.1
Fetching ffi 1.9.21
Installing ffi 1.9.21 with native extensions
Fetching ipaddress 0.8.3
Installing ipaddress 0.8.3
Fetching plist 3.4.0
Installing plist 3.4.0
Fetching systemu 2.6.5
Installing systemu 2.6.5
Fetching wmi-lite 1.0.0
Installing wmi-lite 1.0.0
Fetching ohai 8.26.1
Installing ohai 8.26.1
Fetching proxifier 1.0.3
Installing proxifier 1.0.3
Fetching rspec-support 3.7.1
Installing rspec-support 3.7.1
Fetching rspec-core 3.7.1
Installing rspec-core 3.7.1
Fetching rspec-expectations 3.7.0
Installing rspec-expectations 3.7.0
Fetching rspec-mocks 3.7.0
Installing rspec-mocks 3.7.0
Fetching rspec_junit_formatter 0.2.3
Installing rspec_junit_formatter 0.2.3
Fetching multi_json 1.13.1
Installing multi_json 1.13.1
Fetching rspec 3.7.0
Installing rspec 3.7.0
Fetching rspec-its 1.2.0
Installing rspec-its 1.2.0
Fetching net-scp 1.2.1
Installing net-scp 1.2.1
Fetching net-telnet 0.1.1
Installing net-telnet 0.1.1
Fetching sfl 2.3
Installing sfl 2.3
Fetching specinfra 2.73.2
Installing specinfra 2.73.2
Fetching serverspec 2.41.3
Installing serverspec 2.41.3
Fetching syslog-logger 1.6.8
Installing syslog-logger 1.6.8
Fetching chef 12.12.15
Installing chef 12.12.15
Fetching knife-solo 0.6.0
Installing knife-solo 0.6.0
Bundle complete! 2 Gemfile dependencies, 46 gems now installed.
Bundled gems are installed into `./vendor/bundle`
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.

リポジトリを準備

ホストOS:terminal
$ bundle exec knife solo init .
実行結果
Creating kitchen...
Creating knife.rb in kitchen...
Creating cupboards...
Setting up Berkshelf...

site-cookbooks以下にdstatクックブックを作成

ホストOS:terminal
$ chef generate cookbook site-cookbooks/dstat dstat
実行結果
Generating cookbook dstat
- Ensuring correct cookbook file content
- Ensuring delivery configuration
- Ensuring correct delivery build cookbook content

Your cookbook is ready. Type `cd site-cookbooks/dstat` to enter it.

There are several commands you can run to get started locally developing and testing your cookbook.
Type `delivery local --help` to see a full list.

Why not start by writing a test? Tests for the default recipe are stored at:

test/smoke/default/default_test.rb

If you'd prefer to dive right in, the default recipe can be found at:

recipes/default.rb

レシピを作成

site-cookbooks/dstat/recipes/default.rb
#
# Cookbook:: dstat
# Recipe:: default
#
# Copyright:: 2018, The Authors, All Rights Reserved.
package "dstat" do
  action :install
end

Nodeオブジェクト設定ファイルを更新

run_listrecipe[dstat]を追記

nodes/{project-name}.json
{
  "run_list": [
    "recipe[dstat]"
  ],
  "automatic": {
    "ipaddress": "host-name"
  }
}

knife-soloでChef Soloを実行

ホストOS:terminal
$ bundle exec knife solo cook {your host name}
実行結果
Running Chef on {your host name}...
Checking Chef version...
Installing Berkshelf cookbooks to 'cookbooks'...
Resolving cookbook dependencies...
Uploading the kitchen...
WARNING: Local cookbook_path '{Your directory}/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 13.6.4
resolving cookbooks for run list: ["dstat"]
Synchronizing Cookbooks:
  - dstat (0.1.0)
Installing Cookbook Gems:
Compiling Cookbooks...
Converging 1 resources
Recipe: dstat::default
  * yum_package[dstat] action install (up to date)

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

dstatはインストール済みのためup to dateと表示されています。
TODO 実行するとcookbooksが消えてWARNINGが出る。。。なぜ。。。

Chef SoloでApache、MySQLをセットアップ

Apacheのクックブックを作成

ホストOS:terminal
$ chef generate cookbook site-cookbooks/apache apache
実行結果
Generating cookbook apache
- Ensuring correct cookbook file content
- Ensuring delivery configuration
- Ensuring correct delivery build cookbook content

Your cookbook is ready. Type `cd site-cookbooks/apache` to enter it.

There are several commands you can run to get started locally developing and testing your cookbook.
Type `delivery local --help` to see a full list.

Why not start by writing a test? Tests for the default recipe are stored at:

test/smoke/default/default_test.rb

If you'd prefer to dive right in, the default recipe can be found at:

recipes/default.rb

MySQLのクックブックを作成

ホストOS:terminal
$ chef generate cookbook site-cookbooks/mysql mysql
実行結果
Generating cookbook mysql
- Ensuring correct cookbook file content
- Ensuring delivery configuration
- Ensuring correct delivery build cookbook content

Your cookbook is ready. Type `cd site-cookbooks/mysql` to enter it.

There are several commands you can run to get started locally developing and testing your cookbook.
Type `delivery local --help` to see a full list.

Why not start by writing a test? Tests for the default recipe are stored at:

test/smoke/default/default_test.rb

If you'd prefer to dive right in, the default recipe can be found at:

recipes/default.rb

Nodeオブジェクト設定ファイルを更新

run_listrecipe[dstat]を追記

nodes/{host-name}.json
{
  "run_list": [
    "recipe[dstat]",
    "recipe[apache]",
    "recipe[mysql]"
  ],
  "automatic": {
    "ipaddress": "{your host name}"
  }
}

Apacheのレシピを作成

site-cookbooks/apache/recipes/default.rb
#
# Cookbook:: apache
# Recipe:: default
#
# Copyright:: 2018, The Authors, All Rights Reserved.
package "httpd" do
  action :install
end

# サービスの有効化と起動
service "httpd" do
  action [ :enable, :start]
end

MySQLのレシピを作成

site-cookbooks/mysql/recipes/default.rb
#
# Cookbook:: mysql
# Recipe:: default
#
# Copyright:: 2018, The Authors, All Rights Reserved.

# CentOS7 用の rpm を追加するレシピ
remote_file "#{Chef::Config[:file_cache_path]}/mysql-community-release-el7-5.noarch.rpm" do
  source 'http://repo.mysql.com/mysql-community-release-el7-5.noarch.rpm'
  action :create
end

rpm_package 'mysql-community-release' do
  source "#{Chef::Config[:file_cache_path]}/mysql-community-release-el7-5.noarch.rpm"
  action :install
end

package 'mysql-server' do
  action :install
end

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

Chef Soloを実行

ホストOS:terminal
$ bundle exec knife solo cook {your host name}
実行結果
Running Chef on {your host name}...
Checking Chef version...
Installing Berkshelf cookbooks to 'cookbooks'...
Resolving cookbook dependencies...
Uploading the kitchen...
WARNING: Local cookbook_path '{Your directory}/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 13.6.4
resolving cookbooks for run list: ["dstat", "apache", "mysql"]
Synchronizing Cookbooks:
  - dstat (0.1.0)
  - apache (0.1.0)
  - mysql (0.1.0)
Installing Cookbook Gems:
Compiling Cookbooks...
Converging 5 resources
Recipe: dstat::default
  * yum_package[dstat] action install (up to date)
Recipe: apache::default
  * yum_package[httpd] action install
    - install version 2.4.6-67.el7.centos.6 of package httpd
  * service[httpd] action enable
    - enable service service[httpd]
  * service[httpd] action start
    - start service service[httpd]
Recipe: mysql::default
  * remote_file[/home/vagrant/chef-solo/local-mode-cache/cache/mysql-community-release-el7-5.noarch.rpm] action create
    - create new file /home/vagrant/chef-solo/local-mode-cache/cache/mysql-community-release-el7-5.noarch.rpm
    - update content in file /home/vagrant/chef-solo/local-mode-cache/cache/mysql-community-release-el7-5.noarch.rpm from none to 0592c3
    (new content is binary, diff output suppressed)
    - restore selinux security context
  * rpm_package[mysql-community-release] action install
    - install version el7-5 of package mysql-community-release
  * yum_package[mysql-server] action install[2018-02-15T16:49:49+00:00] WARN: yum_package[mysql-server] matched multiple Provides for mysql-server but we can only use the first match: mysql-community-server. Please use a more specific version.
[2018-02-15T16:49:49+00:00] WARN: yum_package[mysql-server] matched multiple Provides for mysql-server but we can only use the first match: mysql-community-server. Please use a more specific version.

    - install version 5.6.39-2.el7 of package mysql-community-server
  * service[mysqld] action enable (up to date)
  * service[mysqld] action start
    - start service service[mysqld]

Running handlers:
Running handlers complete
Chef Client finished, 7/9 resources updated in 49 seconds

ゲストOSで実行結果の確認

ゲストOSへログイン

ホストOS:terminal
$ ssh {your host name}

Apacheが起動しているか確認

ゲストOS:terminal
$ service httpd status
実行結果
Redirecting to /bin/systemctl status httpd.service
● httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
   Active: active (running) since Thu 2018-02-15 16:46:23 UTC; 12min ago
     Docs: man:httpd(8)
           man:apachectl(8)
 Main PID: 7518 (httpd)
   Status: "Total requests: 0; Current requests/sec: 0; Current traffic:   0 B/sec"
   CGroup: /system.slice/httpd.service
           ├─7518 /usr/sbin/httpd -DFOREGROUND
           ├─7519 /usr/sbin/httpd -DFOREGROUND
           ├─7520 /usr/sbin/httpd -DFOREGROUND
           ├─7521 /usr/sbin/httpd -DFOREGROUND
           ├─7522 /usr/sbin/httpd -DFOREGROUND
           └─7523 /usr/sbin/httpd -DFOREGROUND

MySQLの動作確認

ゲストOS:terminal
$ mysql -u root
実行結果
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.6.39 MySQL Community Server (GPL)

Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> 

仮想サーバーを破棄して、サイドChef Soloを実行

仮想サーバーの破棄

ホストOS:terminal
$ vagrant destroy -f
実行結果
==> default: Forcing shutdown of VM...
==> default: Destroying VM and associated drives...

仮想サーバーの起動とログイン

ホストOS:terminal
$ vagrant up
ホストOS:terminal
$ vagrant ssh

ApacheやMySQLが削除されているか確認

ゲストOS:terminal
$ mysql -v
-bash: mysql: command not found
$ httpd -v
-bash: httpd: command not found

Chefをインストール

ゲストOSからログアウトしてから

ホストOS:terminal
$ bundle exec knife solo bootstrap {your host name}
実行結果
Bootstrapping Chef...
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 23432  100 23432    0     0  10867      0  0:00:02  0:00:02 --:--:-- 10873
el 7 x86_64
Getting information for chef stable 12.12.15 for el...
downloading https://omnitruck-direct.chef.io/stable/chef/metadata?v=12.12.15&p=el&pv=7&m=x86_64
  to file /tmp/install.sh.3413/metadata.txt
trying curl...
sha1	92d14fa522ff14b1e22622312c8271db3cc0d512
sha256	ce1f216242f26d7274c108a9cb9d8add7095727e039bac968de9291f56a90c25
url	https://packages.chef.io/files/stable/chef/12.12.15/el/7/chef-12.12.15-1.el7.x86_64.rpm
version	12.12.15
downloaded metadata file looks valid...
downloading https://packages.chef.io/files/stable/chef/12.12.15/el/7/chef-12.12.15-1.el7.x86_64.rpm
  to file /tmp/install.sh.3413/chef-12.12.15-1.el7.x86_64.rpm
trying curl...
Comparing checksum with sha256sum...
Installing chef 12.12.15
installing with rpm...
warning: /tmp/install.sh.3413/chef-12.12.15-1.el7.x86_64.rpm: Header V4 DSA/SHA1 Signature, key ID 83ef826a: NOKEY
Preparing...                          ################################# [100%]
Updating / installing...
   1:chef-12.12.15-1.el7              ################################# [100%]
Thank you for installing Chef!
Running Chef on {your host name}...
Installing Berkshelf cookbooks to 'cookbooks'...
Resolving cookbook dependencies...
Uploading the kitchen...
WARNING: Local cookbook_path '{Your directory}/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.12.15
resolving cookbooks for run list: ["dstat", "apache", "mysql"]
Synchronizing Cookbooks:
  - dstat (0.1.0)
  - mysql (0.1.0)
  - apache (0.1.0)
Installing Cookbook Gems:
Compiling Cookbooks...
Converging 7 resources
Recipe: dstat::default
  * yum_package[dstat] action install
    - install version 0.7.2-12.el7 of package dstat
Recipe: apache::default
  * yum_package[httpd] action install
    - install version 2.4.6-67.el7.centos.6 of package httpd
  * service[httpd] action enable
    - enable service service[httpd]
  * service[httpd] action start
    - start service service[httpd]
Recipe: mysql::default
  * remote_file[/home/vagrant/chef-solo/local-mode-cache/cache/mysql-community-release-el7-5.noarch.rpm] action create
    - create new file /home/vagrant/chef-solo/local-mode-cache/cache/mysql-community-release-el7-5.noarch.rpm
    - update content in file /home/vagrant/chef-solo/local-mode-cache/cache/mysql-community-release-el7-5.noarch.rpm from none to 0592c3
    (new content is binary, diff output suppressed)
    - restore selinux security context
  * rpm_package[mysql-community-release] action install
    - install version el7-5 of package mysql-community-release
  * yum_package[mysql-server] action install[2018-02-16T02:23:38+00:00] WARN: yum_package[mysql-server] matched multiple Provides for mysql-server but we can only use the first match: mysql-community-server. Please use a more specific version.

    - install version 5.6.39-2.el7 of package mysql-community-server
  * service[mysqld] action enable (up to date)
  * service[mysqld] action start
    - start service service[mysqld]

Running handlers:
Running handlers complete
Chef Client finished, 8/9 resources updated in 01 minutes 12 seconds

もう一度ゲストOSにsshするとmysqlコマンドなどが実行できるようになっています。

最後に

コマンドが新しくなっていたり、Versionの兼ね合いとかにだいぶ悩まされました。
ところどころ納得いかないところ(Warningがでてたり)があります、詳しい方がいらっしゃいましたらご指摘いただけると幸いです。

次は仮想サーバーにRails環境を構築します。

24
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
24
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?