ruby - access updated node attributes in cookbook recipe -


i new chef environment. , working on simple cookbook.

to simplify, have following attributes in:

attributes/default.rb:

default[:user1] = "" default[:user2] = "" default[:filename] = "" 

recipes/default.rb: @ run time, filename cookbook , have extract users file.

file = "#{node[:filename]}"  ruby_block 'extract userdata'   block     json = file.read(file)     obj = json.parse(json)      userdata = obj['users']      if userdata.empty?       raise "errors: userdata not available"     else       node.override[:user1] = userdata['user1']       node.override[:user2] = userdata['user2']     end   end   puts "user1: #{node[:user1]}"   puts "user2: #{node[:user2]}"   action :run end 

logs (puts) above block @ runtime fetch me usernames correctly.

now, trying use above 2 updated attributes below in further down cookbook recipe.

user1 = #{node[:user1]} user2 = #{node[:user2]} 

but these 2 values coming out empty if not set/overriden.

please suggest how can updated data.

i'll summarize following answers (which gives views on same problem) , gives example on specific case.


you're problem here compile time versus converge time

what happens here recipe , resources evaluated @ compile time , content of ruby_block resource evaluated @ converge time.

there's 2 solutions around this:

  • first option run ruby_block @ compile time:

    ruby_block 'extract userdata'   block     json = file.read(file)     obj = json.parse(json)      userdata = obj['users']      if userdata.empty?       raise "errors: userdata not available"     else       node.override[:user1] = userdata['user1']       node.override[:user2] = userdata['user2']     end   end   puts "user1: #{node[:user1]}"   puts "user2: #{node[:user2]}"   action :nothing end.run_action(:run) 

    notice action :nothing avoid resource executed @ converge time , .run_action(:run) tell evaluation run resource it's evaluated.

  • second option use lazy evaluation in other resources this:

    execute "do something"   command lazy { "/path/command #{node['user1]}" } end 

    the lazy {} has encompass whole attribute value, not variable or throw error.

i advise preferably use option 2 as possible. doing things @ compile time end in difficult run understand when goes wrong actions taken in 2 different flows.

i recommend using string access node attributes, single quoted when fixed text, double quoted when need interpolation symbols can unexpected behaviors if attribute name match existing symbol in recipe dsl namespace.


Comments

Popular posts from this blog

php - Admin SDK -- get information about the group -

Python Error - TypeError: input expected at most 1 arguments, got 3 -

dns - How To Use Custom Nameserver On Free Cloudflare? -