Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chef: Can a variable set within one ruby_block be used later in a recipe?

Let's say I have one variable, directory_list, which I define and set in a ruby_block named get_directory_list. Can I use directory_list later on in my recipe, or will the compile/converge processes prevent this?

Example:

ruby_block "get_file_list" do
    block do
        transferred_files = Dir['/some/dir/*']
    end
end

transferred_files.each do |file|
    file "#{file}" do
        group "woohoo"
        user "woohoo"
    end
end
like image 216
grill Avatar asked Oct 06 '15 21:10

grill


1 Answers

Option 1: You could also put your file resource inside the ruby_block.

ruby_block "get_file_list" do
    block do
        files = Dir['/some/dir/*']

        files.each do |f|
            t = Chef::Resource::File.new(f)
            t.owner("woohoo")
            t.group("woohoo")
            t.mode("0600")
            t.action(:create)
            t.run_context=(rc)
            t.run_action(:create)
        end

    end
end

Option 2: You could use node.run_state to pass data around.

ruby_block "get_file_list" do
    block do
        node.run_state['transferred_files'] = Dir['/some/dir/*']
    end
end

node.run_state['transferred_files'].each do |file|
    file "#{file}" do
        group "woohoo"
        user "woohoo"
    end
end

Option 3: If this were just one file, you could declare a file resource with action :nothing, look up the resource from within the ruby_block, and set the filename, and then notify the file resource when the ruby_block runs.

Option 4: If this is the example from IRC today, just place your rsync and the recursive chown inside a single bash resource. rsync and chown are already idempotent, so I don't think it's objectionable in this particular case.

like image 133
Martin Avatar answered Oct 20 '22 23:10

Martin