user3540835
user3540835

Reputation: 453

How to delay the execution of search mechanism in a chef recipe till run time

How to delay the execution of search mechanism in a chef recipe till run time.

I want to make sure that the execution of below code is delayed till run-time.

node = search(:node, "chef_environment:#{node.chef_environment} AND (role:A)")
result = node[:hostname]

I have a scenario where above code is part of recipe say 'search_recipe' which is in the runlist of three roles 'A', 'B' , 'C'.

When role B and C are applied to a node 'search_recipe' is able to fetch the hostname , however when it runs as part of role A it fails at compile time as at compile time there is no node which is available with role A , role for the node is getting reflected only after the recipe execution starts.

I have tried using lazy and lambda blocks but it did not help me out.

Upvotes: 0

Views: 597

Answers (1)

coderanger
coderanger

Reputation: 54249

Search will never find the current node on its first converge as the node data isn't sent back to the chef server until after a successful run. You can work around this by manually checking the current node when applicable:

my_servers = []
search(:node,  "chef_environment:#{node.chef_environment} AND roles:A") do |n|
  my_servers << n['hostname']
end
if node['roles'].include?('A') && !my_servers.includes?(node['hostname'])
  my_servers << node['hostname']
end

Upvotes: 1

Related Questions