Skip to content

Instantly share code, notes, and snippets.

@atheiman
Last active June 11, 2016 18:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atheiman/57ea367e9feb9e298d73e7e42ff07e3d to your computer and use it in GitHub Desktop.
Save atheiman/57ea367e9feb9e298d73e7e42ff07e3d to your computer and use it in GitHub Desktop.
Chef Node Search API
require 'chef'
def config_chef
chef_config_env_var = 'CHEF_CONFIG'
if ENV[chef_config_env_var]
chef_config = ENV[chef_config_env_var]
else
default_chef_configs = ['~/.chef/knife.rb', '/etc/chef/client.rb']
default_chef_configs.each do |c|
if File.exists?(File.expand_path(c))
chef_config = c
break
end
end
end
raise "Could not find Chef config at #{default_chef_configs.join(' or ')}. \
Create one of these or specify another location with env var #{chef_config_env_var}" unless chef_config
# it's easiest to use .from_file to read in chef config from a knife.rb or client.rb
Chef::Config.from_file File.expand_path(chef_config)
end
config_chef
# Chef node search query
search_str = 'chef_environment:dev AND run_list:*base_os*'
nodes = Chef::Search::Query.new.search(
:node,
search_str,
filter_result: { # specify what chef attributes to return, and what the keys should be named
name: ['name'],
hostname: ['hostname'],
fqdn: ['fqdn'],
ip: ['ipaddress'],
environment: ['chef_environment'],
run_list: ['run_list'],
#my_attr: ['path']['to']['deep']['attr']
},
)[0] # the first value in the returned array is the actual search results, rest is pagination data
raise "No nodes returned from search '#{search_str}'" if nodes.empty?
pp nodes
# [{"name"=>"db",
# "hostname"=>"nodeb",
# "fqdn"=>"nodeb.mydomain.net",
# "ip"=>"10.190.124.5",
# "environment"=>"dev",
# "run_list"=>
# ["recipe[base_os]",
# "role[mysql]"]},
# {"name"=>"webserver",
# "hostname"=>"nodea",
# "fqdn"=>"nodea.mydomain.net",
# "ip"=>"10.190.121.82",
# "environment"=>"dev",
# "run_list"=>
# ["recipe[base_os]",
# "role[webserver]"]}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment