Evaluating a ruby variable to be used later in the chef script

I’m trying to evaluate a ruby variable during a recipe to be used in a later resource block, ideally from stdout.

I.e something like…

$GLOBAL_VAR = "not set"
ruby_block 'test' do
          $GLOBAL_VAR = "set"

file 'testfile' do
         content "global_var = #{$GLOBAL_VAR}"

Alas, this always evaluates to “not set”. I’ve tried looking into ‘lazy’ evaluation, but I can’t seem to solve the issue. Any advice?

@dann This sort of thing really lends itself to a helper library. Especially if you’re looking to set the value from stdout. Check out https://docs.chef.io/libraries.html

This is the way I’ve done it:

ruby_block "get master" do
    block do
      Chef::Resource::RubyBlock.send(:include, Chef::Mixin::ShellOut)
      command1 = "redis-cli -h #{sentinel_ip} -p 26379 info | grep -o '[0-9]\\{1,3\\}\\.[0-9]\\{1,3\\}\\.[0-9]\\{1,3\\}\\.[0-9]\\{1,3\\}' && redis-cli -h #{sentinel_ip} -p #{defaultport} -a #{auth} config set #{runtime_config} && redis-cli -h #{sentinel_ip} -p #{defaultport} -a #{auth} config rewrite"
      command_out = shell_out(command1)
      node.run_state['master_ip'] = command_out1.stdout
    action :create

  template "redis.conf" do
    path "/etc/redis.conf"
    source "redis.conf.erb"
    owner node['lc_redis']['user']
    group node['lc_redis']['group']
    mode "0600"
        :node_type => node_type,
        :masterport => node['redis']['defaultport'],
        :masterip => lazy { node.run_state['master_ip'].chomp },
        :maxmemory => node['redis']['maxmemory'],
        :maxmemory_policy => node['redis']['maxmemory_policy'],
        :secret => auth,
        :runtime_config => runtime_config

I hope this helps.