Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 37 ยท Projects and Practice

Project: A Complete Web Server Cookbook

Build a complete Chef cookbook for a web server: metadata, attributes, template, recipe, notifications, ChefSpec and InSpec tests, plus a runnable Ruby simulation.

In this project you will design a small but complete cookbook, webserver, the way a real team would. It installs Nginx, writes a configuration from a template, publishes a home page, manages the service, and comes with unit tests, integration tests and a Test Kitchen file. Every file is real Chef code and is shown read-only. At the end a Ruby simulation runs the whole thing (attributes, template, resources, notifications and a second idempotent run) so you can see the pieces working together.

Real Chef cannot run on this site. The cookbook files are exactly what you would create on your workstation. The simulation is a plain Ruby stand-in that models the converge and is labelled as such.

The plan

flowchart TD
  A["attributes/default.rb: port, workers, site name"] --> R["recipes/default.rb"]
  T["templates/default/nginx.conf.erb"] --> R
  R --> P["package nginx"]
  R --> F["template nginx.conf"]
  R --> H["file index.html"]
  R --> S["service nginx: enable and start"]
  F -- "notifies reload" --> S
  R --> V["tests: ChefSpec, InSpec, Kitchen"]

The recipe wires attributes into resources; the config template notifies the service.

Layout of the cookbook:

TEXT
webserver/
  metadata.rb
  Berksfile            (or Policyfile.rb)
  kitchen.yml
  attributes/default.rb
  recipes/default.rb
  templates/default/nginx.conf.erb
  templates/default/index.html.erb
  spec/unit/recipes/default_spec.rb
  test/integration/default/default_test.rb

Step 1: metadata and attributes

Ruby
# metadata.rb
name 'webserver'
maintainer 'Platform Team'
description 'Installs and configures Nginx'
version '0.1.0'
chef_version '>= 18.0'
supports 'ubuntu', '>= 22.04'
supports 'almalinux', '>= 9'
Ruby
# attributes/default.rb
default['webserver']['port'] = 8080
default['webserver']['worker_processes'] = 'auto'
default['webserver']['site_name'] = 'Example Site'
default['webserver']['docroot'] = '/var/www/site'
default['webserver']['gzip'] = true

Every value a user might want to change is an attribute with a default. The names are nested under webserver so they cannot clash with other cookbooks.

Step 2: templates

ERB
# templates/default/nginx.conf.erb
# Managed by Chef, local changes will be overwritten
worker_processes <%= @worker_processes %>;
events { worker_connections 1024; }
http {
<% if @gzip -%>
  gzip on;
<% end -%>
  server {
    listen <%= @port %>;
    root <%= @docroot %>;
    index index.html;
  }
}
ERB
# templates/default/index.html.erb
<!doctype html>
<title><%= @site_name %></title>
<h1><%= @site_name %></h1>
<p>Served by <%= @hostname %>.</p>

Step 3: the recipe

Ruby
# recipes/default.rb
apt_update 'refresh' if platform_family?('debian')

package 'nginx'

directory node['webserver']['docroot'] do
  recursive true
  mode '0755'
end

template '/etc/nginx/nginx.conf' do
  source 'nginx.conf.erb'
  owner 'root'
  group 'root'
  mode '0644'
  variables(
    port: node['webserver']['port'],
    worker_processes: node['webserver']['worker_processes'],
    docroot: node['webserver']['docroot'],
    gzip: node['webserver']['gzip']
  )
  verify 'nginx -t -c %{path}'
  notifies :reload, 'service[nginx]', :delayed
end

template "#{node['webserver']['docroot']}/index.html" do
  source 'index.html.erb'
  mode '0644'
  variables(site_name: node['webserver']['site_name'], hostname: node['hostname'])
end

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

Why it is built this way: the verify check blocks a broken config; the reload is delayed so one reload happens after all changes; service comes last, so the config is in place before the first start.

Step 4: a ChefSpec test

Ruby
# spec/unit/recipes/default_spec.rb
require 'chefspec'

describe 'webserver::default' do
  platform 'ubuntu', '24.04'

  it 'installs nginx and starts the service' do
    expect(chef_run).to install_package('nginx')
    expect(chef_run).to enable_service('nginx')
    expect(chef_run).to start_service('nginx')
  end

  it 'renders the config and reloads nginx when it changes' do
    config = chef_run.template('/etc/nginx/nginx.conf')
    expect(config).to notify('service[nginx]').to(:reload).delayed
  end

  context 'with a custom port' do
    override_attributes['webserver']['port'] = 9000

    it 'uses the custom port' do
      expect(chef_run).to render_file('/etc/nginx/nginx.conf').with_content(/listen 9000;/)
    end
  end
end

Step 5: Test Kitchen and InSpec

YAML
# kitchen.yml
driver:
  name: dokken
provisioner:
  name: dokken
transport:
  name: dokken
verifier:
  name: inspec
platforms:
  - name: ubuntu-24.04
    driver: { image: dokken/ubuntu-24.04 }
suites:
  - name: default
    run_list: ['recipe[webserver::default]']
Ruby
# test/integration/default/default_test.rb
describe package('nginx') { it { should be_installed } }
describe service('nginx') do
  it { should be_enabled }
  it { should be_running }
end
describe port(8080) { it { should be_listening } }
describe http('http://localhost:8080') do
  its('status') { should eq 200 }
  its('body') { should match(/Example Site/) }
end

Run cookstyle ., chef exec rspec, then kitchen test. Green on all three means the cookbook is ready for a Policyfile.

Simulation: converge the whole cookbook

The simulation applies the same recipe logic to an in-memory machine. It renders both templates with real ERB, installs the package, notifies the service, and runs twice to show idempotence. A second scenario changes an attribute and shows the delayed reload.

Ruby Stand-in: converge the webserver cookbook

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Run 1 installs everything and the service start covers the first reload. Run 2 changes nothing, which is what the second kitchen converge should also show. Run 3 changes only the config, and then the service is reloaded, not restarted.

Extensions to try

  1. Add a webserver::tls recipe that installs certificates from an encrypted data bag.
  2. Add a server_name list loop to the template, using an array attribute.
  3. Add a custom resource webserver_site so each virtual host is one resource.
  4. Put the cookbook in a Policyfile with a named_run_list and push it to staging.
  5. Replace the static page with a template built from search results (a list of backend nodes).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the nginx.conf template use verify 'nginx -t -c %{path}'?

    verify tests the rendered temporary file, so a broken config is never installed.
  2. 2. Why is the reload notification :delayed?

    Delayed notifications run after converge and are de-duplicated, so several changes cause one reload.
  3. 3. What does a second kitchen converge with no changes prove?

    A stable cookbook reports zero updated resources on the second run.
  4. 4. Where do values such as the port belong?

    Attributes make the cookbook configurable; variables pass the values to the template explicitly.

Summary

  • A good cookbook has metadata, attributes with defaults, templates, a short recipe, and tests at three levels (Cookstyle, ChefSpec, Kitchen with InSpec).
  • Templates take values through variables; verify protects against broken config; notifies ... :delayed gives one reload.
  • Idempotence means a second run changes nothing.
  • Extensions: TLS from data bags, custom resources, Policyfiles, search-driven pages.

Next: Project: A Multi-Environment Fleet