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
- wget https://packages.chef.io/files/stable/chef-workstation/22.1.745/amazon/2/chef-workstation-22.1.745-1.el7.x86_64.rpm
- yum install chef-workstation-22.1.745-1.el7.x86_64.rpm -y
Download starter kit
- Visit https://manage.chef.io/login . 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 https://raw.githubusercontent.com/jbz/knife-audit/master/lib/chef/knife/audit.rb
- 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 deleteUnusedCookbook.sh inside chef-repo directory. Now paste the following code in deleteUnusedCookbook.sh
#!/bin/bash
knife audit | tail -n +2 | awk '{ if($2 == 0) print $1;}'>unusedCookbook.txt
file=unusedCookbook.txt
for i in `cat $file`
do
knife cookbook delete "$i" -y
done
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 deleteUnusedCookbook.sh
- Now run the script-> ./deleteUnusedCookbook.sh
To get an overview of chef please visit:- https://blog.knoldus.com/chef-overview-best-devops-tool-2021/?relatedposts_hit=1&relatedposts_origin=147652&relatedposts_position=0&relatedposts_hit=1&relatedposts_origin=147652&relatedposts_position=0