Sometime back I had to fiddle with Chef. I created some notes, posting it over here, so that I won’t loose it. Don’t think it’ll be useful much to anyone else other than me :) Its basically a list of instructions that is scattered on their site.

So, anyone other than me, please ignore this post!

Write a cookbook

chef generate repo ~/chef-repo => Install starter kit to create .chef directory and certs that we need to communicate with chef server

cd ~/chef-repo
chef generate cookbook cookbooks/COOKBOOK_NAME

Create a recipe:

chef generate recipe cookbooks/COOKBOOK_NAME RECIPE_NAME => RECIPE_NAME shouldn’t have suffix. Eg. it should be ‘webserver and not ‘webserver.rb’ => Write the script in RECIPE_NAME.rb file that got generated

How to refer(include) a recipe(RECIPE_NAME) in another recipe:

include_recipe 'COOKBOOK_NAME::RECIPE_NAME' => Eg: include_recipe ‘my_cookbook::webserver’

=> By default the recipe that gets called is ‘cookbooks/COOKBOOK_NAME/recipes/default.rb’ => So include any other recipe in this using include_recipe

Create a file:

chef generate file cookbooks/COOKBOOK_NAME FILE_NAME.txt


How to upload the cookbook to the chef server. There are 2 ways:

Option 1. Prefer this one. This one takes up the dependencies if any.

Create a file named Berksfile in the ~/chef-repo/cookbooks/COOKBOOK_NAME directory Add the following to that file:

source "https://supermarket.chef.io"
metadata

Install the dependencies: berks install

Finally upload (along with dependencies): berks upload => OR without SSL => berks upload --no-ssl-verify

Option 2. This one just uploads the cookbook. Won’t download dependencies

knife cookbook upload COOKBOOK_NAME

View uploaded cookbooks:

knife cookbook list

Bootstraping the node

knife ssl fetch ##Save the SSL certificate
knife bootstrap IP_ADDRESS_OF_NODE -x ROOT_USER_NAME -P ROOT_PASSWORD --sudo 

Verify bootstrap process was successful. Either check in chef manage console or do:

On Windows

knife node list | findstr NODE_NAME_WINDOWS

On Linux

knife node list | grep NODE_NAME_WINDOWS

How to reference another cookbook:

Append following to ~/chef-repo/cookbooks/COOKBOOK_NAME/metadata.rb: depends 'ANOTHER_COOKBOOK_NAME', '~> MAJOR.MINOR.PATCH' => Eg: depends 'sql_server', '~> 2.4.0'

How to override third party cookbook’s attributes:

Create a custom attribute file that overrides third party attribute values:

chef generate attribute cookbooks/COOKBOOK_NAME default

Add override values as follows in the generated ‘cookbooks/COOKBOOK_NAME/attributes/default.rb‘:

default['ANOTHER_COOKBOOK_NAME']['ATTRIBUTE_NAME'] = ATTRIBUTE_VALUE

Eg: default['sql_server']['accept_eula'] = true Eg: default['sql_server']['version'] = '2012' Eg: default['sql_server']['instance_name'] = 'MSSQLSERVER'

Modifying cookbook version:

Edit ~/chef-repo/cookbooks/COOKBOOK_NAME/metadata.rb to change the version

Applying cookbook on node:

Run the following directly on the NODE, (NOT ON THE workstation): chef-client