How to pass value from one resource to another resource in a chef's recipe?
I am trying to change an attribute in one resource and I want to use the updated value in another resource, but the updated value is not reflected in other resources. Please help me
code
node[:oracle][:asm][:disks].each_key do |disk|
Chef::Log.info("I am in #{cookbook_name}::#{recipe_name} and current disk count #{node[:oracle][:asm][:test]}")
bash "beforeTest" do
code <<-EOH
echo #{node[:oracle][:asm][:test]}
EOH
end
ruby_block "test current disk count" do
block do
node.set[:oracle][:asm][:test] = "#{node[:oracle][:asm][:test]}".to_i+1
end
end
bash "test" do
code <<-EOH
echo #{node[:oracle][:asm][:test]}
EOH
end
end
The value I am trying to update is the value stored in node[:oracle][:asm][:test]
Your problem is that the variable code
is being set at compile time by the chef, before the ruby block changes the value of your attribute. You need to add a lazy initializer around your code.
Chef::Log.info("I am in #{cookbook_name}::#{recipe_name} and current disk count #{node[:oracle][:asm][:test]}")
bash "beforeTest" do
code lazy{ "echo #{node[:oracle][:asm][:test]}" }
end
ruby_block "test current disk count" do
block do
node.set[:oracle][:asm][:test] = "#{node[:oracle][:asm][:test]}".to_i+1
end
end
bash "test" do
code lazy{ "echo #{node[:oracle][:asm][:test]}" }
end
The first block is really not needed lazy, but I threw it there just in case the value changes elsewhere too.
Lazy is good, but here's another approach. You can use it node.run_state
for your own purposes.
Here is an example using https://docs.chef.io/recipes.html
package 'httpd' do
action :install
end
ruby_block 'randomly_choose_language' do
block do
if Random.rand > 0.5
node.run_state['scripting_language'] = 'php'
else
node.run_state['scripting_language'] = 'perl'
end
end
end
package 'scripting_language' do
package_name lazy { node.run_state['scripting_language'] }
action :install
end