Saturday, December 16, 2023

How To Customize Chef Recipes To Compatible With Multiple Chef Client Versions

Metadata.rb is used in Chef to define several important metadata values within the Chef cookbook. Chef infra client version is one of them. The Chef version setting can be used to define the range of chef client versions supported by the cookbook.

For example, the following specifies a match for any chef client version in the16.x series. The configurations defined in Chef recipes will be applied only to servers (nodes) running chef client version 16.x

                chef_version '~> 16.0'

However, even after setting the 'chef_version' for cookbook as shown in the above example, you can still customize your recipes to work with other chef client versions.

This blog explains one possible mechanism for customizing a Chef recipe to run with different versions of Chef clients. 

Pre-requisites: chef workstation, chef cookbook

Let's get started.

Add following sample recipe to the cookbook. This recipe can be used to create folders. if-else conditional blocks have been introduced to customize the recipe for compatibility with different Chef client versions.

  directory "C:/temp/sampleproj" do
    action :create
  end

if (node["chef_packages"]["chef"]["version"] == "17.10.0") then

    directory "C:/temp/chefclientversion17" do
        action :create
    end    
else
    directory "C:/temp/sampleproj/otherchefclientversion" do
        action :create
    end    
end    

   

Recipe reads the Chef client version installed in the node using ["chef_packages"]["chef"]["version"], if Chef-client version of the node is equal to 17.10.0 , a chefclientversion17 folder will be created, otherwise, an otherchefclientversion folder will be created. Similarly, if else conditional blocks can be used to customize recipes based on the Chef client version.

Find Sample code in GitHub

No comments:

Post a Comment