Skip to main content

Configuration Management, pt.3 - Using Chef

Back-end Development
Planning & Strategy

We have looked at how Configuration Management has evolved, and how to set up a basic environment to run Chef on any number of servers. Now lets look at what we can do with Chef.

Custom Cookbooks

While you don't need to set up custom cookbooks to use Chef, you almost always will in order to configure things exactly as needed. Once we have created a cookbook and recipe, we will add that to the run list and execute the setup process on the server.

To set up our first cookbook we will use knife to get things started.

knife cookbook create -o site-cookbooks demo-cookbook

This puts a shell of a cookbook in our site-cookbooks directory.

Installing Apache

Add depends 'httpd', '~> 0.3.5’ to cookbook metadata.rb

Install Apache

httpd_service 'demo' do
  mpm 'prefork'
  action [:create, :start]
end

Setup the Directory

directory ‘/var/www/vhosts/demo/' do
  recursive true
end

Create the Site

httpd_config 'demo' do
  instance 'demo'
  source 'demo.conf.erb'
  notifies :restart, 'httpd_service[demo]'
end

MySQL

Add Client

mysql_client 'default' do
  action :create
end

Add Service

mysql_service 'default' do
  initial_root_password ‘initial_root_passwd’
  action [:create, :start]
end

Create Database

# Create the database instance.
mysql_database ‘chef_demo_db’ do
  connection(
    :host => '127.0.0.1',
    :username => 'root',
    :password => 'mysql_root_password'
  )
  action :create
end

Add User

mysql_database_user 'db_admin' do
  connection(
    :host => '127.0.0.1',
    :username => 'root',
    :password => 'mysql_root_password'
  )
  password 'mysql_admin_password'
  database_name ‘chef_demo_db’
  host '127.0.0.1'
  action [:create, :grant]
end

PHP

Add PHP Apache Module

httpd_module 'php5' do
  instance 'demo'
end

PHP MySql Library

package 'php5-mysql' do
  action :install
  notifies :restart, 'httpd_service[demo]'
end

Deployment

File creation example

file ‘/var/www/vhosts/demo/index.html' do
  content ‘<html>Very Site, Much Deployment</html>’
  mode '0644'
  owner 'deploy'
  group 'deploy'
end

Checkout Files

git “/var/www/vhosts/demo“ do
  repository 'git@github.com:mbopp/demo-repo.git'
  revision ‘master’
  action :sync
end

Deploy

deploy ‘demo_repo' do
  repo 'git@github.com:mbopp/demo-repo.git'
  user 'deploy'
  deploy_to ‘/var/www/vhosts/demo’
  notifies :restart, 'service[demo]'
  action :deploy
end