Search code examples
chef-infrachef-recipecookbook

How to use node attributes in a shell script in CHEF recipe


I have created a new CHEF Cookbook and in the attributes folder i have added the following value to the default attribute.rb file ******** node.default['main']['a2'] = "hello world" ******** In the chef recipe i would like to echo or create a new file with the name "hello world"

The recipe has the following lines:

Cookbook Name:: a2

# Recipe:: default<br>
#<br>
# Copyright (c) 2018 The Authors, All Rights Reserved.<br>
execute 'just_test' do <br>
command 'touch /tmp/a2345' <br>
end <br>
execute 'just_test1' do <br>
command "touch /tmp/node['main']['a2']" <br>
end <br>
execute 'just_test2' do <br>
command "echo node['main']['a2']" <br>
end <br>

Although the recipe is successful, i do not see a file with "hello world"

recipe: a2::default
* execute[just_test] action run
- execute touch /tmp/a2345
* execute[just_test1] action run
- execute touch /tmp/node['main']['a2']
* execute[just_test2] action run
- execute echo node['main']['a2']
[2018-04-03T15:52:18+00:00] WARN: Skipping final node save because override_runlist was given

In the tmp directory the following files are created

a2345 node[main][a2]

How can we do attribute substitution in CHEF recipe??? Are there alternative to achieve this functionality

Thank you


Solution

    1. You should not use execute to create an empty file, use file resource.
    2. Chef is written in Ruby and follows Ruby string interpolation. So, in your case it should be "touch /tmp/#{node['main']['a2']}" - outer double quotes are important.
    3. Have you tried to go through our official documentation?. You could learn there about this and other useful 'cases'.