How to use a Ruby block to assign variables in chef recipe
Asked Answered
F

1

5

I am trying to execute Ruby logic on the fly in a Chef recipe and believe that the best way to achieve this is with a block.

I am having difficulty transferring variables assigned inside the block to the main code of the chef recipe. This is what I tried:

ruby_block "Create list" do
  block do
    to_use ||= []
    node['hosts'].each do |host|
      system( "#{path}/command --all" \
              " | awk '{print $2; print $3}'" \
              " | grep #{host} > /dev/null" )
      unless $? == 0
        to_use << host
      end
    end
    node['hosts'] = to_use.join(',')
  end
  action :create
end

execute "Enable on hosts" do
  command "#{path}/command --enable -N #{node['hosts']}"
end

Rather than try to re-assign the chef attribute on the fly, I also tried to create new variables in the block but still can't find a way to access them in the execute statement.

I was originally using a class and calling methods however it was compiled before the recipe and I really need the logic to be executed at runtime, during the recipe.

Federative answered 24/5, 2015 at 13:48 Comment(2)
The best chef receipes are idpotent, so executing ruby logic on the fly is not generally a good idea. What exactly are you trying to do?Caecum
node['hosts'].select! would modify it inplace.Unvoice
S
7

Your problem is compile time versus converge time. Your block will be run at converge time but at this time the node['host'] in the execute resource has already been evaluated.

The best solution in this case would be to use lazy evaluation so the variable will be expanded when the resource is converged instead of when it is compiled:

execute "Enable on hosts" do
  command lazy { "#{path}/command --enable -N #{node['hosts']}" }
end

Here's a little warning though, the lazy operator has to include the full command attribute text and not only the variable, it can work only as first keyword after the attribute name.

Speciation answered 26/5, 2015 at 9:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.