How to create and read a file in the same recipe

I'm confused about the way Chef orders things. I'm trying to read a remote file and put the contents into a variable. So, I tried this:

remote_file "/tmp/tmpfile.txt" do
    source "https://domain.com/tmpfile.txt"
end

foo = File.read('/tmp/tmpfile.txt')

Which fails with "No such file or directory /tmp/tmpfile.txt".

But if I comment out the second part so it just reads

remote_file "/tmp/tmpfile.txt" do
    source "https://domain.com/tmpfile.txt"
end

then the /tmp/tmpfile.txt file is created as expected. I can then add back in the second part, and the recipe proceeds normally.

Why can't I have both lines in the same recipe, and what is the recommended way to deal with this?

Try putting the File.read in a ruby_block.

Thanks. Putting the code inside a ruby_block fixes that problem, but raises another. I'm trying to loop through the input file of IP addresses and create a firewalld rich rule for each address with the firewalld_rich_rule resource from the firewalld cookbook.

But when that resource is called within the ruby_block, it results in

    NoMethodError
    -------------
    undefined method `firewalld_rich_rule' for Chef::Resource::RubyBlock

I've tried calling the firewalld cookbook with include_recipe firewalld, without success.

Is there a way to load a resource inside ruby_block, or another approach to solving the original problem of the file getting created at the end of the run instead of at the beginning?

Well, one way you could do that is to put the recipe as part of a user-written resource, and turn on unified_mode. That way, the code in there (and anything that uses it) will execute in the order supplied, and you won't need the ruby_block.

Ohh thanks a lot for the guidance