---
title: "Chef"
lang: "en"
author: "Mohammad Abu Mattar"
canonical: https://mkabumattar.com/chef
---

0

[Home](/)›[Cheatsheets](/cheatsheets)

Cheatsheets

# Chef

Chef reference guide covering installation, cookbooks, recipes, resources, knife commands, server management, and automation workflows for infrastructure configuration management.

10 Categories28 Sections67 ExamplesPublished: 28 Feb 2026

[Markdown for AI(opens in a new tab)](/chef/index.md "Open the plain-Markdown version of this page, for pasting into an AI tool")

Series

[Infrastructure as Code Mastery](/series/infrastructure-as-code-mastery)2/2

[PreviousAnsible](/cheatsheets/ansible)

All posts in this series (2)

Cheatsheets2

1.  [Ansible](/cheatsheets/ansible)
2.  [ChefYou are here](/cheatsheets/chef)

Chef is an Infrastructure as Code platform for automating infrastructure configuration, deployment, and management. This cheatsheet covers Chef concepts, commands, patterns, and best practices for managing infrastructure with Chef Infra, Chef Server, and related tools.

[Getting Started](#category-gettingstarted)

-   [Installation & Setup](#section-installation)
-   [Chef Configuration](#section-chefconfig)
-   [Workstation Setup](#section-workstationsetup)

[Basic Resources](#category-basicresources)

-   [File Resource](#section-fileresource)
-   [Package Resource](#section-packageresource)
-   [Service Resource](#section-serviceresource)

[Recipes & Cookbooks](#category-recipesandcookbooks)

-   [Recipe Syntax](#section-recipesyntax)
-   [Cookbook Structure](#section-cookbookstructure)
-   [Recipe Patterns](#section-recipes)

[Knife Commands](#category-knifecommands)

-   [Node Management](#section-nodemanagement)
-   [Cookbook Operations](#section-cookbookops)
-   [Data Bags](#section-databag)

[Chef Server Management](#category-chefserver)

-   [Chef Server Setup](#section-serversetup)
-   [Chef Server Control Commands](#section-serverctl)

[Advanced Resources](#category-advancedresources)

-   [Template Resource](#section-templateresource)
-   [Execute Resource](#section-executeresource)
-   [Ruby Block Resource](#section-rubyblock)

[Attributes & Variables](#category-attributesvariables)

-   [Node Attributes](#section-attributes)
-   [Data Bags](#section-databags)
-   [Environments](#section-environments)

[Roles & Environments](#category-rolesandenvironments)

-   [Role Definition](#section-roles)
-   [Role Management](#section-rolemanagement)

[Testing & Validation](#category-testingvalidation)

-   [Test Kitchen](#section-kitchentesting)
-   [ChefSpec Unit Testing](#section-chefspec)
-   [InSpec Testing](#section-inspection)

[Cookbook Patterns & Workflows](#category-cookbookpatterns)

-   [Common Patterns](#section-patterns)
-   [Development Workflow](#section-workflow)
-   [Best Practices Summary](#section-bestpractices)

No commands found

Try adjusting your search term

## Getting Started

### Installation & Setup

Install Chef workstation and set up development environment

#### Accessibility

Beginner

#### Keywords

installsetupworkstationrequirementsdependencies

#### Install Chef Workstation on Linux

Code

Terminal window

```
wget https://packages.chef.io/files/stable/chef-workstation/23.10.1234/ubuntu/22.04/chef-workstation_23.10.1234-1_amd64.debsudo dpkg -i chef-workstation_23.10.1234-1_amd64.deb
```

#### Verify Chef Installation

Displays all installed Chef tools and versions

Code

Terminal window

```
chef --version
```

Execution

Terminal window

```
Chef Workstation: 23.10.1234Chef Infra Client: 18.3.0Chef InSpec: 5.22.3Chef Habitat: 1.6.521Test Kitchen: 3.5.0Cookstyle: 7.32.1
```

-   Chef client version 18+ recommended
-   Test Kitchen included in workstation

### Chef Configuration

Configure knife and chef client settings

#### Accessibility

Beginner

#### Keywords

configknife.rbclient.rbcredentials

#### Create knife Configuration

Basic knife.rb configuration for chef server connectivity

Code

```
1current_dir = File.dirname(__FILE__)2log_level                :info3log_location             STDOUT4node_name                'dev_user'5client_key               "#{current_dir}/dev_user.pem"6validation_client_name   'chef-validator'7validation_key           "#{current_dir}/chef-validator.pem"8chef_server_url          'https://chef.example.com/organizations/myorg'9cookbook_path            ["#{current_dir}/../cookbooks"]
```

-   Store in ~/.chef/knife.rb
-   PEM keys must have correct permissions (600)

#### Chef Client Configuration

Chef-client.rb configuration file

Code

```
1log_level :info2log_location "/var/log/chef-client.log"3chef_server_url "https://chef.example.com/organizations/myorg"4validation_client_name "chef-validator"5node_name Socket.gethostname
```

-   Located at /etc/chef/client.rb
-   Loaded on each chef-client run

### Workstation Setup

Initialize and configure Chef development workspace

#### Accessibility

Beginner

#### Keywords

workspacedirectorybootstrapknife

#### Generate Chef Repo

Creates standard Chef repository structure

Code

Terminal window

```
chef generate repo my-chef-repocd my-chef-repo
```

Execution

Terminal window

```
Generating Chef Infra repo my-chef-repo- Creating workspace directory structure- Creating default cookbooks directory- Creating default roles directory- Creating default environments directory- Creating data_bags directory
```

-   Generates .gitignore and basic files
-   Ready for git initialization

#### Generate Cookbook

Creates new cookbook with standard structure

Code

Terminal window

```
chef generate cookbook cookbooks/apache2
```

Execution

Terminal window

```
Generating cookbook apache2- Creating cookbook directory structure- Creating CHANGELOG.md- Creating metadata.rb- Creating README.md- Creating spec/spec_helper.rb- Creating .kitchen.yml
```

-   Creates ChefSpec and InSpec test files
-   Ready for Test Kitchen

## Basic Resources

### File Resource

Manage file creation, deletion, and modification

#### Accessibility

Beginner

#### Keywords

filecreatedeletemodifyrightsmodeowner

#### Create Simple File

Code

```
1file '/etc/app/config.txt' do2  content 'application configuration'3  owner 'root'4  group 'root'5  mode '0644'6  action :create7end
```

#### Create File with Content Test

Creates file with specific ownership and permissions

Code

```
1file '/var/log/app.log' do2  content "#{Time.now} - Application Started\n"3  owner 'app_user'4  group 'app_group'5  mode '0666'6end
```

Execution

Terminal window

```
Recipe: default* file[/var/log/app.log] action create- create new file /var/log/app.log- update permissions to 0666- update ownership to app_user:app_group
```

-   Mode as string with leading 0
-   Modes are octal: 0644, 0755, etc.

#### Delete File

Removes file from system

Code

```
1file '/etc/old-config.conf' do2  action :delete3end
```

-   Safe to run multiple times (idempotent)
-   Will not error if file doesn't exist

### Package Resource

Install, upgrade, and remove software packages

#### Accessibility

Beginner

#### Keywords

packageinstallremoveupgradeversion

#### Install Single Package

Code

```
1package 'nginx' do2  action :install3end
```

#### Install Multiple Packages

Installs multiple packages in single resource

Code

```
1package ['curl', 'wget', 'git', 'htop'] do2  action :install3end
```

Execution

Terminal window

```
Recipe: default* package[curl] action install- install version 7.68.0-1ubuntu1 of curl* package[wget] action install- install version 1.20.3-1 of wget* package[git] action install- install version 1:2.34.1-1ubuntu1 of git
```

-   Chef uses platform package manager
-   Version specified as :install installs latest
-   Use version attribute for specific version

#### Install Specific Version

Install specific version of package

Code

```
1package 'nginx' do2  version '1.18.0-0ubuntu1'3  action :install4end
```

-   Version must be available in package repository

### Service Resource

Manage system services startup and runtime

#### Accessibility

Beginner

#### Keywords

servicestartstoprestartenablemanagable

#### Start and Enable Service

Code

```
1service 'nginx' do2  supports status: true, restart: true, reload: true3  action [:enable, :start]4end
```

#### Restart Service on Configuration Change

File change triggers service restart with notifications

Code

```
1file '/etc/nginx/nginx.conf' do2  content node['nginx']['config']3  notifies :restart, 'service[nginx]', :immediately4end5
6service 'nginx' do7  supports status: true, restart: true8  action :nothing9end
```

Execution

Terminal window

```
Recipe: default* file[/etc/nginx/nginx.conf] action create- update content in file /etc/nginx/nginx.conf* service[nginx] action restart- restart service nginx
```

-   :immediately processed before other resources
-   :action :nothing prevents immediate service start

#### Stop and Disable Service

Stops running service and disables autostart

Code

```
1service 'old-service' do2  action [:stop, :disable]3end
```

-   Disable prevents service from starting on boot

## Recipes & Cookbooks

### Recipe Syntax

Write Chef recipes with proper Ruby syntax

#### Accessibility

Beginner

#### Keywords

reciperubysyntaxresourcesaction

#### Basic Recipe Structure

Complete recipe with multiple resources

Code

default.rb

```
1description 'Install and configure web server'2
3package 'apache2'4
5service 'apache2' do6  action [:enable, :start]7end8
9file '/var/www/html/index.html' do10  content '<h1>Welcome</h1>'11  mode '0644'12end
```

-   Recipes are Ruby files
-   Comments start with
-   Executed top to bottom

#### Conditional Execution

Only run resources based on conditions

Code

```
1package 'mysql-server' do2  action :install3  only_if { node['install_database'] == true }4end5
6execute 'initialize-db' do7  command 'mysql_install_db'8  not_if 'test -d /var/lib/mysql/mysql'9end
```

-   only\_if: resource executes only if condition true
-   not\_if: resource executes only if condition false

### Cookbook Structure

Organize cookbooks with files, templates, attributes

#### Accessibility

Beginner

#### Keywords

cookbookstructurefilestemplatesattributesmetadata

#### Cookbook Directory Layout

Standard cookbook directory structure

Code

Terminal window

```
cookbooks/apache2/├── recipes/│   ├── default.rb│   ├── server.rb│   └── ssl.rb├── files/│   ├── default/│   │   └── httpd.conf├── templates/│   ├── default/│   │   └── apache2.conf.erb├── attributes/│   ├── default.rb│   └── server.rb├── metadata.rb├── README.md└── .kitchen.yml
```

-   recipes/: Chef recipes
-   files/: Static files (binaries, configs)
-   templates/: Templated files with variables (ERB)
-   attributes/: Default attribute values

#### Cookbook Metadata

Cookbook metadata with dependencies

Code

```
1name 'apache2'2maintainer 'Chef Community'3maintainer_email 'cookbooks@example.com'4description 'Installs and configures Apache web server'5version '14.0.0'6license 'Apache-2.0'7chef_version '>= 16.0'8
9depends 'openssl'10depends 'httpd'11
12supports 'ubuntu', '>= 18.04'13supports 'centos', '>= 7.0'
```

-   version in semantic versioning
-   depends: cookbook dependencies
-   supports: compatible operating systems

### Recipe Patterns

Common recipe patterns and best practices

#### Accessibility

Intermediate

#### Keywords

patternrecipeidempotentconvergeguard

#### Idempotent File Installation

Downloads file only if not already present

Code

```
1remote_file '/opt/app/binary' do2  source 'https://downloads.example.com/app-1.0.tar.gz'3  checksum 'abcd1234ef567890'4  mode '0755'5  action :create_if_missing6end
```

-   create\_if\_missing prevents re-download
-   checksum validates file integrity
-   Idempotent: safe to run multiple times

#### Recipe with Node Attributes

Use node attributes in recipes

Code

```
1package node['packages']['webserver']2
3service node['services']['webserver'] do4  action [:enable, :start]5end6
7node.override['app']['installed'] = true
```

-   node\[\] accesses attribute values
-   node.override sets attribute value
-   Attributes from multiple sources merged

## Knife Commands

### Node Management

List, bootstrap, and manage Chef nodes

#### Accessibility

Intermediate

#### Keywords

knifenodebootstraplistshowdelete

#### Bootstrap Node

Bootstrap installs Chef client and runs initial recipes

Code

Terminal window

```
knife bootstrap 192.168.1.100 -u ubuntu -i ~/.ssh/key.pem -N webserver01 --run-list 'recipe[apache2]' --sudo
```

Execution

Terminal window

```
Connecting to 192.168.1.100192.168.1.100 ➜ Installing Chef Infra Client 18.3.0...192.168.1.100 ➜ Chef Infra Client successfully installed192.168.1.100 ➜ Starting Chef Infra Client, version 18.3.0192.168.1.100 ➜ Running handlers: [chef-client-finished]192.168.1.100 ➜ Chef Infra Client finished, 8/8 resources updated in 25 seconds
```

-   Default runs once for initial setup
-   \-N sets node name in Chef Server
-   \--run-list specifies recipes to execute

#### List All Nodes

Shows all nodes registered with Chef Server

Code

Terminal window

```
knife node list
```

Execution

Terminal window

```
database01webserver01webserver02loadbalancer01
```

-   Requires knife.rb configuration
-   Only shows registered nodes

#### Show Node Details

Detailed information about specific node

Code

Terminal window

```
knife node show webserver01
```

Execution

Terminal window

```
Node Name: webserver01Environment: productionFQDN: webserver01.example.comIP: 192.168.1.100Run List: recipe[apache2], recipe[php]Roles: [web_server]Chef Version: 18.3.0Platform: ubuntu 22.04 x86_64Attributes:  apache:    port: 80    workers: 4
```

-   Shows attributes, run\_list, roles
-   Platform and Chef version visible

### Cookbook Operations

Manage and upload cookbooks

#### Accessibility

Intermediate

#### Keywords

cookbookuploaddeletelisttestlint

#### Upload Cookbook

Uploads cookbook to Chef Server

Code

Terminal window

```
knife cookbook upload apache2 -o cookbooks/
```

Execution

Terminal window

```
Uploading apache2 [14.0.0]Uploaded 1 cookbookapache2 [14.0.0]
```

-   \-o specifies cookbook directory
-   Version in metadata.rb required
-   Creates version in Chef Server

#### Lint Cookbook

Lint checks and corrects cookbook code style

Code

Terminal window

```
cookstyle cookbooks/apache2 --autocorrect
```

Execution

Terminal window

```
Inspecting 8 files6 files OK2 files corrected
```

-   cookstyle is Chef's linter
-   \--autocorrect fixes style issues
-   Runs before uploading

#### Delete Cookbook

Removes cookbook version from Chef Server

Code

Terminal window

```
knife cookbook delete apache2 -v 14.0.0
```

-   \-v specifies version to delete
-   Requires confirmation

### Data Bags

Manage encrypted data and secrets

#### Accessibility

Intermediate

#### Keywords

databagcreateeditsecretencryption

#### Create Data Bag

Creates new data bag container

Code

Terminal window

```
knife data bag create users
```

Execution

Terminal window

```
Created data_bag[users]
```

-   Data bags store JSON data
-   Can contain multiple items

#### Create Encrypted Data Bag Item

Creates encrypted data bag item

Code

Terminal window

```
knife data bag create secrets db_password --secret-file ~/.chef/encrypted_data_bag_secret
```

Execution

Terminal window

```
Created data_bag_item[secrets::db_password]
```

-   Secret file required for encryption
-   Stored encrypted on Chef Server

## Chef Server Management

### Chef Server Setup

Install and configure Chef Server

#### Accessibility

Advanced

#### Keywords

serverinstallsetupconfigurationbackendfrontend

#### Install Chef Server

Install and configure Chef Server

Code

Terminal window

```
wget https://packages.chef.io/files/stable/chef-server/15.5.1234/ubuntu/22.04/chef-server-core_15.5.1234-1_amd64.debsudo dpkg -i chef-server-core_15.5.1234-1_amd64.debsudo chef-server-ctl reconfigure
```

Execution

Terminal window

```
Chef Server Starting...* omnibus-ctl (default) -> install* chef-server-postgresql (default) -> install* opscode-erchef (default) -> install* nginx (default) -> installChef Server configured and started successfully
```

-   Requires 4GB minimum RAM
-   PostgreSQL backend required
-   Takes time on first run

#### Create Organization

Create new organization on Chef Server

Code

Terminal window

```
sudo chef-server-ctl org-create myorg "My Organization" --filename myorg-validator.pem
```

Execution

Terminal window

```
Organization myorg created successfullyValidator key written to myorg-validator.pem
```

-   Requires admin credentials
-   Generates validator key for bootstrapping

### Chef Server Control Commands

Administrative commands for Chef Server

#### Accessibility

Advanced

#### Keywords

chef-server-ctlstatususerorggrant

#### Check Chef Server Status

Shows status of all Chef Server services

Code

Terminal window

```
sudo chef-server-ctl status
```

Execution

Terminal window

```
run: chef-server-postgresql: (pid 1234) 5678s; run: log: (pid 1235) 98srun: opscode-erchef: (pid 1236) 5600s; run: log: (pid 1237) 98srun: nginx: (pid 1238) 5580s; run: log: (pid 1239) 98sdown: opscode-solr4: 10s, normally up; run: log: (pid 1240) 98s
```

-   All services should show run
-   Verify connectivity issues with status

#### Create Admin User

Creates new admin user

Code

Terminal window

```
sudo chef-server-ctl user-create admin Admin User admin@example.com --filename admin.pem
```

Execution

Terminal window

```
User admin created successfullyPrivate key written to admin.pem
```

-   Save private key securely
-   Can grant org permissions

#### Grant User Permissions

Grants server admin permissions to user

Code

Terminal window

```
sudo chef-server-ctl grant-server admin admin
```

-   Must include org and user
-   Requires restart after changes

## Advanced Resources

### Template Resource

Create files from ERB templates with variables

#### Accessibility

Intermediate

#### Keywords

templateerbvariabledynamicrender

#### Simple ERB Template

Code

```
1template '/etc/app/config.conf' do2  source 'config.conf.erb'3  owner 'app'4  group 'app'5  mode '0644'6  variables(7    app_name: 'MyApp',8    port: 8080,9    environment: node.chef_environment10  )11  notifies :restart, 'service[app]'12end
```

#### ERB Template File Content

Template renders with variables substituted

Code

```
1# Configuration for <%= @app_name %>2server {3  listen <%= @port %>;4  server_name _;5
6  # Environment: <%= @environment %>7  <% if @environment == 'production' %>8    access_log /var/log/nginx/access.log combined;9  <% else %>10    access_log /var/log/nginx/dev-access.log;11  <% end %>12}
```

Execution

Terminal window

```
# Configuration for MyAppserver {  listen 8080;  server_name _;
  # Environment: production  access_log /var/log/nginx/access.log combined;}
```

-   ERB syntax <%= %> for output
-   <% %> for logic without output
-   Variables passed to template via hash

#### Template with Lazy Attribute

Lazy attribute evaluates at convergence time

Code

```
1template '/etc/mysql/my.cnf' do2  source 'my.cnf.erb'3  variables lazy {4    {5      max_connections: node['mysql']['max_connections'],6      port: node['mysql']['port']7    }8  }9  action :create10end
```

-   Lazy {} defers evaluation
-   Useful for dynamic attribute values
-   Re-evaluates on each run

### Execute Resource

Run arbitrary commands on target system

#### Accessibility

Intermediate

#### Keywords

executecommandshellbashguardtimeout

#### Simple Execute Command

Code

```
1execute 'bash /usr/local/bin/install-app.sh' do2  not_if 'test -d /opt/app'3end
```

#### Execute with Guard Clause

Execute resource with guard prevents duplicate initialization

Code

```
1execute 'initialize-database' do2  command '/usr/bin/mysql_install_db'3  user 'mysql'4  group 'mysql'5  only_if { !::File.exist?('/var/lib/mysql/mysql') }6end
```

Execution

Terminal window

```
Recipe: default* execute[initialize-database] action run- execute /usr/bin/mysql_install_db
```

-   only\_if prevents execution if condition met
-   Command must be idempotent

#### Execute with Timeout

Execute command with time limit

Code

```
1execute 'build-application' do2  command 'make build && make test'3  cwd '/opt/src'4  timeout 6005  user 'ubuntu'6end
```

-   Timeout in seconds
-   cwd changes working directory
-   Useful for long-running builds

### Ruby Block Resource

Execute Ruby code within recipes

#### Accessibility

Advanced

#### Keywords

ruby\_blockcodeevalnotification

#### Ruby Block with Notification

Code

```
1ruby_block 'create_application_user' do2  block do3    shell_out!('useradd -m -s /bin/bash appuser')4  end5  not_if { ::File.exist?('/home/appuser') }6end
```

#### Ruby Block to Set Attributes

Ruby block generates API key and sets attribute

Code

```
1ruby_block 'generate-api-key' do2  block do3    key = SecureRandom.hex(32)4    node.override['app']['api_key'] = key5    Chef::Log.info("Generated API key: #{key}")6  end7  action :run8end
```

-   Block contains arbitrary Ruby code
-   shell\_out! executes shell commands
-   Can set node attributes

## Attributes & Variables

### Node Attributes

Set and manage node attributes

#### Accessibility

Intermediate

#### Keywords

attributedefaultoverrideautomaticattribute\_file

#### Default Attributes File

Code

attributes/default.rb

```
1default['apache2']['port'] = 802default['apache2']['workers'] = 43default['apache2']['modules'] = %w(mod_rewrite mod_ssl)4default['apache2']['config_dir'] = '/etc/apache2'
```

#### Override Attributes

Override attributes set higher priority

Code

attributes/override.rb

```
1override['apache2']['port'] = 80802override['apache2']['workers'] = 8
```

-   default lowest priority
-   override highest priority
-   Node attributes in middle

#### Access Attributes in Recipe

Access attributes using node\[\] syntax

Code

```
1package 'apache2'2
3template '/etc/apache2/apache2.conf' do4  variables(5    port: node['apache2']['port'],6    workers: node['apache2']['workers'],7    modules: node['apache2']['modules']8  )9end
```

-   node\['key'\] accesses attribute value
-   node\['key'\] = value sets attribute
-   Attributes come from multiple sources

### Data Bags

Store shared data and secrets

#### Accessibility

Intermediate

#### Keywords

databagsecretsjsonencryption

#### Data Bag Item Structure

Code

```
1{2  "id": "db_user",3  "username": "appdb",4  "password": "encrypted_password",5  "host": "database.example.com"6}
```

#### Access Data Bag in Recipe

Load and use data bag item in recipe

Code

```
1db_config = data_bag_item('database', 'db_user')2
3template '/etc/app/database.yml' do4  variables(5    host: db_config['host'],6    username: db_config['username'],7    password: db_config['password']8  )9end
```

-   data\_bag\_item(bag, item) loads data
-   Encrypted items auto-decrypted
-   Secret file required for decryption

### Environments

Create and manage environment configurations

#### Accessibility

Intermediate

#### Keywords

environmentproductionstagingdevelopmentcookbook\_versions

#### Environment Definition

Production environment with cookbook versions

Code

```
1name 'production'2description 'Production environment'3
4cookbook_versions(5  'apache2' => '= 14.0.0',6  'mysql' => '= 8.4.0'7)8
9override_attributes(10  apache2: { port: 80 },11  mysql: { max_connections: 1000 }12)
```

-   cookbook\_versions locks recipe versions
-   override\_attributes apply to all nodes
-   Located in environments/ directory

#### Access Environment in Recipe

Conditional logic based on environment

Code

```
1if node.chef_environment == 'production'2  Chef::Log.warn("Running in PRODUCTION")3  node.override['app']['debug'] = false4else5  node.override['app']['debug'] = true6end
```

-   node.chef\_environment returns environment name
-   Useful for environment-specific configs

## Roles & Environments

### Role Definition

Create and manage roles

#### Accessibility

Intermediate

#### Keywords

rolenamedescriptionrun\_listattributes

#### Web Server Role

Role with recipes and attributes

Code

```
1name 'web_server'2description 'Web server role for application'3
4run_list(5  'recipe[apache2]',6  'recipe[php]',7  'recipe[ssl]'8)9
10override_attributes(11  apache2: {12    port: 80,13    max_clients: 25614  }15)
```

-   run\_list specifies recipes
-   Roles can include other roles
-   override\_attributes apply when role assigned

#### Database Server Role

Database server role with MySQL recipes

Code

```
1name 'database_server'2description 'Primary database server'3
4run_list(5  'recipe[mysql::server]',6  'recipe[mysql::replication]'7)8
9override_attributes(10  mysql: {11    server_id: 1,12    max_connections: 50013  }14)
```

-   Dedicated role for database servers
-   Includes replication configuration

### Role Management

Create and apply roles to nodes

#### Accessibility

Intermediate

#### Keywords

kniferolecreateuploadapply

#### Upload Role to Server

Code

Terminal window

```
knife role from file roles/web_server.rb
```

#### Assign Role to Node

Updates node's run list to include role

Code

Terminal window

```
knife node run_list set webserver01 'role[web_server]'
```

Execution

Terminal window

```
Set the run list to ['role[web_server]'] for node webserver01
```

-   Role must exist on Chef Server
-   Run list can include multiple roles

#### Add Recipe to Existing Run List

Appends recipe to node's run list

Code

Terminal window

```
knife node run_list add webserver01 'recipe[monitoring]'
```

Execution

Terminal window

```
Run List: recipe[monitoring], role[web_server]
```

-   New recipes added to end
-   Can specify position with -a option

## Testing & Validation

### Test Kitchen

Local testing of cookbooks with Test Kitchen

#### Accessibility

Intermediate

#### Keywords

kitchentestlocalconvergeverify

#### Kitchen Configuration

Test Kitchen configuration for two platforms

Code

.kitchen.yml

```
1driver:2  name: vagrant3provisioner:4  name: chef-zero5platforms:6  - name: ubuntu-22.047  - name: centos-88suites:9  - name: default10    run_list:11      - recipe[apache2::default]12    attributes:
```

-   Defines test platforms and driver
-   run\_list specifies recipes to test
-   Can test multiple suites

#### Kitchen Test Lifecycle

Complete kitchen test creates, converges, and destroys instance

Code

Terminal window

```
kitchen test default-ubuntu-2204
```

Execution

Terminal window

```
-----> Starting Test Kitchen-----> Creating <default-ubuntu-2204>...-----> Kitchen is finished. (15m4s)-----> Creating <default-ubuntu-2204>...  Instance created on 192.168.56.101-----> Converging <default-ubuntu-2204>...  Chef Infra Client, version 18.3.0  Running handlers:  Chef Infra Client finished, 7/7 resources updated-----> Verifying <default-ubuntu-2204>...-----> Kitchen is finished. (18m16s)
```

-   kitchen test is full cycle
-   Creates VM, runs chef, runs tests, destroys
-   Test output shows convergence

#### Kitchen Commands

Individual kitchen lifecycle steps

Code

Terminal window

```
kitchen listkitchen createkitchen convergekitchen verifykitchen destroy
```

-   list: shows test instances
-   create: creates instances
-   converge: runs chef client
-   verify: runs InSpec tests
-   destroy: removes instances

### ChefSpec Unit Testing

Unit test recipes with ChefSpec

#### Accessibility

Advanced

#### Keywords

chefspecunittestspecrspec

#### ChefSpec Test File

ChefSpec tests recipe behavior

Code

```
1require 'spec_helper'2
3describe 'apache2::default' do4  let(:chef_run) do5    ChefSpec::SoloRunner.new(platform: 'ubuntu', version: '22.04').converge(described_recipe)6  end7
8  it 'converges successfully' do9    expect { chef_run }.not_to raise_error10  end11
12  it 'installs apache2 package' do13    expect(chef_run).to install_package('apache2')14  end15
16  it 'enables and starts service' do17    expect(chef_run).to enable_service('apache2')18    expect(chef_run).to start_service('apache2')19  end20end
```

-   Uses RSpec framework
-   Mock convergence without real systems
-   Fast feedback on recipe changes

#### Run ChefSpec Tests

ChefSpec test execution results

Code

Terminal window

```
chef exec rspec
```

Execution

Terminal window

```
apache2::default  converges successfully  installs apache2 package  enables and starts service
Finished in 0.34 seconds3 examples, 0 failures
```

-   Fast feedback on recipe changes
-   Run before kitchen tests

### InSpec Testing

Integration testing with InSpec

#### Accessibility

Advanced

#### Keywords

inspectestintegrationverifycontrols

#### InSpec Control

InSpec controls verify infrastructure state

Code

```
1control 'apache-package-1' do2  title 'Apache2 package is installed'3  desc 'Verify Apache web server package is installed'4  impact 1.05  describe package('apache2') do6    it { should be_installed }7  end8end9
10control 'apache-service-1' do11  title 'Apache2 service is enabled'12  desc 'Verify Apache web server is enabled and active'13  impact 1.014  describe service('apache2') do15    it { should be_installed }16    it { should be_enabled }17    it { should be_running }18  end19end
```

-   Controls test actual system state
-   impact indicates severity (0-1.0)
-   describe blocks contain assertions

#### Run InSpec Tests

InSpec test execution shows all controls pass

Code

Terminal window

```
inspec exec test/integration/default/default.rb
```

Execution

Terminal window

```
Profile Summary: 2 successful controls, 0 control failures, 0 skippedTest Summary: 5 successful, 0 failures, 0 skipped
```

-   Runs against real or test systems
-   Verbose output shows each check
-   Failures reported with details

## Cookbook Patterns & Workflows

### Common Patterns

Recommended patterns for cookbook development

#### Accessibility

Intermediate

#### Keywords

patternbest\_practicereusablemodularityDRY

#### Wrapper Cookbook Pattern

Wrapper cookbook includes and customizes library cookbook

Code

cookbooks/production-apache2/recipes/default.rb

```
1include_recipe 'apache2::default'2
3node.override['apache2']['port'] = 4434node.override['apache2']['ssl_enabled'] = true5
6include_recipe 'apache2::ssl'
```

-   Separates library from production code
-   Keeps library cookbooks generic
-   Wrapper applies production config

#### Helper Methods in Libraries

Code

cookbooks/apache2/libraries/helpers.rb

```
1module Apache2Helper2  def self.apache_user3    node['apache2']['user']4  end5
6  def self.apache_group7    node['apache2']['group']8  end9end
```

#### Use Library Methods

Helpers reduce code duplication across recipes

Code

```
1# recipe using helper2file '/etc/apache2/config' do3  owner Apache2Helper.apache_user4  group Apache2Helper.apache_group5end
```

-   Libraries loaded before recipes
-   Reusable logic in helper methods

### Development Workflow

Recommended cookbook development workflow

#### Accessibility

Intermediate

#### Keywords

workflowdeveloptestlintupload

#### Full Development Workflow

Complete workflow from development to production

Code

Terminal window

```
# 1. Create cookbookchef generate cookbook cookbooks/apache2
# 2. Edit recipes and testsvi cookbooks/apache2/recipes/default.rbvi cookbooks/apache2/test/integration/default/default_spec.rb
# 3. Lint codecookstyle cookbooks/apache2 --autocorrect
# 4. Run unit testschef exec rspec cookbooks/apache2
# 5. Test on local VMkitchen test
# 6. Upload to Chef Serverknife cookbook upload apache2 -o cookbooks/
# 7. Converge nodeknife ssh 'role:web_server' 'sudo chef-client'
```

-   Iterative process with feedback loops
-   Test before uploading to server
-   Use version control for all changes

#### Converge Multiple Nodes

Converge all nodes with web\_server role

Code

Terminal window

```
knife ssh 'role:web_server' 'sudo chef-client' -a ipaddress
```

Execution

Terminal window

```
Starting Chef Infra Client, version 18.3.0resolving cookbooks for run list: ["role[web_server]"]Synchronizing Cookbooks:  - apache2 (14.0.0)  - php (8.0.0)Running handlers:Chef Infra Client finished, 8/8 resources updated in 32 seconds
```

-   knife ssh targets nodes by search query
-   \-a specifies attribute for connection
-   Executes command on matching nodes

### Best Practices Summary

Final best practices checklist

#### Accessibility

Beginner

#### Best Practices

-   Always use guard clauses (only\_if, not\_if) for idempotency
-   Use notifications instead of hardcoded dependencies
-   Keep cookbooks small and focused on single responsibility
-   Use attributes for configuration, not hardcoding values
-   Test all changes with ChefSpec and Kitchen before production
-   Use consistent naming for recipes and resources
-   Document features in README.md and comments
-   Use data bags for secrets, never hardcode passwords
-   Version cookbook dependencies explicitly
-   Run cookstyle for linting before upload

#### Common Errors

-   **Non-idempotent recipes cause unexpected changes.:** Always use guard clauses
-   **Hardcoded values make cookbooks unmaintainable.:** Use attributes instead
-   **Forgetting to upload a cookbook after changes.:** Run knife upload before convergence
-   **Missing dependencies between resources.:** Use notifications and subscriptions
-   **Testing only on one platform misses compatibility issues.:** Test on multiple operating systems
-   **Not encrypting secrets in data bags.:** Store passwords securely
-   **Overcomplicating recipes reduces readability.:** Keep recipes simple
-   **Ignoring chef-client run output makes debugging difficult.:** Always review the logs

#### Keywords

practicechecklistdesignsecuritymaintenance

[Learn more](https://docs.chef.io/chef_cookbook_patterns/)

#### Recipe Best Practices

Common recipe best practices

Code

```
1# Good Recipe Practices2
3# 1. Use meaningful resource names4service 'webserver' do5  service_name 'apache2'  # Use if name differs6  action [:enable, :start]7end8
9# 2. Use guard clauses for idempotency10package 'nginx' do11  action :install12  not_if 'which nginx'13end14
15# 3. Use notifications for dependencies16file '/etc/nginx/nginx.conf' do17  content lazy { IO.read(template_file) }18  notifies :reload, 'service[nginx]'19end20
21# 4. Log important information22ruby_block 'app-initialized' do23  block { Chef::Log.info "Application initialized" }24end
```

-   Guard clauses keep resources idempotent
-   Notifications manage dependencies
-   Logging aids debugging

Was this useful?

## Share

[Facebook](https://facebook.com/sharer/sharer.php?u=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fchef "Share on Facebook")[Twitter](https://twitter.com/intent/tweet/?text=Chef&url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fchef "Share on Twitter")[LinkedIn](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fchef&title=Chef&summary=Chef%20reference%20guide%20covering%20installation%2C%20cookbooks%2C%20recipes%2C%20resources%2C%20knife%20commands%2C%20server%20management%2C%20and%20automation%20workflows%20for%20infrastructure%20configuration%20management.&source=https://mkabumattar.com "Share on LinkedIn")[WhatsApp](https://wa.me/?text=Chef%20https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fchef "Share on WhatsApp")[Telegram](https://t.me/share/url?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fchef&text=Chef "Share on Telegram")[Reddit](https://www.reddit.com/submit?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fchef&title=Chef "Share on Reddit")[Hacker News](http://news.ycombinator.com/submitlink?u=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fchef&t=Chef "Share on Hacker News")[Pinterest](https://pinterest.com/pin/create/button/?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fchef&media=&description=Chef%20reference%20guide%20covering%20installation%2C%20cookbooks%2C%20recipes%2C%20resources%2C%20knife%20commands%2C%20server%20management%2C%20and%20automation%20workflows%20for%20infrastructure%20configuration%20management. "Share on Pinterest")[Email](<mailto:?subject=Chef&body=Check out this article: https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fchef>)

## Comments

## You might also enjoy

More posts on similar topics

## [Ansible](/cheatsheets/ansible)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Reference

Ansible is an automation tool for configuration management, application deployment, and orchestration. This cheatsheet is a quick reference for common Ansible tasks, modules, and best practices.

[read more](/cheatsheets/ansible)

## [Docker Compose](/cheatsheets/docker-compose)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Reference

Docker Compose is a tool for defining and running multi-container Docker applications. It uses a YAML file to configure application services, networks, and volumes. This cheatsheet provides a quick re

[read more](/cheatsheets/docker-compose)

## [Dockerfile](/cheatsheets/dockerfile)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Reference

This cheat sheet covers the core Dockerfile instructions, best practices, and common pitfalls for building small, secure Docker images. Each section pairs a Dockerfile snippet with the build output it

[read more](/cheatsheets/dockerfile)

## [PostgreSQL](/cheatsheets/postgresql)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Reference

PostgreSQL reference guide covering psql commands, database creation, tables, queries, functions, joins, transactions, indexes, and advanced SQL operations.

[read more](/cheatsheets/postgresql)

## [Redis](/cheatsheets/redis)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Reference

Redis reference guide covering commands, data types, keys, strings, lists, sets, hashes, sorted sets, transactions, pub/sub, and caching strategies.

[read more](/cheatsheets/redis)

## [SSH](/cheatsheets/ssh)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Reference

export const components = { h1: 'h1', h2: 'h2', h3: 'h3', h4: 'h4', h5: 'h5', h6: 'h6', p: 'p', a: 'a', ul: 'ul', ol: 'ol', li: 'li', code: 'code', pre: 'pre', strong: 'str

[read more](/cheatsheets/ssh)

6 related posts
