Chef Cheat Sheet: The Basics

The big data repository known as Chef Server is manipulated with a tool called knife. The general (simplified) syntax for this tool is:

$ knife category command item

The category can be one of: environment, client, node, data bag, cookbook, … The full list can be found here.

The command (usually) is one of create, list, show, edit or delete. There are more commands, though, depending on what is being requested through knife.

On the cheat sheat itself, let’s start with some classics:

Nodes and Environments

$ knife environment list
$ knife environment edit xxxx
$ knife node list 
$ knife node edit yyyy

Data Bags

As you may already know, data bags are stored in a 2 layer structure, thus allowing for simple categorization (e.g. grouping data bags by service or by environment). Some simple commands dealing with them may be:

$ knife data bag list xxdomain
$ knife data bag show xxdomain yyleaf
$ knife data bag edit xxdomain yyleaf

One can create a data bag with the editor or by providing a source file:

$ knife data bag create xxdomain yyleaf
$ knife data bag from file xxdomain file.json

The file may look like:

  "id": "yyleaf",
  "key": "value",

Finding nodes and environments

Very basic stuff:

$ knife environment list | grep xxenv
$ knife node list | grep xxnode

The node search above works if we know something about the node name; this may not always be the case. In an ideal scenario, nodes have names prefixed with the environment they belong to – this makes listing nodes by environment a trivial task by using some construct derived from the commands above. But when this is not the case:

$ knife search "chef_environment:xxenv"

NB: the search command returns a “summary” output. If one is interested in the node name alone, some output trimming must be performed:

$ knife search "chef_environment:xxenv" -a "name" 2>/dev/null | grep "name" | awk '{print $2}'

Running commands on multiple nodes

The basic way to do it is to capture the search result and run ssh on every node:

$ nodes=$(knife search "chef_environment:xxenv" -a "fqdn" 2>/dev/null | grep "fqdn" | awk '{print $2}')
$ for n in $nodes ; do ssh $n "zzcommand" ; done

One may improve it in a shell script in order to run the ssh commands in parallel and wait for their result; either way, it’s overengineering. The simple way to achieve such thing is:

$ knife ssh "chef_environment:xxenv" "zzcommand"

The search query can get even more complicated, allowing for complex queries to target individual nodes by their configuration:

$ knife ssh "chef_environment:xxenv AND recipe:xxrecp" "zzcommand"

… and from here, the sky is the limit. Thank you for your read!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.