Chef Cheat Sheet
Reference for Chef recipes, resources, cookbooks, and knife CLI commands used for infrastructure automation.
Basic Recipe
A recipe installing and configuring nginx.
package 'nginx' do action :installendtemplate '/etc/nginx/nginx.conf' do source 'nginx.conf.erb' owner 'root' group 'root' mode '0644' variables(port: node['nginx']['port']) notifies :restart, 'service[nginx]'endservice 'nginx' do action [:enable, :start]end
Core Concepts
Key Chef terminology and building blocks.
- cookbook- A packaged unit of recipes, attributes, templates, and files
- recipe- A Ruby DSL file declaring the desired state of resources
- resource- A statement describing a piece of system state (package, file, service)
- node- A managed machine running chef-client, with its own attributes
- run-list- Ordered list of recipes/roles applied to a node
- attributes- Configurable settings that parameterize recipes per node/environment
- data bag- Global JSON store for data shared across cookbooks (e.g. secrets, users)
Knife CLI
Common knife commands for managing the Chef ecosystem.
knife cookbook create my_cookbook # Scaffold a cookbookknife cookbook upload my_cookbook # Upload to Chef Serverknife node list # List managed nodesknife node run_list add NODE 'recipe[my_cookbook]'knife ssh 'role:web' 'sudo chef-client' # Run chef-client remotelyknife bootstrap NODE_IP -x user -P pass --node-name web1
metadata.rb
Cookbook metadata file declaring name, version, dependencies.
name 'my_cookbook'maintainer 'DevOps Team'version '1.2.0'depends 'nginx', '~> 12.0'supports 'ubuntu'supports 'centos'
Custom Resource
Define a reusable custom resource with properties and an action block.
# resources/site.rbproperty :app_name, String, name_property: trueproperty :port, Integer, default: 8080property :enable_ssl, [true, false], default: falseaction :create do directory "/var/www/#{new_resource.app_name}" do owner 'deploy' mode '0755' recursive true end template "/etc/nginx/sites-available/#{new_resource.app_name}" do source 'vhost.erb' variables(port: new_resource.port, ssl: new_resource.enable_ssl) notifies :reload, 'service[nginx]', :delayed endend# Usage in a recipe:# my_site 'blog' do# port 3000# action :create# end
Guards & Notification Timing
Use only_if/not_if guards and control whether notifications fire immediately or at end of run.
execute 'migrate_db' do command 'rake db:migrate' cwd '/srv/app' only_if { File.exist?('/srv/app/Rakefile') } not_if 'rake db:migrate:status | grep -q up' notifies :restart, 'service[app]', :immediatelyendtemplate '/etc/app/config.yml' do source 'config.yml.erb' # :delayed (default) batches the notification to run once at the end # :immediately runs it right after this resource converges notifies :reload, 'service[app]', :delayedend
Chef Search API
Query the Chef Server index from a recipe to build dynamic, role-aware configuration.
# Find all nodes with role[web] in the current environmentweb_nodes = search(:node, "role:web AND chef_environment:#{node.chef_environment}")web_ips = web_nodes.map { |n| n['ipaddress'] }template '/etc/haproxy/haproxy.cfg' do source 'haproxy.cfg.erb' variables(backends: web_ips) notifies :reload, 'service[haproxy]'end# partial_search is faster when you only need specific attributespartial_search(:node, 'role:db', keys: { 'ip' => ['ipaddress'], 'name' => ['name'] }).each { |r| puts r['ip'] }
Advanced Chef Ecosystem
Tooling and concepts beyond basic recipes for production Chef workflows.
- why-run mode- `chef-client --why-run` simulates convergence without changing the system, similar to a dry run
- Policyfiles- Modern dependency/version pinning mechanism replacing environments + Berkshelf for cookbook resolution
- Ohai- Tool that collects system state (node attributes) at the start of every chef-client run
- Chef InSpec- Separate compliance-as-code framework for auditing node state independent of convergence
- compile phase- First pass where the resource collection is built by evaluating recipe Ruby code top to bottom
- converge phase- Second pass where each resource in the collection is actually executed against the system
- chef-shell- Interactive REPL for testing recipe code and resource behavior against a node
- custom resources- Reusable, versioned abstractions (replacing legacy LWRPs) defined under `resources/`
Roles & Environments
Group nodes and pin cookbook versions using roles and environments.
# roles/web.rbname 'web'description 'Web server role'run_list 'recipe[nginx]', 'recipe[myapp::deploy]'default_attributes 'nginx' => { 'worker_processes' => 4 }# environments/production.rbname 'production'description 'Production environment'cookbook_versions 'myapp' => '= 2.3.0', 'nginx' => '~> 12.0'default_attributes 'myapp' => { 'log_level' => 'warn' }
Use Test Kitchen ('kitchen converge' / 'kitchen verify') to spin up isolated VMs or containers and validate recipes before uploading to your Chef Server.