Knife Audit to get used and unused cookbooks from chef server

turned on laptop computer
Reading Time: 2 minutes

Hello all, today we are going to do a task related to automation in chef. We are going to create a bash script to get all used and unused cookbooks from chef server using knife audit, and also will be deleting unused cookbooks. We can run this script as cron to achieve full automation.

Download and Install Chef Workstation

First thing first, we are going to install chef in our system. I am using Amazon linux machine. If you have other machine type then do accordingly. For ubuntu instead of yum use apt

Download starter kit

  • Visit . If you are new to chef server, please create a new account otherwise login
  • Go to administration and choose you organization
  • On your left hand side click on starter kit and download it
  • A zip file be downloaded. unzip it and go inside chef-repo directory. Now you are connected with your chef server

Install Knife Audit

  • We need to have .chef/plugins/knife directory inside chef-repo. If you don’t have it then please make it using mkdir or any other method
  • Now create a file named audit.rb inside .chef/plugins/knife directory
  • visit
  • Copy the content and paste it in newly created audit.rb file
  • Install gem if not present -> sudo yum install gem -y
  • Install knife audit -> gem install knife-audit

Bash Script

Now, we are going to create a bash script to get unused cookbooks and delete from the chef server

Create a file inside chef-repo directory. Now paste the following code in

knife audit | tail -n +2 | awk '{ if($2 == 0) print $1;}'>unusedCookbook.txt

for i in `cat $file`
knife cookbook delete "$i" -y

Here unusedCookbook.txt will contain the name of all unused cookbook on chef server. As a result In the script $2==0 will give the list of all unused cookbook. To get all used cookbook names change it to $2!=0 but please test it once without deleting otherwise it will delete all cookbooks which are currently in use

  • Now, to make it executable please do -> chmod +x
  • Now run the script-> ./

To get an overview of chef please visit:-