Search code examples
chef-infra

how to set node attribute value from execute resouce command output


execute 'my_commad' do
  command 'myvar=`curl http://example.com/blah/blah` && echo -n $myvar > /etc/value'
end

node.default[:attribute1] = ::File.read('/etc/value').chomp

This will fail, because at the time of convergence the node attributes are checked first and hence it will throw the following error:

ERROR: No such file or directory @ rb_sysopen - /etc/value


Solution

  • if you are setting the node attribute at the recipe itself and not in an attribute file, this might work for you. though, in my opinion, there is a better way to do so...

    you can use ruby_block and use ruby code to fetch the value that you need from the url and then assign it to a node attribute. it will be something like:

    ruby_block 'fetch value' do
      block do
        require 'net/http'
        require 'uri'
    
        url = 'http://example.com/blah/blah'
        val = Net::HTTP.get(URI.parse(url))
        node.default[:attribute1] = val
    end
    

    just make sure that every read for the attribute1 node attribute, is taking place after it was assigned. you might need to rearrange the node run-list to make sure that all recipes that depend on this recipe, will be appear in the node run-list after the recipe above was executed.