Attribute used in http_request

Hi Community,

I am new to Chef and am trying to resolve a problem. Basically what I need is to read a value from a local file and set it as a variable which gets used later in a http request as the token.

I have the recipe below.

ruby_block 'Generate Admin token' do
    block do
        Chef::Resource::RubyBlock.send(:include, Chef::Mixin::ShellOut)      
        command = 'cat /tmp/token.txt'
        command_out = shell_out(command)
        node.run_state['admin_token'] = command_out.stdout
    end
end

http_request 'http call' do
    headers lazy {({
      'Content-Type' => 'application/json',
      'api-token' => "#{node.run_state['admin_token']}"
    })}
    action :post
    url "https://xxxx/apis/iam/v2/policies/viewer-access/members:add"
    message ( '{"members": ["team:ldap:xxx"]}' )
end

The HTTP call works well if I assign the token variable outside with a node.default['token'] and use node['token'] inside the header (and without lazy) but does not work as per the code above. The error was a "401 Unauthorized" as the token value is a DelayedEvaluator at compile stage.

I am running the test on Test Kitchen. Please kindly let me know how to get this worked.

Thanks,
Rick

Is there a reason you need the ruby_block? Otherwise I 'd simplify it like:

admin_token = ::File.read('/tmp/token.txt')

http_request 'http call' do
    headers lazy {({
      'Content-Type' => 'application/json',
      'api-token' => admin_token
    })}
    action :post
    url "https://xxxx/apis/iam/v2/policies/viewer-access/members:add"
    message ( '{"members": ["team:ldap:xxx"]}' )
end