Search code examples
chef-infraerb

Chef : using search method in a template file


I'm in a Chef template file, to deploy a bash script. I need to retrieve the fqdn of another node, that has a specific role. I tried the following :

#!/bin/bash
[...]
<%- master_servers = search(:node, 'environment_code:#{node.chef_environment} AND roles:master_server') %>
master = "<%=master_servers[0].[fqdn]%>"
[...]

But when deploying, I have this error :

Chef::Mixin::Template::TemplateError (undefined method `search' for #<Chef::Mixin::Template::TemplateContext:0x0000001691c718>) on line #106:

I'm using Chef v12.3.0.
Is the "search" not available to my version ? or am I mis-using it ?

EDIT :
OK, I found a lead : 1st, I'm not supposed to use the "search" in the template file, but in the cookbook, so, I've changed it to this :
In the cookbook file, I have that :

master_servers = search(:node, 'environment_code:#{node.chef_environment} AND roles:master_server')
  template "/opt/tools/export.sh" do
    source "/opt/tools/export.erb"
    variables( 'master_servers ': master_servers)
  end

But when I run that, I have an error during the "chef-client" :

================================================================================
Recipe Compile Error in /var/chef/cache/cookbooks/test1/recipes/export.rb
================================================================================

Net::HTTPServerException
------------------------
400 "Bad Request"

And pointng to this line:

 9>>   master_servers = search(:node, 'environment_code:#{node.chef_environment} AND roles:master_server')

How am I supposed to find my node, and sending it to the template file ?


Solution

  • OK, I've found the right syntax, with my old ruby/chef version :

    master_servers = search(:node, 'environment_code:#{node.chef_environment} AND roles:master_server')
      template "/opt/tools/export.sh" do
        source "/opt/tools/export.erb"
        variables( :master_servers => master_servers)
      end
    

    Then in the template file :

    master_server="<%=@master_servers[0]['fqdn']%>"