Search code examples
rubybashchef-infrachef-recipechef-solo

How to use cookbook_file in conjunction with bash?


I am writing a chef recipe using the below logic:

if grep -q -i "release 6" /etc/redhat-release  
then       
  upload **file1** using cookbook_file resource  
else if grep -q -i "release 7" /etc/redhat-release  
then    
  upload **file2** using cookbook_file resource  
fi

Please let me know how a chef recipe with above logic will look like??
What chef resources can I leverage?


Solution

  • Using a cookbook_file resource you're not uploading a file, you're copying it locally as it has benn downloaded with the cookbook on the node (or it can be downloaded 'on-demand', depending on your client.rb configuration.

    The files directory in cookbook_file allow to use file_specificity for this exact use case so in your context your recipe would be only:

    cookbook_file '/path/to/target' do
       source 'my_source_file'
       action :create
    end
    

    And your cookbook files directory would look like this (the file in default will be used when there's no other matching directory, see the full doc in link above):

    cookbook/
    ├── files
    │   └── default
    │       └── my_source_file
    │   └── redhat_6.4
    │       └── my_source_file
    │   └── redhat_7.1
    │       └── my_source_file
    

    If you really want to use only the major version then you can remove the minor in the directory structure and use the Ohai attributes in the source property like this (use double quotes for interpolation of variables):

    cookbook_file '/path/to/target' do
       source "#{node[platform]}-#{node[platform_version][/(\d).\d/,1]}/my_source_file"
       action :create
    end